Courses3 levels
Level 1 · Foundations11 courses
Level 2 · Core5 courses
Level 3 · Advanced5 courses
Labs8 topics
Library Practice exams AI Range Pricing Start free

Practice library / More programming languages

Workbook · Easy · 4 hours

SQL Fundamentals

Build and query a small SQLite database: tables, filtering, sorting, joins and aggregation.

  • sql
  • sqlite
  • joins
  • aggregation
  • databases
On this page 12 sections
  1. ·Chapter 1 — What a Database Is, and What SQL Does
  2. ·Chapter 2 — Installing and Using SQLite
  3. ·Chapter 3 — Creating Tables and Choosing Data Types
  4. ·Chapter 4 — Inserting Data
  5. ·Chapter 5 — Selecting and Projecting Columns
  6. ·Chapter 6 — Filtering with WHERE
  7. ·Chapter 7 — Sorting and Limiting Results
  8. ·Chapter 8 — Updating and Deleting Rows Safely
  9. ·Chapter 9 — Aggregate Functions and GROUP BY
  10. ·Chapter 10 — Joining Tables
  11. ·Chapter 11 — Subqueries and Views
  12. ·Chapter 12 — Worked Project: Query a Small Library Database

SQL is the common language of stored data. Most web applications, log pipelines and analytics stacks query a relational database, and the security work that follows depends on being able to read those queries without guessing. This workbook teaches SQL from zero on SQLite, a file-based engine that needs no server. It covers tables and types, insert and update, filtering, sorting, joins across tables, aggregation and grouping, subqueries and views. One running library database carries the examples from chapter to chapter so each new idea builds on the last. By the end you can read common SELECT statements and write the one you need.

No installation needed. Open sqliteonline.com in a browser and type SQL directly. To install SQLite instead, run sudo apt install sqlite3.

This workbook uses one running example: a small library database with three tables (books, members, loans). Each chapter adds a skill. Type every example yourself. Each chapter ends with practice questions. Answer them before you open the <details> block.

Chapter 1 — What a Database Is, and What SQL Does

Chapter Objectives

  • Explain what a relational database stores and why
  • Name a table, a row and a column
  • List the four SQL statement groups and what each one does
  • Say why SQL, not a spreadsheet, suits large or shared data

A database stores data so a program can find, change and trust it later. A relational database stores data in tables. A table has columns (the fields, fixed in advance) and rows (one record each).

idtitleauthoryear
1Clean CodeRobert Martin2008
2The Pragmatic ProgrammerAndrew Hunt1999

This table has four columns and two rows. Each row is one book. SQL (Structured Query Language) is the language that creates tables, puts rows in and takes them out again. Almost every application that remembers data between visits stores it in a database, and SQL is the common way to reach one.

SQL statements fall into four groups:

GroupNameDoes
DDLData Definition LanguageCreates and changes the shape of a table: CREATE, DROP, ALTER
DMLData Manipulation LanguageChanges the rows inside a table: INSERT, UPDATE, DELETE
DQLData Query LanguageReads rows: SELECT
DCLData Control LanguageControls who can do the above: GRANT, REVOKE

This workbook covers DDL, DML and DQL. DCL matters more on a server database such as PostgreSQL or MySQL than in SQLite, where one file is the whole database.

A spreadsheet also has rows and columns. A database adds three things a spreadsheet lacks. Many programs can read and write it at the same time. It enforces rules: a column can refuse an empty value. SQL can also join several tables and summarise millions of rows in one statement. The chapters ahead build each of those abilities, step by step.

Worked example

No SQL yet — read the table above and answer in words.

  • The column year holds the type: number.
  • The column title holds the type: text.
  • A new book arrives. It becomes a new row, not a new column.
  • A table gains a field, "pages", for every book. It becomes a new column.

Practice questions

1. A table students has columns id, name and grade. A new student joins the class. Does the table gain a row or a column?

Answer

A row. Each student is one record. A new field that applies to every student, such as date_of_birth, would be a new column instead.

