Databases

SQL Basics

Learn SQL from the first query to joins and summaries, with small examples you can run.

8 chapters 64 lessons
Start the course →

Course map

8 chapters in order. Start at the first, or jump to the one you need.

  1. Chapter 1 Your First Queries 8 lessons
  2. Chapter 2 Filtering and Sorting 8 lessons
  3. Chapter 3 Summarising Data with GROUP BY 8 lessons
  4. Chapter 4 Joining Tables 8 lessons
  5. Chapter 5 Inserting, Updating and Deleting 8 lessons
  6. Chapter 6 Creating Tables and Constraints 8 lessons
  7. Chapter 7 Subqueries and CTEs 8 lessons
  8. Chapter 8 Window Functions 8 lessons

1. Your First Queries

  1. SQL How to Read a Database Reading Before you write a query, learn what is in the database: list the tables, read the columns and their types, spot the keys, count the rows and peek at a few of them. Runs on the Shop, Bank or School sample data. Level: basic.
  2. SQL SELECT Columns Reading Choose exactly the columns you want, in the order you want. Why SELECT * is for looking and not for programs, how to name a column with its table, constants in a result, SELECT without a table, and what the error for a wrong name looks like. Runs on the sample data. Level: basic.
  3. SQL Expressions and Arithmetic Reading Calculate in a query: + - * / and the remainder, brackets and the order of operations, why 7 / 2 is 3 in SQLite, how to get decimals, and how calculated columns are built from real columns. Runs on the sample data. Level: basic.
  4. SQL Aliases and Readable Results Reading Give columns and tables short, clear names with AS, use double quotes for names with spaces, add comments to explain a query, and lay a query out so that it can be read. Runs on the sample data. Level: basic.
  5. SQL Text Functions Reading Join, clean and cut text: the || operator, UPPER and LOWER, LENGTH, SUBSTR and INSTR, TRIM and REPLACE, and what NULL does to text. Runs on the sample data. Level: basic.
  6. SQL Numbers and Rounding Reading Round results with ROUND, take the size of a number with ABS, tell whole numbers from decimals, convert between types with CAST, and show money held in cents. Runs on the sample data. Level: basic.
  7. SQL Dates and Times Reading Dates are text in SQLite. Learn the ISO format, DATE and STRFTIME to pick parts out, adding days or months, finding the days between two dates with JULIANDAY, and why a fixed date makes a repeatable example. Runs on the sample data. Level: intermediate.
  8. SQL DISTINCT and Reading Error Messages Reading Remove repeated rows with DISTINCT, see how it works on one column and on several, and learn to read the most common SQL error messages so you can fix a query yourself. Ends the first chapter. Runs on the sample data. Level: basic.

2. Filtering and Sorting

  1. SQL WHERE Reading Choose the rows you want with WHERE: the comparison operators, text and number conditions, dates as text, why text matching is exact, and how to count the rows that match. Runs on the sample data. Level: basic.
  2. SQL AND, OR and NOT Reading Combine conditions with AND, OR and NOT, see how the order of evaluation can surprise you, and use brackets to say exactly what you mean. Runs on the sample data. Level: basic.
  3. SQL IN and BETWEEN Reading Test against a list of values with IN and NOT IN, test a range with BETWEEN for numbers and dates, and learn that BETWEEN includes both ends. Runs on the sample data. Level: basic.
  4. SQL LIKE Patterns Reading Search text with LIKE and its two wildcards, % for any number of characters and _ for exactly one. See how case is treated in SQLite, how to search for a real percent sign, and how patterns behave in other databases. Runs on the sample data. Level: basic.
  5. SQL NULL Reading NULL means no value. Test for it with IS NULL and IS NOT NULL, see why = NULL never works, how NULL behaves in conditions, and how to replace it with COALESCE or turn a value into NULL with NULLIF. Runs on the sample data. Level: basic.
  6. SQL ORDER BY Reading Sort the result with ORDER BY: ascending and descending, several columns, sorting by a calculation or an alias, where NULL goes, and why a result without ORDER BY has no guaranteed order. Runs on the sample data. Level: basic.
  7. SQL LIMIT and OFFSET Reading Keep only the first rows with LIMIT, skip rows with OFFSET to page through a result, why a stable ORDER BY is needed, and how top-N queries and pages are built. Runs on the sample data. Level: basic.
  8. SQL CASE Reading Make decisions inside a query with CASE: put rows into groups or labels, use it in the SELECT list, in ORDER BY and in WHERE, the simple and searched forms, and how it handles NULL. Ends chapter 2. Runs on the sample data. Level: intermediate.

