Mikael
Mikael

Reputation: 5489

Select all and give random output (Random sorted output)

I have a table looking something like this

ID Name City 
-------------
0  asd  sda
1  hrs  gsh
2  ghd  0
3  hsa  0
.
.

How could I return city != '0' in random order and then city = '0' in random order?

Upvotes: 1

Views: 127

Answers (2)

gbn
gbn

Reputation: 432321

For SQL Server (RAND gives same value for all rows in SQL Server)

ORDER BY
    CASE WHEN City <> '0' THEN 1 ELSE 2 END,
    NEWID()

Upvotes: 1

Jonathan Leffler
Jonathan Leffler

Reputation: 754140

Assuming your DBMS supports a RAND function that returns a different random number for each row in your result set:

SELECT ID, Name, City
  FROM SomethingLikeThis
 ORDER BY CASE WHEN City = 0 THEN 1 ELSE 0 END, RAND();

Upvotes: 1

Related Questions