2. Match each statement to its group: CREATE TABLE, SELECT, DELETE.

Answer

CREATE TABLE is DDL (it defines a table's shape). SELECT is DQL (it reads rows). DELETE is DML (it removes rows).

Chapter 2 — Installing and Using SQLite

Chapter Objectives

  • Install SQLite and open a database file
  • Run a dot command to list tables and show a schema
  • Explain why SQLite suits learning and small tools

SQLite is a database engine that stores a whole database in one file. It needs no server and no setup, so it is a quick way to learn SQL. Other engines (MySQL, PostgreSQL, SQL Server) run as a server and serve many applications at once. The SQL in this workbook is close to standard SQL and works, with small changes, on all of them.

Install SQLite and open a database file:

sudo apt install sqlite3 -y
sqlite3 library.db

Example output:

SQLite version 3.45.1 2024-01-30 16:01:20
Enter ".help" for usage hints.
sqlite>

The file library.db did not exist before this command. SQLite creates it the moment you write data into it. The prompt sqlite> means you are inside the SQLite shell, not the normal Linux shell.

SQLite also has dot commands: shell commands that start with a dot and are not SQL. They never end with a semicolon.

CommandDoes
.tablesLists the tables in the open database
.schemaShows the CREATE TABLE statement of each table
.headers onShows column names above query results
.mode columnLines up columns for easier reading
.quitLeaves the SQLite shell

Worked example

Turn on headers and column mode once, at the start of every session, then check for tables in the new file:

.headers on
.mode column
.tables

.tables prints nothing: a fresh database has no tables yet. That is correct, not an error. Chapter 3 adds the first one.

Practice questions

1. You type SELECT 1; and then .tables; with a trailing semicolon. One of the two fails. Which one, and why?

Answer

.tables; fails. The dot-command parser does not strip the trailing semicolon, so the token becomes tables;, which matches no known command. SQLite reports an unknown-command error: Error: unknown command or invalid arguments: "tables;". Enter ".help" for help. Dot commands are not SQL. They never take a semicolon.

2. You close the SQLite shell with .quit and reopen the same file tomorrow. Are the tables and rows still there?

Answer

Yes. SQLite stores everything in the .db file on disk. Closing the shell does not delete data; only DROP TABLE or deleting the file does.

Chapter 3 — Creating Tables and Choosing Data Types

Chapter Objectives

  • Write a CREATE TABLE statement with column types
  • Choose NOT NULL, UNIQUE, PRIMARY KEY and DEFAULT correctly
  • Remove a table safely with DROP TABLE IF EXISTS

CREATE TABLE defines a table's columns and the type of value each one holds.

TypeHoldsExample
INTEGERWhole numbers2008, -5
REALDecimal numbers9.99
TEXTText'Clean Code'
NULLNo value at all—

A constraint is a rule a column must obey on every row.

ConstraintRule
PRIMARY KEYIdentifies each row. Must be unique. SQLite fills an INTEGER PRIMARY KEY in for you, counting up
NOT NULLThe column cannot be empty
UNIQUENo two rows can share this value
DEFAULT valueUsed when INSERT does not give a value

Worked example

Create the first table of the running example:

CREATE TABLE books (
    id        INTEGER PRIMARY KEY,
    title     TEXT NOT NULL,
    author    TEXT NOT NULL,
    year      INTEGER,
    available INTEGER NOT NULL DEFAULT 1
);

available uses 1 for "on the shelf" and 0 for "on loan". SQLite has no BOOLEAN type; INTEGER with 0/1 is the normal substitute.

Check the result:

.schema books

Example output:

CREATE TABLE books (
    id        INTEGER PRIMARY KEY,
    title     TEXT NOT NULL,
    author    TEXT NOT NULL,
    year      INTEGER,
    available INTEGER NOT NULL DEFAULT 1
);

Remove a table only with the safe form, which does not error on a table that is already gone:

DROP TABLE IF EXISTS books_test;

DROP TABLE deletes the table and every row in it. SQLite does not ask to confirm. Run .schema first to check you are dropping the table you mean.

Practice questions

1. A table needs a column that never repeats across rows, such as an email address. Which constraint do you add?

Answer

UNIQUE. PRIMARY KEY is also unique, but a table has only one primary key; a second unique column, such as email, needs the UNIQUE constraint instead.

2. You run DROP TABLE orders; on a database with no orders table. What happens, and how do you avoid it?

Answer

SQLite returns an error: no such table. Use DROP TABLE IF EXISTS orders; so the statement succeeds whether or not the table exists.

Chapter 4 — Inserting Data

Chapter Objectives

  • Insert one row and several rows in one statement
  • Explain when you can skip the column list
  • Read back inserted rows with a plain SELECT *

INSERT INTO adds one or more rows to a table. Name the columns, then give one value per column, in the same order.

Worked example

Add the five books of the running example:

INSERT INTO books (title, author, year) VALUES
    ('Clean Code',                 'Robert Martin',  2008),
    ('The Pragmatic Programmer',   'Andrew Hunt',    1999),
    ('Python Crash Course',        'Eric Matthes',   2015),
    ('Introduction to Algorithms', 'Thomas Cormen',  2009),
    ('The Mythical Man-Month',     'Fred Brooks',    1975);

id is not in the column list. SQLite fills it in by itself, starting at 1, because id is the INTEGER PRIMARY KEY. available is also not in the list, so each row gets the table's default, 1.

Read the rows back:

SELECT * FROM books;

Example output:

id  title                       author           year  available
--  --------------------------  ---------------  ----  ---------
1   Clean Code                  Robert Martin    2008  1
2   The Pragmatic Programmer    Andrew Hunt      1999  1
3   Python Crash Course         Eric Matthes     2015  1
4   Introduction to Algorithms  Thomas Cormen    2009  1
5   The Mythical Man-Month      Fred Brooks      1975  1

If a statement gives a value for every column, in the table's own order, you can drop the column list:

INSERT INTO books VALUES (6, 'Refactoring', 'Martin Fowler', 1999, 1);

Naming the columns is safer. If the table's column order ever changes, a statement without a column list silently puts values in the wrong fields.

Practice questions

1. INSERT INTO books (title, author) VALUES ('1984', 'George Orwell'); leaves out year. What value does that row get?

Answer

NULL. A column left out of the INSERT and with no DEFAULT gets NULL, meaning "no value".

2. Why is INSERT INTO books (title, author, year) VALUES (...) safer than INSERT INTO books VALUES (...) with no column list?

Answer

The column list ties each value to a named column. Without it, the values are matched to columns purely by position, so a changed table or a wrong value order silently puts data in the wrong column.

Chapter 5 — Selecting and Projecting Columns

Chapter Objectives

  • Read specific columns instead of every column
  • Rename a column in the output with AS
  • Remove duplicate values with DISTINCT

SELECT reads rows. SELECT * reads every column; naming columns reads only the ones you need, which is faster and clearer in real queries.

Worked example

SELECT title, year FROM books;

Example output:

title                       year
--------------------------  ----
Clean Code                  2008
The Pragmatic Programmer    1999
Python Crash Course         2015
Introduction to Algorithms  2009
The Mythical Man-Month      1975
Refactoring                 1999

AS renames a column only in the output. It does not change the table.

SELECT title AS "Book Title", year AS "Published" FROM books;

DISTINCT drops repeated values, so each one appears once:

SELECT DISTINCT available FROM books;

Example output:

available
---------
1

Every book is on the shelf right now, so DISTINCT returns the single value 1. Chapter 8 loans some books out, which changes this result.

Practice questions

1. SELECT author FROM books; returns six rows, one with the same author twice. How do you make that author appear once?

Answer

SELECT DISTINCT author FROM books;. DISTINCT removes a row only when every selected column matches another row exactly.

2. SELECT title AS book_name FROM books; is run, then SELECT * FROM books; right after. Does the second statement show a column called book_name?

Answer

No. AS renames a column only in that one query's output. The table's real column is still called title.

Chapter 6 — Filtering with WHERE

Chapter Objectives

  • Filter rows with comparison operators
  • Combine conditions with AND, OR and NOT
  • Match a range with BETWEEN, a list with IN and a pattern with LIKE
  • Test for a missing value with IS NULL

WHERE keeps only the rows that match a condition. It comes straight after FROM.

OperatorMeans
=Equal to
!= or <>Not equal to
>, <, >=, <=Greater than, less than, and their "or equal" forms
BETWEEN a AND bFrom a to b, both included
IN (a, b, c)Equal to any value in the list
LIKE 'pattern'Matches a text pattern. % stands for any run of characters, _ for exactly one
IS NULL / IS NOT NULLThe value is, or is not, missing

Worked example

SELECT title, year FROM books WHERE year >= 2008;

Example output:

title                       year
--------------------------  ----
Clean Code                  2008
Python Crash Course         2015
Introduction to Algorithms  2009

Combine conditions with AND (both must be true) and OR (either can be true):

SELECT title FROM books WHERE year >= 2008 AND year <= 2010;
SELECT title FROM books WHERE author = 'Robert Martin' OR author = 'Fred Brooks';

LIKE matches a text pattern. % means "any characters, including none":

SELECT title FROM books WHERE title LIKE '%Programmer%';

Example output:

title
------------------------
The Pragmatic Programmer

= is case-sensitive for text in SQLite by default; LIKE is not. title LIKE 'clean code' still matches 'Clean Code'.

Practice questions

1. Write the condition that selects books published from 1999 to 2009, both years included, using BETWEEN.

Answer

WHERE year BETWEEN 1999 AND 2009. BETWEEN includes both ends of the range.

2. WHERE author IN ('Robert Martin', 'Fred Brooks') and WHERE author = 'Robert Martin' OR author = 'Fred Brooks' are both run. Do they return the same rows?

Answer

Yes. IN is a shorter way to write several OR-joined equality checks on the same column.

Chapter 7 — Sorting and Limiting Results

Chapter Objectives

  • Sort rows with ORDER BY, ascending and descending
  • Sort by more than one column
  • Cap the number of rows with LIMIT, and page through results with OFFSET

ORDER BY sorts the result. ASC (ascending, the default) sorts low to high; DESC sorts high to low.

Worked example

SELECT title, year FROM books ORDER BY year DESC;

Example output:

title                       year
--------------------------  ----
Python Crash Course         2015
Introduction to Algorithms  2009
Clean Code                  2008
The Pragmatic Programmer    1999
Refactoring                 1999
The Mythical Man-Month      1975

The Pragmatic Programmer and Refactoring both show 1999. ORDER BY year DESC alone does not say which of the two comes first. SQLite keeps them in the order it finds them, unless a second column breaks the tie.

Sorting by more than one column breaks ties: rows that match on the first column sort by the second.

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

LIMIT caps how many rows come back. This finds the three oldest books:

SELECT title, year FROM books ORDER BY year ASC LIMIT 3;

Example output:

title                       year
--------------------------  ----
The Mythical Man-Month      1975
The Pragmatic Programmer    1999
Refactoring                 1999

Clean Code (2008) is next in line but does not fit: the two rows tied at 1999 already fill positions 2 and 3, so LIMIT 3 stops before reaching it.

OFFSET skips a number of rows before LIMIT starts counting, which pages through a long result:

SELECT title FROM books ORDER BY title LIMIT 2 OFFSET 2;

This returns rows 3 and 4 of the alphabetical list, skipping the first two.

Practice questions

1. Which clause comes first in a SELECT with WHERE, ORDER BY and LIMIT together?

Answer

WHERE, then ORDER BY, then LIMIT: SELECT ... FROM ... WHERE ... ORDER BY ... LIMIT ....

2. A results page shows 10 rows per page. Write the LIMIT/OFFSET pair for page 3.

Answer

LIMIT 10 OFFSET 20. Page 1 is OFFSET 0, page 2 is OFFSET 10, page 3 skips the first 20 rows.

Chapter 8 — Updating and Deleting Rows Safely

Chapter Objectives

  • Change existing rows with UPDATE ... WHERE
  • Remove rows with DELETE ... WHERE
  • Explain why a SELECT with the same WHERE comes first

UPDATE changes the columns you name, in every row that matches WHERE. DELETE removes whole rows that match WHERE.

UPDATE and DELETE with no WHERE clause act on every row in the table. SQLite does not ask to confirm. Always write and check the WHERE clause before you run either statement.

Worked example

Mark two books as on loan:

UPDATE books SET available = 0 WHERE title = 'The Pragmatic Programmer';
UPDATE books SET available = 0 WHERE title = 'Introduction to Algorithms';

Check before deleting, then delete:

SELECT title FROM books WHERE year < 1990;

Example output:

title
-----------------------
The Mythical Man-Month
DELETE FROM books WHERE year < 1990;

This removes exactly the one row the SELECT showed. Running the same SELECT first turns a one-shot, hard-to-undo statement into a checked one.

Practice questions

1. UPDATE books SET available = 1; has no WHERE clause. What does it do?

Answer

It sets available to 1 on every row in the books table, not just one book. Always add a WHERE clause that names the row or rows you mean to change.

2. You want to delete the book titled 'Refactoring'. Which command checks what you are about to delete, before you run the DELETE?

Answer

SELECT * FROM books WHERE title = 'Refactoring';. Run it first and confirm it shows only the row you intend to remove, then run the matching DELETE.

Chapter 9 — Aggregate Functions and GROUP BY

Chapter Objectives

  • Summarise a column with COUNT, SUM, AVG, MIN and MAX
  • Group rows with GROUP BY and aggregate each group
  • Filter groups with HAVING, and explain how it differs from WHERE

An aggregate function turns many rows into one value.

FunctionReturns
COUNT(*)Number of rows
COUNT(column)Number of rows where column is not NULL
SUM(column)Total of a numeric column
AVG(column)Average of a numeric column
MIN(column), MAX(column)Smallest and largest value

Worked example

SELECT COUNT(*) AS total_books, AVG(year) AS avg_year FROM books;

With the six rows from Chapter 4 (one deleted in Chapter 8, leaving five: Clean Code 2008, The Pragmatic Programmer 1999, Python Crash Course 2015, Introduction to Algorithms 2009, Refactoring 1999):

total_books  avg_year
-----------  --------
5            2006.0

GROUP BY puts rows with the same value into one group, so an aggregate function runs once per group instead of once for the whole table:

SELECT available, COUNT(*) AS how_many
FROM books
GROUP BY available;

Example output:

available  how_many
---------  --------
0          2
1          3

HAVING filters groups, after GROUP BY runs. WHERE filters rows, before grouping. This is the one rule to remember:

SELECT available, COUNT(*) AS how_many
FROM books
GROUP BY available
HAVING how_many > 2;

Example output:

available  how_many
---------  --------
1          3

Only the group with more than two books survives HAVING. WHERE could not do this: at the point WHERE runs, there are no groups yet, only rows.

Practice questions

1. You need every book published after 2000, counted by author. Do you filter the year with WHERE or HAVING?

Answer

WHERE, because it filters individual rows (year > 2000) before GROUP BY author forms the groups. HAVING would filter the groups themselves, for example by how many books each author has.

2. SELECT author, COUNT(*) FROM books GROUP BY author; includes an author with only one book. Why does COUNT(*) show 1 and not 0 or blank?

Answer

GROUP BY only forms a group for values that exist in the table. A group with one matching row counts that one row, so COUNT(*) is 1, not 0.

Chapter 10 — Joining Tables

Chapter Objectives

  • Explain what a foreign key links
  • Combine rows from two tables with INNER JOIN
  • Keep unmatched rows with LEFT JOIN
  • Use table aliases to shorten a query with several tables

A foreign key is a column that holds the primary key of a row in another table, linking the two. loans.book_id links each loan to one row in books.

CREATE TABLE members (
    id     INTEGER PRIMARY KEY,
    name   TEXT NOT NULL,
    email  TEXT UNIQUE NOT NULL
);

CREATE TABLE loans (
    id          INTEGER PRIMARY KEY,
    book_id     INTEGER NOT NULL REFERENCES books(id),
    member_id   INTEGER NOT NULL REFERENCES members(id),
    loan_date   TEXT NOT NULL,
    return_date TEXT
);

INSERT INTO members (name, email) VALUES
    ('Amina Hassan', 'amina@example.com'),
    ('Chen Wei',      'chen@example.com');

INSERT INTO loans (book_id, member_id, loan_date, return_date) VALUES
    (2, 1, '2024-04-01', NULL),
    (4, 1, '2024-04-10', NULL);

return_date is NULL for both loans: neither book has come back yet, which matches books.available = 0 for those two rows from Chapter 8.

Worked example

INNER JOIN returns only rows that match in both tables:

SELECT members.name, books.title, loans.loan_date
FROM loans
INNER JOIN members ON loans.member_id = members.id
INNER JOIN books   ON loans.book_id   = books.id;

Example output:

name          title                        loan_date
------------  ---------------------------  ----------
Amina Hassan  The Pragmatic Programmer     2024-04-01
Amina Hassan  Introduction to Algorithms   2024-04-10

Chen Wei has no row in loans, so INNER JOIN leaves her out entirely. LEFT JOIN keeps every row from the left-hand table, filling unmatched columns with NULL. By default the SQLite shell prints a NULL value as an empty cell; the dot command below gives it a visible label instead:

.nullvalue NULL
SELECT members.name, books.title
FROM members
LEFT JOIN loans ON loans.member_id = members.id
LEFT JOIN books ON loans.book_id   = books.id;

Example output:

name          title
------------  --------------------------
Amina Hassan  The Pragmatic Programmer
Amina Hassan  Introduction to Algorithms
Chen Wei      NULL

Aliases shorten a query that names the same table several times:

SELECT m.name, b.title, l.loan_date
FROM loans l
JOIN members m ON l.member_id = m.id
JOIN books   b ON l.book_id   = b.id
WHERE l.return_date IS NULL;

m, b and l stand for members, books and loans. JOIN alone means INNER JOIN; SQLite treats the two as the same.

Practice questions

1. INNER JOIN on members and loans returns 2 rows. The members table has 3 rows. Why does the join return fewer rows than the table?

Answer

INNER JOIN keeps only rows that match in both tables. A member with no row in loans has nothing to match, so INNER JOIN drops that member from the result. LEFT JOIN would keep them, with NULL in the loan columns.

2. Why does loans.book_id reference books.id instead of storing the book's title directly?

Answer

A foreign key links to an id. The same book, identified once, can then be loaned many times without repeating its title, author and year in every loan row. A correction to the book's title also only needs to happen in one place: books.

Chapter 11 — Subqueries and Views

Chapter Objectives

  • Use a subquery inside WHERE to filter on another table's result
  • Explain when a subquery and a JOIN solve the same problem
  • Save a query as a reusable VIEW

A subquery is a SELECT nested inside another statement. SQLite runs the inner query first and uses its result in the outer one.

Worked example

Find every book that has never been loaned, without a JOIN:

SELECT title
FROM books
WHERE id NOT IN (SELECT book_id FROM loans);

Example output:

title
--------------------
Clean Code
Python Crash Course
Refactoring

The inner query (SELECT book_id FROM loans) returns 2 and 4. The outer query then keeps every book whose id is not in that list. A JOIN can also give the same answer, with a LEFT JOIN plus a WHERE ... IS NULL check. For "rows with no match at all", a subquery often reads more directly.

A view names a SELECT so you can reuse it like a table, without copying the data:

CREATE VIEW books_on_loan AS
SELECT b.title, m.name AS borrower, l.loan_date
FROM loans l
JOIN books   b ON l.book_id   = b.id
JOIN members m ON l.member_id = m.id
WHERE l.return_date IS NULL;

SELECT * FROM books_on_loan;

Example output:

title                        borrower      loan_date
---------------------------  ------------  ----------
The Pragmatic Programmer     Amina Hassan  2024-04-01
Introduction to Algorithms   Amina Hassan  2024-04-10

A view stores the query, not the rows. Each time you read books_on_loan, SQLite runs the SELECT again against the current data.

Practice questions

1. SELECT title FROM books WHERE id IN (SELECT book_id FROM loans); — in words, what does this return?

Answer

The titles of books that have at least one row in loans: books that have been loaned at least once, whether or not they have been returned.

2. A books row is deleted after books_on_loan is created. Does the view still show the deleted book?

Answer

No. A view holds the query, not a copy of the rows. Reading the view re-runs the SELECT, so a deleted row disappears from the view's result too.

Chapter 12 — Worked Project: Query a Small Library Database

Chapter Objectives

  • Build a multi-table database from a plan, not one piece at a time
  • Write a query that joins, filters, groups and sorts in one statement
  • Check a report's result against the raw rows by hand

This chapter uses the books, members and loans tables from the earlier chapters, plus one more loan, to build a short report.

Worked example

Add one more loan: Chen Wei borrows 'Clean Code' on '2024-04-15' and returns it on '2024-04-28'.

INSERT INTO loans (book_id, member_id, loan_date, return_date)
VALUES (1, 2, '2024-04-15', '2024-04-28');

Report: how many books has each member borrowed, ever?

SELECT m.name, COUNT(*) AS books_borrowed
FROM loans l
JOIN members m ON l.member_id = m.id
GROUP BY m.id
ORDER BY books_borrowed DESC;

Trace it by hand first. loans now has three rows: two for Amina (member 1), one for Chen (member 2). GROUP BY m.id makes one group per member; COUNT(*) counts the rows in each group.

Example output:

name          books_borrowed
------------  --------------
Amina Hassan  2
Chen Wei      1

Report: which books are currently out, and to whom?

SELECT b.title, m.name AS borrower
FROM loans l
JOIN books   b ON l.book_id   = b.id
JOIN members m ON l.member_id = m.id
WHERE l.return_date IS NULL
ORDER BY b.title;

Only loans with no return_date are "currently out". Chen's loan of Clean Code has a return_date, so it is correctly left out of this report, even though it counted in the first one.

Example output:

title                        borrower
---------------------------  ------------
Introduction to Algorithms   Amina Hassan
The Pragmatic Programmer     Amina Hassan

Practice questions

1. Write a query that lists each book's title and how many times it has been loaned, including books loaned zero times.

Answer
SELECT b.title, COUNT(l.id) AS times_loaned
FROM books b
LEFT JOIN loans l ON l.book_id = b.id
GROUP BY b.id
ORDER BY times_loaned DESC;

LEFT JOIN keeps every book, even with no matching loan. COUNT(l.id) counts only the non-NULL loan ids, so an unloaned book correctly shows 0.

2. The "books currently out" report above returned 2 rows. Explain, from the raw loans data, why it is 2 and not 3.

Answer

loans has three rows after this chapter's INSERT. Two have return_date IS NULL: Amina's loans of The Pragmatic Programmer and Introduction to Algorithms. The third, Chen's loan of Clean Code, has a return_date of 2024-04-28. The clause WHERE l.return_date IS NULL keeps only the first two.

Workbook complete. You can now create tables, insert and filter data, sort and aggregate it, join several tables and save a query as a view. Practise the same skills against a web application's database in SQL Fundamentals Lab. To see what happens when an application trusts user input inside a SQL statement instead of filtering it safely, continue to SQL Injection Deep Dive.

Sign in to track progress and send feedback.

Related