Title: Sorting
Slug: sorting
Summary: Sorting in SQL. Date: 2017-01-16 12:00
Category: SQL
Tags: Basics
Authors: Chris Albon

Note: This tutorial was written using Catherine Devlin's SQL in Jupyter Notebooks library. If you have not using a Jupyter Notebook, you can ignore the two lines of code below and any line containing %%sql. Furthermore, this tutorial uses SQLite's flavor of SQL, your version might have some differences in syntax.

For more, check out Learning SQL by Alan Beaulieu.


In [1]:
# Ignore
%load_ext sql
%sql sqlite://
%config SqlMagic.feedback = False

Create Data


In [2]:
%%sql

-- Create a table of criminals
CREATE TABLE criminals (pid, name, age, sex, city, minor);
INSERT INTO criminals VALUES (412, 'James Smith', 15, 'M', 'Santa Rosa', 1);
INSERT INTO criminals VALUES (234, 'Bill James', 22, 'M', 'Santa Rosa', 0);
INSERT INTO criminals VALUES (632, 'Stacy Miller', 23, 'F', 'San Francisco', 0);
INSERT INTO criminals VALUES (901, 'Gordon Ado', 32, 'F', 'San Francisco', 0);
INSERT INTO criminals VALUES (512, 'Bill Byson', 21, 'M', 'Petaluma', 0);


Out[2]:
[]

View All Rows


In [3]:
%%sql

--  Select all
SELECT *

-- From the criminals table
FROM criminals


Out[3]:
pid name age sex city minor
412 James Smith 15 M Santa Rosa 1
234 Bill James 22 M Santa Rosa 0
632 Stacy Miller 23 F San Francisco 0
901 Gordon Ado 32 F San Francisco 0
512 Bill Byson 21 M Petaluma 0

Sort By Ascending Age


In [4]:
%%sql

--  Select all unique
SELECT distinct *

-- From the criminals table
FROM criminals

-- Sort by ascending age
ORDER BY age ASC


Out[4]:
pid name age sex city minor
412 James Smith 15 M Santa Rosa 1
512 Bill Byson 21 M Petaluma 0
234 Bill James 22 M Santa Rosa 0
632 Stacy Miller 23 F San Francisco 0
901 Gordon Ado 32 F San Francisco 0

Sort By Descending Age


In [5]:
%%sql

--  Select all unique
SELECT distinct *

-- From the criminals table
FROM criminals

-- Sort by descending age
ORDER BY age DESC


Out[5]:
pid name age sex city minor
901 Gordon Ado 32 F San Francisco 0
632 Stacy Miller 23 F San Francisco 0
234 Bill James 22 M Santa Rosa 0
512 Bill Byson 21 M Petaluma 0
412 James Smith 15 M Santa Rosa 1

Sort Alphabetically


In [6]:
%%sql

--  Select all unique
SELECT distinct *

-- From the criminals table
FROM criminals

-- Sort by name
ORDER BY name


Out[6]:
pid name age sex city minor
512 Bill Byson 21 M Petaluma 0
234 Bill James 22 M Santa Rosa 0
901 Gordon Ado 32 F San Francisco 0
412 James Smith 15 M Santa Rosa 1
632 Stacy Miller 23 F San Francisco 0