tags:

views:

42

answers:

5

I have a table with an id as the primary key, and a description as another field.

I want to first select the records that have the id<=4, sorted by description, then I want all the other records (id>4), sorted by description. Can't get there!

+2  A: 
select *, id<=4 as low from table order by low, description
Scott Saunders
This is fine, even if it returns a not-needed column (low)
vulkanino
+1  A: 

You may want to use an id <= 4 expression in your ORDER BY clause:

SELECT * FROM your_table ORDER BY id <= 4 DESC, description;

Test case (using MySQL):

CREATE TABLE your_table (id int, description varchar(50));

INSERT INTO your_table VALUES (1, 'c');
INSERT INTO your_table VALUES (2, 'a');
INSERT INTO your_table VALUES (3, 'z');
INSERT INTO your_table VALUES (4, 'b');
INSERT INTO your_table VALUES (5, 'g');
INSERT INTO your_table VALUES (6, 'o');
INSERT INTO your_table VALUES (7, 'c');
INSERT INTO your_table VALUES (8, 'p');

Result:

+------+-------------+
| id   | description |
+------+-------------+
|    2 | a           |
|    4 | b           |
|    1 | c           |
|    3 | z           |
|    7 | c           |
|    5 | g           |
|    6 | o           |
|    8 | p           |
+------+-------------+
8 rows in set (0.00 sec)

Related post:

Daniel Vassallo
+4  A: 
select id, descr
from t
order by 
 case when id <= 4 then 0 else 1 end, 
 descr
GSerg
+1 I like this, my first thought for stuff like this is always UNION instead of thinking of the slicker solution.
kekekela
Why not just `ORDER BY id <= 4 DESC, descr`? ... The comparison operators already return `0` or `1`.
Daniel Vassallo
@Daniel: Because initially OP didn't say anything about the database. This trick might be valid in mysql (I believe it's an extension?), but, for instance, in MS SQL Server the result of a comparison is a boolean value which cannot be used this way, therefore a `case` is a must.
GSerg
@GSerg: Oh, you're right. I see that the `[mysql]` tag was added later. Yes it won't work in SQL Server, but in MySQL, the `ORDER BY` syntax allows any valid expression... Anyway +1 as yours is more portable.
Daniel Vassallo
+1  A: 
select id, description
from MyTable
order by case when id <= 4 then 0 else 1 end, description
RedFilter
+1  A: 

You can use UNION

SELECT * FROM (SELECT * FROM table1 WHERE id <=4 ORDER by description)aaa
UNION
SELECT * FROM (SELECT * FROM table1 WHERE id >4 ORDER by description)bbb

OR

SELECT * FROM table1
ORDER BY
CASE WHEN id <=4 THEN 0
ELSE 1
END, description
a1ex07
the first one doesn't work because of the ORDER BY before the UNION (MySQl). second one is fine.
vulkanino
Oops, my bad.. Union version fixed.
a1ex07