A Chaptered Guide to SELECT, From One Table to Grouped Results
SELECT is the statement you will write most often. This web guide builds it up chapter by chapter, adding one clause at a time, using a single small table so the changes are easy to see.
The practice table
CREATE TABLE songs (
id INTEGER PRIMARY KEY,
title TEXT NOT NULL,
artist TEXT NOT NULL,
year INTEGER,
plays INTEGER DEFAULT 0
);
Add ten or so rows of your own favourite songs before you start.
Chapter 1: choosing columns
SELECT title, artist FROM songs;
List the columns you want, separated by commas. SELECT * gives all columns, handy for exploring.
Chapter 2: filtering with WHERE
SELECT title FROM songs WHERE year >= 2020;
Combine conditions with AND and OR, and use brackets to make the meaning clear:
SELECT title FROM songs WHERE (artist = 'Nina' OR artist = 'Omar') AND year >= 2020;
Chapter 3: sorting with ORDER BY
SELECT title, plays FROM songs ORDER BY plays DESC;
DESC means largest first; ASC, the default, means smallest first. Without ORDER BY, the database may return rows in any order.
Chapter 4: limiting results
SELECT title, plays FROM songs ORDER BY plays DESC LIMIT 5;
The five most played songs. (SQL Server uses TOP or OFFSET ... FETCH instead of LIMIT.)
Chapter 5: calculated columns and aliases
SELECT title, plays * 3 AS estimated_minutes FROM songs;
AS gives the result column a friendly name.
Chapter 6: counting and totals
Aggregate functions summarise many rows into one value:
SELECT COUNT(*) AS songs, SUM(plays) AS total_plays FROM songs;
Others include AVG, MIN and MAX.
Chapter 7: grouping
SELECT artist, COUNT(*) AS songs
FROM songs
GROUP BY artist
ORDER BY songs DESC;
GROUP BY makes one result row per artist. Every selected column must either be in GROUP BY or be inside an aggregate function.
Chapter 8: filtering groups with HAVING
SELECT artist, COUNT(*) AS songs
FROM songs
GROUP BY artist
HAVING COUNT(*) >= 2;
WHERE filters rows before grouping; HAVING filters groups after.
Chapter 9: one join
Add an artists table and link it:
SELECT s.title, a.country
FROM songs s
JOIN artists a ON a.name = s.artist;
Real designs would link with an id, as described in our complete read on keys.
The order clauses must appear in
| Position | Clause |
|---|---|
| 1 | SELECT |
| 2 | FROM (and JOIN) |
| 3 | WHERE |
| 4 | GROUP BY |
| 5 | HAVING |
| 6 | ORDER BY |
| 7 | LIMIT |
Where next
Try our visual query builder to assemble SELECT statements by clicking, then read the SQL it produces. Writing the same query by hand afterwards is excellent practice.
A free learning page for beginners. Practise on a test database, never on real customer data, and check the official documentation for your database version.
This page is a free outline. No downloadable files, paid content, courses or certificates are offered on this site.