Find a course

Module 1: Databases and Your First QueriesLesson 2 of 1113 min

Your First SELECT: Columns, Sorting and Limits

Write SELECT queries that choose columns, rename them with AS, remove duplicates with DISTINCT, sort with ORDER BY and return only the top rows.

Step 1 of 15Learn

Meet the books table

Here is the complete books table you'll query in this lesson and the ones that follow. It's small on purpose, so you can check every result by eye.

book_idtitleauthorgenrepriceyearstock
1The Silent OrbitMara QuinnSci-Fi18.00201912
2Gardens of SaltLeo ParkFiction15.5020210
3Data in PracticeAna RuizTech42.0020227
4Night FerryLeo ParkMystery12.99201725
5Learning to CookSam OdellFood24.0020203
6The Last SignalMara QuinnSci-Fi21.0020239
7Quiet NumbersAna RuizTech35.002018NULL
8River RoadJo BanksFiction14.00201618

The simplest query returns everything:

SELECT *
FROM books;

The asterisk means "all columns." The query returns all 8 rows and all 7 columns. Two clauses appear in almost every query you'll write:

  • SELECT lists the columns you want.
  • FROM names the table they come from.

SELECT * is handy for a first look at an unfamiliar table, but in real work you should name the columns you need. Real tables can have dozens of columns and millions of rows; pulling everything is slow, wastes network bandwidth, and can break reports when someone adds a column later.

SELECT title, author, price
FROM books;

This returns 8 rows with only three columns, in the order you listed them. Columns are separated by commas, with no comma after the last one, a classic beginner error that produces a syntax error.

Notice that SQL returns a result set that is itself a table: rows and columns. That's why you can later feed one query's result into another.

Step 2 of 15Practice · Chart

Price of each book in the books table

ORDER BY price ASC LIMIT 1 would return which book? Tap its bar.

Tap the bar that answers the question, then press Check.

Price of each book in the books tableBar chart with 8 categories: The Silent Orbit: $18; Gardens of Salt: $15.5; Data in Practice: $42; Night Ferry: $12.99; Learning to Cook: $24; The Last Signal: $21; Quiet Numbers: $35; River Road: $14.$0$10$20$30$40$50PriceThe SilentOrbitGardensof SaltData inPracticeNightFerryLearningto CookThe LastSignalQuietNumbersRiverRoad$18$15.5$42$12.99$24$21$35$14
Data from the course's sample books table.
Price of each book in the books table
ItemPrice
The Silent Orbit$18
Gardens of Salt$15.5
Data in Practice$42
Night Ferry$12.99
Learning to Cook$24
The Last Signal$21
Quiet Numbers$35
River Road$14

Step 3 of 15Practice · Work it out

Using the books table above, how many rows does this query return? SELECT title, price FROM books;

Step 4 of 15Note

Step 5 of 15Learn

Aliases, calculations and DISTINCT

You can rename columns in the result with AS, which creates an alias:

SELECT title AS book_title, price AS list_price
FROM books;

The table is unchanged; only the result's column headings differ. Aliases make reports readable and are essential when you compute new values:

SELECT title, price, price * 0.9 AS sale_price
FROM books;

For "The Silent Orbit," sale_price is 18.00 × 0.9 = 16.20. You can use the arithmetic operators +, −, * and /, and combine columns, as in price * stock AS stock_value. In standard SQL, if an alias contains spaces you must quote it with double quotes, so most people stick to underscores.

DISTINCT removes duplicate rows from the result:

SELECT DISTINCT author
FROM books;

The table has 8 books but only 5 distinct authors: Mara Quinn, Leo Park, Ana Ruiz, Sam Odell and Jo Banks. DISTINCT applies to the whole row of selected columns, not just the first column. SELECT DISTINCT author, genre returns each unique combination. Here it also returns 5 rows, because each author writes in only one genre; if Leo Park had also written a Sci-Fi book, that would be a separate row.

A quick way to answer "what values appear in this column?", such as which genres you carry, is SELECT DISTINCT genre FROM books;.

Step 6 of 15Practice · Code challenge · SQL

Code challenge · SQL

Write a query that returns only the title and price of every book, in that column order.

The starter query returns every column. Change it so the result has exactly two columns and all 8 rows.

The database for this exercise (tables and rows)
CREATE TABLE books (
  book_id INTEGER PRIMARY KEY,
  title   TEXT NOT NULL,
  author  TEXT NOT NULL,
  genre   TEXT,
  price   REAL,
  year    INTEGER,
  stock   INTEGER
);
INSERT INTO books VALUES
  (1, 'The Silent Orbit',  'Mara Quinn', 'Sci-Fi',  18.00, 2019, 12),
  (2, 'Gardens of Salt',   'Leo Park',   'Fiction', 15.50, 2021, 0),
  (3, 'Data in Practice',  'Ana Ruiz',   'Tech',    42.00, 2022, 7),
  (4, 'Night Ferry',       'Leo Park',   'Mystery', 12.99, 2017, 25),
  (5, 'Learning to Cook',  'Sam Odell',  'Food',    24.00, 2020, 3),
  (6, 'The Last Signal',   'Mara Quinn', 'Sci-Fi',  21.00, 2023, 9),
  (7, 'Quiet Numbers',     'Ana Ruiz',   'Tech',    35.00, 2018, NULL),
  (8, 'River Road',        'Jo Banks',   'Fiction', 14.00, 2016, 18);
