Sorting results

Sorting results in SQL

Sorting results can be achieved by using a modifier command at the end of the SQL querry

#load the extension
%load_ext sql 
#connect to the database
%sql sqlite:///mydatabase.db 
'Connected: @mydatabase.db'

The results can be sorted with the command ORDER BY

SELECT column-list FROM table_name [WHERE condition] [ORDER BY column1, column2, .. columnN] [ASC | DESC]

Let's show an example where we extract the fruits that are either yellow or red

%sql SELECT * FROM tutyfrutty WHERE color = "yellow" OR color = "red" 
 * sqlite:///mydatabase.db
Done.
index fruit color kcal
0 Banana yellow 89
2 Apple red 52
3 lemon yellow 15
7 Cranberry red 308

Ascending sort

%sql SELECT * FROM tutyfrutty WHERE color = "yellow" OR color = "red" ORDER BY kcal ASC
 * sqlite:///mydatabase.db
Done.
index fruit color kcal
3 lemon yellow 15
2 Apple red 52
0 Banana yellow 89
7 Cranberry red 308

descending sort

%sql SELECT * FROM tutyfrutty WHERE color = "yellow" OR color = "red" ORDER BY kcal DESC
 * sqlite:///mydatabase.db
Done.
index fruit color kcal
7 Cranberry red 308
0 Banana yellow 89
2 Apple red 52
3 lemon yellow 15

Sort by multiple columns

You can sort by more than one column. Just specify multiple columns in the ORDER BY keyword. In the example, we will sort alphabetically on the color column first and sort alphabetically on the fruit column

%sql SELECT * FROM tutyfrutty ORDER BY color, fruit ASC
 * sqlite:///mydatabase.db
Done.
index fruit color kcal
4 lime green 30
1 Orange orange 47
5 plum purple 28
2 Apple red 52
7 Cranberry red 308
0 Banana yellow 89
3 lemon yellow 15