3. Summarising Data with GROUP BY

  1. SQL Aggregate Functions Reading Turn many rows into one number with COUNT, SUM, AVG, MIN and MAX: what each does, how to combine them in one query, how to use them with WHERE, and why they return a single row. Runs on the sample data. Level: basic.
  2. SQL GROUP BY Reading Summarise each group separately with GROUP BY: one row per value, aggregates per group, grouping by several columns, sorting the groups, and the rule that every plain column must be grouped. Runs on the sample data. Level: basic.
  3. SQL HAVING Reading Filter groups with HAVING after GROUP BY, see the difference from WHERE, and learn the order in which a query is processed so that you know which clause to use. Runs on the sample data. Level: basic.
  4. SQL COUNT in Detail Reading COUNT(*), COUNT(column) and COUNT(DISTINCT column) answer different questions. See what each one counts, how NULL changes the result, and how to count different values and groups correctly. Runs on the sample data. Level: basic.
  5. SQL Conditional Aggregation Reading Count and add up several groups in one query with SUM and COUNT around CASE, the FILTER clause, and how to turn rows into columns for a small cross table. Runs on the sample data. Level: intermediate.
  6. SQL NULL in Aggregates Reading See how SUM, AVG, MIN, MAX and COUNT treat NULL, why an average can be misleading when values are missing, what an aggregate returns when there are no rows, and how to count missing values on purpose. Runs on the sample data. Level: intermediate.
  7. SQL Grouping by Dates Reading Summarise data by year, month, weekday or any period: pick the period with STRFTIME or SUBSTR, group and sort by it, build a monthly report and learn why a month without rows does not appear. Runs on the sample data. Level: intermediate.
  8. SQL Shares, Rankings and Joined Text Reading Finish the chapter by turning group totals into shares of the whole, ranking groups, collecting the values of a group into one text with GROUP_CONCAT, and a checklist for building a clear summary query. Runs on the sample data. Level: intermediate.

4. Joining Tables

  1. SQL Why We Join Tables Reading Data lives in several tables linked by keys. See a parent table and its child table, how a foreign key connects them, what happens when two tables are combined with no condition, and why the join condition matters. Runs on the sample data. Level: basic.
  2. SQL INNER JOIN Reading Combine a child table with its parent using JOIN ... ON: the syntax, table aliases, which columns to show, how to filter and sort a joined result, and how many rows to expect. Runs on the sample data. Level: basic.
  3. SQL LEFT JOIN Reading Keep every row of the left table even when it has no match with LEFT JOIN: how the unmatched rows show NULL, how to count children including zero, and why a condition on the right table belongs in ON and not in WHERE. Runs on the sample data. Level: intermediate.
  4. SQL Finding Missing Rows Reading Find the rows that have no partner in another table: LEFT JOIN with IS NULL, NOT EXISTS, and NOT IN with its trap. Check that your answer plus the matches add up to the whole table. Runs on the sample data. Level: intermediate.
  5. SQL Joining Several Tables Reading Chain joins to follow links across three, four or more tables: read the diagram of keys, add one JOIN at a time, mix inner and left joins, keep the row count under control, and test each step. Runs on the sample data. Level: intermediate.
  6. SQL Self Joins Reading Join a table to itself, with two aliases, to compare rows of the same table: a manager and an employee, a category and its parent, two customers in the same city, siblings with one guardian. Runs on the sample data. Level: intermediate.
  7. SQL UNION, INTERSECT and EXCEPT Reading Combine the results of two queries with UNION and UNION ALL, keep the rows found in both with INTERSECT, keep the rows found in only the first with EXCEPT, and learn the rules the two queries must follow. Runs on the sample data. Level: intermediate.
  8. SQL Join Mistakes and How to Spot Them Reading The mistakes that give wrong answers without an error: totals counted twice after a join, a missing or wrong ON condition, a LEFT JOIN turned into an inner join, and the ambiguous column error. A checklist to test every join. Runs on the sample data. Level: intermediate.

