简体   繁体   中英

SQL order a result set based on a column value

I am using mysql, is there a way we can order the result set based on the value of a column.

I want the rows to be in the end or beginning of the result where

col = 'SOMEVALUE'

If my question is not clear, consider the following scenario:

I have a surveys table, that has a status column, I want to get all surveys, but the ones with status = 'Expired' need to be at the end of the result set.

Is there an SQL way of doing this? or I need to sort the result manually after retrieval?

You can use an expression in the order by . In MySQL, this is particularly simple:

order by (status = 'Expired') asc,  -- put status at the end
         status  -- or however you want the rows ordered.

This works because MySQL treats a boolean expression as a number in a numeric context, with 1 for "true" and 0 for "false".

If you have more column value then you can use case in the sorting.

or you can use this also.

CREATE TABLE kaka
(
ID INT NOT NULL AUTO_INCREMENT PRIMARY KEY, 
col_2 VARCHAR(200)
);

INSERT INTO kaka(col_2) VALUES
('a'),
('v'),
('x'),
('aa')


SELECT col_2, CASE col_2 WHEN 'x' THEN 1 WHEN 'aa' THEN 2 WHEN 'v' THEN 3 ELSE 4 END sort
FROM kaka
ORDER BY sort

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM