SQL lessons: a free course from the basics to analytics
12 chapters and 74 lessons take you from your first SELECT to joins, window functions, data changes and query performance. Each lesson explains one topic with SQL examples and links to practice tasks on real databases.
Find a lesson by topic or keyword below, or start with chapter 1.
No lessons found. Try another word.
1 Getting Started with SQL
-
1.1
Introduction to Databases
8 min
A database is an organized collection of data managed by a DBMS. Learn database types, core DBMS functions, and why SQL is the universal data language.
-
1.2
Types of Databases
15 min
The main database types: relational, key-value, document, wide-column, graph, time-series and columnar, with their differences and use cases.
-
1.3
Relational Database Concepts
10 min
The building blocks of relational databases: tables, columns, rows, primary and foreign keys, and ACID transaction properties, with examples.
-
1.4
Basic Data Types
8 min
SQL data types define what values a column can store. Learn numeric, string, date/time, boolean, and other types with practical examples and selection tips.
-
1.5
Complex Data Types
7 min
A short tour of SQL data types that store structure: JSON, XML, arrays, ENUM and SET, BLOB, UUID, spatial types and VECTOR for AI embeddings.
-
1.6
Understanding NULL Values in SQL
6 min
What NULL means in a relational database, how it differs from 0, an empty string and false, which columns allow it, and why it makes logic three-valued.
-
1.7
Overview of SQL
8 min
SQL is the standard language for relational databases. Learn how SQL is organized, what its subsets are, and how a basic query is built.
2 Basic Data Retrieval - The SELECT Statement
-
2.1
Select Data from a Table
6 min
Learn core SQL SELECT basics: choosing all or specific columns, controlling output order, and using DISTINCT to remove duplicates.
-
2.2
Filtering Data
6 min
The SQL WHERE clause filters rows by a condition. Learn comparison operators, BETWEEN, IN, LIKE patterns, and how to handle NULL correctly.
-
2.3
Combine Multiple Conditions
7 min
Learn logical operators AND, OR, and NOT in SQL WHERE, operator precedence, parentheses, and practical NOT IN and NOT LIKE examples.
-
2.4
IS NULL and IS NOT NULL
6 min
Why WHERE column = NULL returns nothing, how IS NULL and IS NOT NULL work, and how NULL hides rows in NOT, <> and NOT IN conditions.
-
2.5
Aliasing Columns
5 min
A SQL column alias gives a column a temporary name in the result. Learn the AS keyword, aliases with spaces, aliases for calculations, and where they work.
-
2.6
Ordering Results
6 min
SQL ORDER BY sorts query results. Learn ascending and descending order, sorting by several columns, by expressions and aliases, and where NULL values end up.
-
2.7
Limiting Results with LIMIT and OFFSET
5 min
SQL LIMIT restricts how many rows a query returns, and OFFSET skips rows. Learn top-N queries, pagination, why ORDER BY is required, and TOP / FETCH FIRST.
-
2.8
Putting It All Together: WHERE, ORDER BY, and LIMIT
6 min
Combine WHERE, ORDER BY and LIMIT in one SQL query. Learn the required clause order, the logical processing order, and filtered top-N and pagination queries.
3 Working with Functions
-
3.1
Built-in SQL Functions
8 min
Learn how built-in SQL functions work in SELECT and WHERE clauses, and apply them to real Sakila-based data analysis scenarios.
-
3.2
Common String Functions
8 min
Learn the core SQL string functions with Sakila examples: clean, combine, and extract text data in practical query workflows.
-
3.3
Core Mathematical Functions
8 min
Learn core SQL mathematical functions with Sakila examples: rounding, modulo, powers, roots, and practical calculation scenarios.
-
3.4
Date and Time Functions
8 min
SQL date and time functions get the current date, extract parts, add intervals, calculate differences and format dates. Examples with NOW, DATE_ADD, DATEDIFF.
-
3.5
Conditional Operator
7 min
SQL CASE WHEN adds if-then-else logic to a query. Learn simple and searched CASE, labels and categories in SELECT, custom sort order, and conditions in WHERE.
-
3.6
JSON Functions
8 min
Read values from JSON columns by path, filter rows by them, count array items and build JSON with JSON_VALUE, ->>, JSON_OBJECT and JSON_ARRAYAGG.
4 Aggregate Functions and Grouping
-
4.1
Basic Aggregation Functions
8 min
Learn core SQL aggregate functions with Sakila examples: COUNT, SUM, AVG, MIN, MAX, plus differences between COUNT(*), COUNT(column), and COUNT(DISTINCT ...).
-
4.2
Grouping Data
7 min
Learn GROUP BY: syntax, rules, single and multi-column grouping, practical Sakila examples.
-
4.3
Filtering Grouped Data
7 min
Learn HAVING clause: syntax, WHERE vs HAVING differences, filtering groups after aggregation, Sakila examples.
-
4.4
Conditional Aggregation
8 min
Conditional aggregation calculates several metrics in one SQL query with SUM, COUNT and AVG over CASE WHEN. Learn the patterns, common mistakes, and pivots.
-
4.5
Advanced Aggregation
9 min
SQL ROLLUP, CUBE and GROUPING SETS add subtotals and grand totals to GROUP BY results. Learn how they differ, WITH ROLLUP in MySQL, and the GROUPING() function.
5 Working with Multiple Tables
-
5.1
Fundamentals of JOINs in SQL
8 min
A SQL JOIN combines rows from two or more tables by a related column. Learn how JOIN works, the ON condition and table aliases, on Sakila data.
-
5.2
INNER JOIN - Combining Matching Rows
6 min
SQL INNER JOIN returns only rows that have a match in both tables. Learn the syntax, table aliases, joining three tables, and what happens to unmatched rows.
-
5.3
LEFT JOIN - Including All Records from the Left Table
7 min
SQL LEFT JOIN returns all rows of the left table and matching rows of the right one, with NULL where none match. Learn syntax, anti-joins and pitfalls.
-
5.4
RIGHT JOIN - Including All Records from the Right Table
4 min
SQL RIGHT JOIN returns all rows from the right table and the matching rows from the left one. Learn the syntax, how it mirrors LEFT JOIN, and when to use it.
-
5.5
FULL OUTER JOIN - Combining Everything from Both Tables
6 min
SQL FULL OUTER JOIN returns all rows from both tables, with NULL where there is no match. Learn the syntax and how to emulate it in MySQL and MariaDB.
-
5.6
CROSS JOIN - The Cartesian Product
5 min
SQL CROSS JOIN returns every combination of rows from two tables. Learn the syntax, the result size, and how to build report grids and fill gaps.
-
5.7
SELF JOIN - Joining a Table to Itself
5 min
A SQL self join joins a table to itself to compare rows or follow a hierarchy. Learn why aliases are required and how to avoid duplicate pairs.
-
5.8
Practical JOIN Scenarios and Techniques
8 min
Practical SQL JOIN examples: joining several tables, aggregating joined data, finding missing rows, and avoiding inflated totals and lost outer rows.
-
5.9
Join Algorithms
9 min
How databases execute joins: nested loop, hash join and merge join. Learn how each algorithm works, when the planner picks it, and how to see it in EXPLAIN.
-
5.10
Dataset Operations
8 min
Dataset operations let you combine, intersect, and subtract query results. Learn UNION, INTERSECT, and EXCEPT with Sakila examples.
6 Subqueries and Common Table Expressions (CTEs)
-
6.1
Introduction to Subqueries
7 min
A subquery is a SELECT inside another query. Learn subquery types, execution flow, and Inline View with practical Sakila examples.
-
6.2
Subqueries in the WHERE Clause
8 min
Subqueries in WHERE let you filter data dynamically. Learn IN, NOT IN, EXISTS, NOT EXISTS, ANY, and ALL with practical Sakila examples.
-
6.3
Correlated Subqueries
6 min
A SQL correlated subquery uses values from the outer query for each row. Learn how it works, compare rows with their group, use EXISTS, mind performance.
-
6.4
Common Table Expressions (CTEs)
8 min
A SQL CTE is a named temporary result set defined with WITH. Learn CTE syntax, CTE vs subquery, chaining multiple CTEs, and practical analysis examples.
-
6.5
Recursive CTEs
9 min
A SQL recursive CTE queries hierarchies with WITH RECURSIVE. Learn the anchor and recursive members, org chart paths, depth limits and cycle protection.
-
6.6
Applying Recursive CTEs
9 min
Practical SQL recursive CTE examples: generate a date series to fill gaps, total a category subtree, explode a bill of materials and find routes in a graph.
7 Window Functions
-
7.1
Window Functions
8 min
SQL window functions calculate across related rows without collapsing them. Learn OVER, PARTITION BY and ORDER BY, window vs GROUP BY, and percent of total.
-
7.2
Using ROW_NUMBER, RANK, DENSE_RANK, and NTILE
8 min
The difference between ROW_NUMBER, RANK, DENSE_RANK and NTILE in SQL: how each handles ties, when to use which, plus PERCENT_RANK and CUME_DIST, on real data.
-
7.3
Window Frames - Controlling the Window Boundaries
8 min
SQL window frames set which rows a window function uses. Learn ROWS vs RANGE, BETWEEN, UNBOUNDED, the default frame, moving averages and the WINDOW clause.
-
7.4
LAG, LEAD, FIRST_VALUE and LAST_VALUE
9 min
Learn LAG, LEAD, FIRST_VALUE, and LAST_VALUE: syntax, common use cases, row-to-row comparison without self joins, and the important LAST_VALUE frame nuance.
8 Data Manipulation Language (DML)
-
8.1
The INSERT INTO Statement
7 min
SQL INSERT INTO adds new rows to a table. Learn the syntax, multi-row inserts, INSERT INTO ... SELECT, NULL and DEFAULT values, and common errors.
-
8.2
The UPDATE Statement
7 min
SQL UPDATE changes existing rows. Learn SET and WHERE, updating several columns, calculating from current values, updates by another table, and safety.
-
8.3
The DELETE Statement
6 min
SQL DELETE removes rows from a table. Learn DELETE ... WHERE, deleting by another table, foreign key errors, checking first, and DELETE vs TRUNCATE.
-
8.4
SQL Transactions
10 min
A SQL transaction groups statements into one unit: all succeed or none do. Learn COMMIT, ROLLBACK, SAVEPOINT, autocommit and isolation levels.
9 Data Definition Language (DDL)
-
9.1
The CREATE TABLE Statement
9 min
SQL CREATE TABLE creates a table. Learn data types, PRIMARY KEY, AUTO_INCREMENT, NOT NULL, UNIQUE, DEFAULT, CHECK and FOREIGN KEY constraints.
-
9.2
The ALTER TABLE Statement
9 min
SQL ALTER TABLE changes an existing table. Learn to add, modify, rename and drop columns, and to add or drop constraints in MySQL and PostgreSQL.
-
9.3
The TRUNCATE and DROP TABLE Statements
6 min
SQL TRUNCATE empties a table and DROP TABLE removes it. Learn how both differ from DELETE in speed, rollback, auto-increment and foreign keys.
-
9.4
Temporary Tables
7 min
SQL temporary tables store intermediate results for one session. Learn CREATE TEMPORARY TABLE, AS SELECT, temp tables vs CTEs, and MySQL pitfalls.
-
9.5
Views
8 min
Learn SQL views: CREATE VIEW syntax, differences from regular and temporary tables, updatability, and practical Sakila examples.
-
9.6
Materialized Views
9 min
A materialized view stores the result of a query on disk and is refreshed on demand. Learn CREATE and REFRESH MATERIALIZED VIEW and the MySQL workaround.
-
9.7
Database Normalization
10 min
Database normalization splits data into related tables so each fact is stored once. Learn 1NF, 2NF, 3NF and BCNF, update anomalies and denormalization.
10 Queries Performance and Quality
-
10.1
Best Practices for Readable and Maintainable SQL Code
8 min
SQL best practices for readable code: keyword case, line breaks and indentation, snake_case names, clear aliases, comments, and a cleanup of a messy query.
-
10.2
Writing Efficient SQL Queries
10 min
Efficient SQL queries reduce server load and speed up reports. Learn practical filtering, JOIN, SARGable, and LIMIT techniques.
-
10.3
Introducing SQL Indexes
10 min
Learn what SQL indexes are, how they affect SELECT performance, and which basic rules help avoid common query speed mistakes.
-
10.4
How to Read EXPLAIN
12 min
Read EXPLAIN and EXPLAIN ANALYZE step by step: access types, join order, cost and rows, estimates vs actual rows, and the red flags of a slow SQL query.
-
10.5
How B-tree Indexes Work
11 min
Understand how B-tree indexes are structured in SQL, why they accelerate search to logarithmic complexity, and how to use them in practical queries.
-
10.6
Full-Text Indexes
10 min
A full-text index finds rows by words in text columns, where LIKE '%word%' scans the whole table. Learn MySQL MATCH AGAINST and PostgreSQL full-text search.
11 Data Transformation and Manipulation for Analysis
-
11.1
Practical String Processing in SQL
10 min
Learn practical string processing in SQL: clean text values, extract email domains, build labels, and validate data quality.
-
11.2
Practical Use of Date and Time Functions
11 min
Learn practical date and time functions in SQL: build daily and monthly metrics, calculate intervals, detect seasonality, and prepare analytical reports.
12 Analysis of tasks
-
12.1
The fastest flight option
6 min
SQL task solution: find the fastest flight with one connection using a self-join of the flights table and interval arithmetic in PostgreSQL.
-
12.2
Calculate the average occupancy rate of flights
7 min
SQL task solution: average seat occupancy per airport and fare class with LEFT JOIN, COUNT FILTER and two levels of aggregation in PostgreSQL.
-
12.3
Aircraft Seat Map
5 min
SQL task solution: build an aircraft seat map by splitting seat numbers with rtrim and right and collecting the letters into a JSON array with json_agg.
-
12.4
Nth Highest Salary
7 min
Find the second or Nth highest salary in SQL: MAX with a subquery, LIMIT OFFSET, DENSE_RANK, a correlated subquery, ties, NULL results and groups.
-
12.5
Find and Delete Duplicate Rows
7 min
How to find duplicate rows in SQL with GROUP BY and HAVING, list every copy with a window function, delete duplicates while keeping one row, and prevent them.
-
12.6
Top N Rows per Group
7 min
Get the top N rows in each group in SQL: ROW_NUMBER with PARTITION BY, ties with RANK and DENSE_RANK, a correlated subquery, and LATERAL joins, on Sakila data.
-
12.7
Running Total
6 min
Calculate a running total in SQL with SUM() OVER (ORDER BY): cumulative revenue, totals that reset each year, the ROWS vs RANGE trap and an old-style solution.
-
12.8
Gaps and Islands
7 min
Solve gaps and islands in SQL: group consecutive dates with the ROW_NUMBER trick, find missing ranges with LEAD, and get each customer's longest streak.
-
12.9
Pivot Rows to Columns
7 min
Pivot rows into columns in SQL: conditional aggregation with SUM(CASE ...), a pivot by month, dynamic pivot in MySQL, the PIVOT operator and unpivot.