Real SQLite, running in your browser on a fresh copy of the database.
  • Result matches the expected table

Step 7 of 15Practice · Work it out

Using the books table, how many rows does this query return? SELECT DISTINCT genre FROM books;

Step 8 of 15Learn

Sorting with ORDER BY and limiting rows

Without ORDER BY, a database makes no promise about row order. Results often appear in insertion order, but that can change at any time as data grows or the database picks a different plan. If order matters, say so:

SELECT title, price
FROM books
ORDER BY price;

Sorting is ascending (ASC) by default: smallest to largest, A to Z, oldest to newest date. Add DESC for descending:

SELECT title, price
FROM books
ORDER BY price DESC;

You can sort by several columns. The second column breaks ties in the first:

SELECT title, author, year
FROM books
ORDER BY author ASC, year DESC;

This groups books alphabetically by author and, within each author, lists the newest first.

To return only the first few rows, most databases (PostgreSQL, MySQL, SQLite) use LIMIT:

SELECT title, price
FROM books
ORDER BY price DESC
LIMIT 3;

This returns the three most expensive books: Data in Practice (42.00), Quiet Numbers (35.00) and Learning to Cook (24.00). SQL Server writes SELECT TOP 3 ... instead, and the SQL standard and Oracle use FETCH FIRST 3 ROWS ONLY.

Always pair LIMIT with ORDER BY. "The first 3 rows" means nothing without an order; "the 3 most expensive" is a real question.

For pagination, OFFSET skips rows: LIMIT 10 OFFSET 20 returns rows 21 to 30.

Step 9 of 15Practice · Diagram

Anatomy of a sorted, limited query

Each clause has one job. Tap a box to see what it does in SELECT title, price FROM books ORDER BY price DESC LIMIT 3;

Which clause decides that the three rows kept are the most expensive ones rather than any three?

Tap the shape that answers the question, then press Check.

Anatomy of a sorted, limited queryProcess diagram: SELECT title, price → FROM books → ORDER BY price DESC → LIMIT 3.SELECTtitle, priceFROM booksORDER BYprice DESCLIMIT 3
SELECT title, price

Chooses which columns appear in the result.

FROM books

Names the table the rows come from.

ORDER BY price DESC

Sorts rows from most to least expensive. Without ORDER BY, the order is not guaranteed.

LIMIT 3

Keeps only the first 3 rows of the sorted result: Data in Practice, Quiet Numbers, Learning to Cook.

Step 10 of 15Practice · Code challenge · SQL

The starter lists the author of every book, so some names appear twice. Change it so each author appears only once (5 rows).

The database for this exercise (tables and rows)
CREATE TABLE books (
  book_id INTEGER PRIMARY KEY,
  title   TEXT NOT NULL,
  author  TEXT NOT NULL,
  genre   TEXT,
  price   REAL,
  year    INTEGER,
  stock   INTEGER
);
INSERT INTO books VALUES
  (1, 'The Silent Orbit',  'Mara Quinn', 'Sci-Fi',  18.00, 2019, 12),
  (2, 'Gardens of Salt',   'Leo Park',   'Fiction', 15.50, 2021, 0),
  (3, 'Data in Practice',  'Ana Ruiz',   'Tech',    42.00, 2022, 7),
  (4, 'Night Ferry',       'Leo Park',   'Mystery', 12.99, 2017, 25),
  (5, 'Learning to Cook',  'Sam Odell',  'Food',    24.00, 2020, 3),
  (6, 'The Last Signal',   'Mara Quinn', 'Sci-Fi',  21.00, 2023, 9),
  (7, 'Quiet Numbers',     'Ana Ruiz',   'Tech',    35.00, 2018, NULL),
  (8, 'River Road',        'Jo Banks',   'Fiction', 14.00, 2016, 18);
Real SQLite, running in your browser on a fresh copy of the database.
  • Result matches the expected table

Step 11 of 15Practice · Put in order

Put the clauses of this query in the order SQL requires you to write them.

Drag the items, or use the arrow buttons, to put them in order.

  1. FROM books
  2. ORDER BY price DESC
  3. LIMIT 5
  4. SELECT title, price

Step 12 of 15Try the calculator

Pagination with LIMIT and OFFSET

Websites show long lists one page at a time. Enter a page size and page number to see the LIMIT and OFFSET values a query would use.

LIMIT
20
OFFSET (rows to skip)
40
First row number shown
41
Last row number shown
60

Step 13 of 15Practice · Spot the mistake

This query should list the titles and prices of the 3 cheapest books. Which lines contain mistakes? Click them.

Step 14 of 15Note

Step 15 of 15Practice · Choose one

Which query returns the titles of the two newest books in the table?