Contents / Previous / Next


Sorting Data with ORDER BY

In a SELECT query, rows are displayed in an undetermined order.
To guarantee that the rows will be returned from SELECT in a specific order,
you must add the ORDER BY clause to the end of the SELECT. SELECT * FROM table WHERE condition ORDER BY column [ DESC ] Example: > SELECT * FROM stud ORDER BY gender; id | name | semester | diploma | gender ----+------+----------+---------+----- 2 | lisa | 2 | bio | f 1 | fred | 2 | bio | m 3 | tom | 1 | bio | m 4 | john | 3 | phy | m
You can reverse the order by adding DESC: > SELECT * FROM stud ORDER BY semester DESC; id | name | semester | diploma | gender ----+------+----------+---------+----- 4 | john | 3 | phy | m 2 | lisa | 2 | bio | f 1 | fred | 2 | bio | m 3 | tom | 1 | bio | m
You can additionally use a WHERE condition (ORDER BY appears after the WHERE clause): > SELECT * FROM stud WHERE diploma='bio' ORDER BY gender; id | name | semester | diploma | gender ----+------+----------+---------+----- 2 | lisa | 2 | bio | f 1 | fred | 2 | bio | m 3 | tom | 1 | bio | m
You can ORDER BY more than one column by specifying multiple columns separated by commas (priority as listed): > SELECT * FROM stud WHERE diploma='bio' ORDER BY gender, semester; id | name | semester | diploma | gender ----+------+----------+---------+----- 2 | lisa | 2 | bio | f 3 | tom | 1 | bio | m 1 | fred | 2 | bio | m