5. Inserting, Updating and Deleting

  1. SQL INSERT Reading Add rows with INSERT INTO: the column list, one row or many, columns you leave out, copying rows with INSERT ... SELECT, and the errors the database gives when a rule is broken. Runs on a copy of the sample data. Level: basic.
  2. SQL UPDATE Reading Change existing rows with UPDATE ... SET ... WHERE: one column or several, calculating a new value from the old one, updating from a subquery, checking how many rows changed, and the danger of forgetting WHERE. Runs on a copy of the sample data. Level: basic.
  3. SQL DELETE Reading Remove rows with DELETE FROM ... WHERE, count before you delete, see how a foreign key can refuse a delete, and why many systems mark rows as inactive instead of deleting them. Runs on a copy of the sample data. Level: basic.
  4. SQL Changing Data Safely Reading Habits that stop a change from becoming a disaster: look first with SELECT, count the rows, keep a copy, change in small steps, check the result afterwards, and know what you cannot undo. Runs on a copy of the sample data. Level: intermediate.
  5. SQL Transactions Reading Group several changes into one all-or-nothing unit with BEGIN, COMMIT and ROLLBACK, see a failed step undone, use a savepoint to undo part of the work, and learn the rules for what belongs in a transaction. Runs on a copy of the sample data. Level: intermediate.
  6. SQL Upsert: Insert or Update Reading Insert a row, or update it when it already exists, in one statement with ON CONFLICT: DO NOTHING, DO UPDATE and the excluded values, why INSERT OR REPLACE is riskier, and how other databases write it. Runs on a copy of the sample data. Level: intermediate.
  7. SQL RETURNING Reading Get the rows you just changed back from INSERT, UPDATE and DELETE with RETURNING: the new ids, the changed values and the deleted rows, without a second query. Includes what other databases offer. Runs on a copy of the sample data. Level: intermediate.
  8. SQL Loading Many Rows Reading Load data in bulk the right way: many rows in one INSERT, a staging table you check before you copy, INSERT ... SELECT, CREATE TABLE AS, generating rows with a recursive query, and checks that every row arrived. Ends chapter 5. Runs on a copy of the sample data. Level: intermediate.

6. Creating Tables and Constraints

  1. SQL CREATE TABLE Reading Create your own tables with CREATE TABLE: columns and types, a primary key, IF NOT EXISTS, how to see what you built, and how to design a small table from a description. Runs on a copy of the sample data. Level: basic.
  2. SQL Data Types Reading The five kinds of value SQLite stores, how a column's declared type (its affinity) converts values, why the type is only a hint in a normal table, how STRICT tables enforce it, and which type to choose. Level: intermediate.
  3. SQL Foreign Keys in Your Tables Reading Link your own tables with REFERENCES: a foreign key to a sample table or to your own parent table, how the link is enforced, ON DELETE rules, why foreign keys must be switched on in SQLite, and how to design a parent and child pair. Runs on a copy of the sample data. Level: intermediate.
  4. SQL NOT NULL, UNIQUE, CHECK and DEFAULT Reading Put the rules in the table: NOT NULL, UNIQUE, CHECK and DEFAULT, how to name a rule, how to test each one by trying to break it, and why the rules belong in the database as well as in the program. Runs on a copy of the sample data. Level: intermediate.
  5. SQL ALTER TABLE Reading Change a table that already has data: add a column, rename a column or a table, drop a column, what SQLite does not allow, and the safe way to make a bigger change. Runs on a copy of the sample data. Level: intermediate.
  6. SQL Indexes Reading Make lookups fast with CREATE INDEX: what an index is, how to see whether a query uses one with EXPLAIN QUERY PLAN, unique indexes, which columns to index, the cost of indexes, and how to drop one. Runs on a copy of the sample data. Level: intermediate.
  7. SQL Views Reading Save a query under a name with CREATE VIEW: how a view hides a join, why it always shows current data, views over summaries, what you cannot do to a view, and how to change or drop one. Runs on a copy of the sample data. Level: intermediate.
  8. SQL Dropping Tables and a Small Design Project Reading Remove tables safely with DROP TABLE, in the right order, and finish the chapter by designing, building, filling and checking a small three-table database from a description. Runs on a copy of the sample data. Level: intermediate.

7. Subqueries and CTEs

  1. SQL Scalar Subqueries Reading Put a query inside a query: a subquery that returns one value, used in WHERE and in SELECT, comparisons with an average or a maximum, what happens when it returns no row or too many, and when to write it as a join. Level: intermediate.
  2. SQL IN and EXISTS with Subqueries Reading Filter with a list built by a query: IN (SELECT ...), NOT IN and its NULL trap, EXISTS and NOT EXISTS, and how they compare with a join for questions like customers who ordered or products never sold. Level: intermediate.
  3. SQL Correlated Subqueries Reading A subquery that uses a value from the outer row: compare each row with its own group's average, find the latest row per group, count related rows in SELECT, and learn why they can be slow and what to use instead. Level: intermediate.
  4. SQL Subqueries in FROM Reading Use a query as a table: a derived table in FROM, an alias it needs, aggregating an aggregate (the average of per-customer totals), joining a summary back to the rows, and when a named view or WITH is clearer. Level: intermediate.
  5. SQL WITH: Common Table Expressions Reading Name a step of a query with WITH, read the query from top to bottom, use the same step more than once, and know how a CTE differs from a view and a derived table. Level: intermediate.
  6. SQL Chained CTEs Reading Build a report step by step with several CTEs, each using the one before: clean, summarise, compare, present. Learn to name the steps, test each one alone, and keep the final query short. Level: intermediate.
  7. SQL Recursive CTEs Reading Queries that call themselves: WITH RECURSIVE to count, to generate a calendar, to walk a tree such as a manager chain or a category tree, how to stop it, and what to watch for. Level: advanced.
  8. SQL Choosing Between Joins, Subqueries and CTEs Reading The same question answered four ways (join, IN, EXISTS, WITH), how to pick by clarity, safety and speed, how to compare them with EXPLAIN QUERY PLAN, and a checklist for rewriting a hard query. Ends chapter 7. Level: intermediate.

8. Window Functions

  1. SQL Window Functions: OVER Reading Calculate across rows without collapsing them: an aggregate with OVER next to every row, the share of the total, the difference from the average, and how a window function differs from GROUP BY. Level: advanced.
  2. SQL PARTITION BY Reading Give each group its own window with PARTITION BY: a group's total or average next to every row, each row's share of its group, the difference from the group average, and how it compares with a correlated subquery. Level: advanced.
  3. SQL ROW_NUMBER, RANK and DENSE_RANK Reading Number and rank rows with window functions: ROW_NUMBER for a unique number, RANK and DENSE_RANK for ties, ranking inside groups with PARTITION BY, and why the ORDER BY inside OVER needs a tie-breaker. Level: advanced.
  4. SQL Running Totals Reading Add up as you go with SUM OVER and ORDER BY: a running total, a running total per group, a running count, the default frame and the tie trap it hides, and the explicit ROWS frame that avoids it. Level: advanced.
  5. SQL LAG and LEAD Reading Look at the previous or next row with LAG and LEAD: change from the last row, days between events, a default for the first row, looking back several rows, and working within a group. Level: advanced.
  6. SQL Moving Averages and Frames Reading Control the rows a window sees with ROWS BETWEEN: a 3-month moving average, a window of the last N rows, the frame forms (PRECEDING, FOLLOWING, CURRENT ROW), and why the first rows of a moving average cover fewer rows. Level: advanced.
  7. SQL Top N per Group Reading Find the best rows of each group: the single latest row per customer, the top 3 per category, how to handle ties with RANK, and how this window-function pattern replaces the correlated subquery of chapter 7. Level: advanced.
  8. SQL NTILE, FIRST_VALUE and Named Windows Reading The rest of the window toolkit: NTILE for quartiles, FIRST_VALUE, LAST_VALUE and NTH_VALUE, the LAST_VALUE frame trap, FILTER on window aggregates, a named WINDOW clause, and a closing summary of the course. Level: advanced.