102 lessons

SQL Tutorial for Beginners

Learn SQL step by step, from your first SELECT to joins, window functions, database design and security, with SQL examples that work in MySQL, PostgreSQL, SQL Server and SQLite.

Browse all 102 lessons by stage

Lessons
102
Code examples
157
Exercises
202
Quiz questions
279

SQL course at a glance

Who it's for

Beginners, data and business analysts, back-end developers and anyone who answers questions from a database.

Prerequisites

None. If you've used a spreadsheet, you already understand tables, rows and columns.

What you need

SQLite with DB Browser for SQLite is the easiest start; MySQL, PostgreSQL and SQL Server work too.

How long it takes

One to two months for the 25 core chapters at five hours a week; read references as needed.

SQL roadmap: beginner to advanced

Work through the 25 core chapters in the first three stages in order, then use the reference stages to go deeper. Each reference lesson links to its prerequisite and includes examples, practice and a quiz.

4

Syntax and commands reference

Companions for reading SQL, filtering values, aliases and limiting result sets.

  1. 26SQL syntax and commentsSQL syntax defines how keywords, names, values and punctuation form valid database statements; comments explain a statement without becoming part of its calculation.
  2. 27SQL operators and precedenceSQL operators compare or calculate values; precedence decides how a compound expression is grouped when parentheses do not specify the grouping.
  3. 28SELECT DISTINCTSELECT DISTINCT removes duplicate rows from a query result by comparing the complete combination of selected expressions.
  4. 29SQL aliasesAn SQL alias gives a column expression or table reference a temporary name within a query without renaming the stored database object.
  5. 30LIKE and wildcard patternsLIKE compares text with a pattern in which percent matches zero or more characters and underscore matches exactly one character.
  6. 31IN, BETWEEN, ANY and ALLIN tests membership, BETWEEN tests an inclusive range, and ANY or ALL compare a value with values returned by a subquery.
Show all 10 lessonsShow fewer
  1. 32EXISTS and NOT EXISTSEXISTS is true when a subquery returns at least one row; NOT EXISTS is true when it returns no rows.
  2. 33IS NULL and IS NOT NULLIS NULL tests whether a value is missing, while IS NOT NULL tests whether it is present; neither uses ordinary equality.
  3. 34LIMIT, TOP and FETCH FIRSTLIMIT, TOP and FETCH FIRST restrict the number of returned rows, using syntax that depends on the database system.
  4. 35SQL keywords and commandsSQL keywords form statements that read data, change rows, define database objects, control transactions and manage permissions.
5

Functions and querying reference

Individual aggregate guides, functions, NULL policies, grouping and ordering.

  1. 36MIN()MIN() returns the smallest non-NULL value in a group of rows, or NULL when no known value is available.
  2. 37MAX()MAX() returns the largest non-NULL value in a group, with NULL returned when the group contains no known candidate.
  3. 38COUNT()COUNT(*) counts input rows, COUNT(expression) counts rows with a non-NULL expression, and COUNT(DISTINCT expression) counts different known values.
  4. 39SUM()SUM() adds the non-NULL numeric values in an input group, returning NULL when there are no known values to add.
  5. 40AVG()AVG() calculates the arithmetic mean of non-NULL input values, with a denominator equal to the number of known values.
  6. 41Aggregate vs window functionsOrdinary aggregation collapses rows into groups, while a window function calculates across related rows and keeps the individual result rows.
Show all 14 lessonsShow fewer
  1. 42GROUP BY and HAVINGGROUP BY forms summary groups, WHERE filters input rows before grouping, and HAVING filters the resulting groups by a group-level condition.
  2. 43SQL string functionsString functions transform, measure or extract text, allowing queries to clean labels and produce consistent display values without changing stored data.
  3. 44SQL numeric and mathematical functionsNumeric functions calculate or reshape numbers, while input types and rounding rules determine the precision of their results.
  4. 45SQL date and time functionsDate and time functions extract calendar parts, perform temporal arithmetic and format values, with substantial syntax and time-zone differences between databases.
  5. 46COALESCE and NULLIFCOALESCE returns the first non-NULL expression, while NULLIF returns NULL when its two expressions compare equal.
  6. 47Conditional aggregationConditional aggregation applies CASE inside an aggregate to calculate selected categories or measures in one grouped query.
  7. 48CAST() and CONVERT()CAST converts an expression to a specified type; CONVERT provides database-specific conversion features whose syntax and meaning vary.
  8. 49Multiple-column and NULL sortingORDER BY compares its expressions in sequence, and an explicit NULL sort key makes missing-value placement predictable across engines.
6

Database and table reference

Database objects, data types, keys, constraints, temporary tables and metadata.

  1. 50CREATE DATABASE and DROP DATABASECREATE DATABASE creates a database container in a server system; DROP DATABASE removes that container and its data, with permissions and syntax depending on the engine.
  2. 51CREATE, ALTER and DROP TABLECREATE TABLE defines a new table, ALTER TABLE changes an existing definition, and DROP TABLE removes the table object and its stored rows.
  3. 52SQL data typesA data type defines how a column represents values and which ranges, comparisons and calculations are appropriate for those values.
  4. 53INSERT INTO SELECTINSERT INTO SELECT adds rows to an existing target table using the result of a query rather than a literal VALUES list.
  5. 54SELECT INTOSELECT INTO has dialect-specific meanings: SQL Server can create a table from a query, while other contexts use it to assign variables.
  6. 55DEFAULT, CHECK and UNIQUE constraintsDEFAULT supplies an omitted value, CHECK restricts allowed row values, and UNIQUE prevents duplicate key values according to the engine’s rules.
Show all 11 lessonsShow fewer
  1. 56AUTO_INCREMENT and identity columnsGenerated identity columns assign identifier values during insertion using an engine-specific mechanism such as AUTO_INCREMENT, identity or an SQLite integer primary key.
  2. 57Primary keys and composite keysA primary key uniquely identifies every row and requires non-NULL key values; a composite key identifies a row through a combination of columns.
  3. 58Foreign keys and referential actionsA foreign key requires a child reference to match an allowed parent key, with referential actions defining what happens when that parent is updated or deleted.
  4. 59Temporary tablesA temporary table stores intermediate rows with an engine-defined session or transaction lifetime, separate from ordinary persistent application tables.
  5. 60Database schema and metadataA schema describes database objects and relationships, while metadata catalogs expose information about those objects, their columns and constraints.
7

Joins and advanced queries reference

Focused join and set-operation guides, subqueries, CTEs, recursion and pivoting.

  1. 61INNER JOININNER JOIN returns combinations of input rows that satisfy the join condition, excluding input rows that have no qualifying match.
  2. 62LEFT, RIGHT and FULL OUTER JOINOuter joins preserve unmatched rows from one or both inputs, adding NULL placeholders for the side that has no qualifying match.
  3. 63Self joins and cross joinsA self join uses the same table in multiple roles, while CROSS JOIN returns every combination of rows from its two inputs.
  4. 64Anti-joins and unmatched recordsAn anti-join returns rows from one input that have no qualifying match in another, commonly expressed with NOT EXISTS or LEFT JOIN and a missing-key test.
  5. 65UNION vs UNION ALLUNION combines compatible query results and removes duplicate selected rows, while UNION ALL preserves every row from each branch.
  6. 66INTERSECT and EXCEPTINTERSECT returns selected rows common to two query results, while EXCEPT returns selected rows from the first result that are absent from the second.
Show all 11 lessonsShow fewer
  1. 67Correlated subqueriesA correlated subquery references a value from an enclosing query, making its logical result depend on the current outer row.
  2. 68Derived tablesA derived table is a query result used as a table input within an enclosing statement, usually written as a parenthesised SELECT in FROM.
  3. 69Common table expressionsA common table expression, or CTE, names a query result with WITH so it can be used within the single statement that follows.
  4. 70Recursive queriesA recursive query combines an initial result with repeated query steps that consume the previous result, making it possible to traverse hierarchies of variable depth.
  5. 71Pivoting and conditional aggregationPivoting reshapes category values into separate output columns, often using conditional aggregation for a fixed set of categories.
9

Practical SQL

Design from requirements, relationships, integrity, cleaning, data transfer, recovery and security.

  1. 83Database Design from RequirementsTurn business requirements into SQL tables, keys, relationships, constraints, and queries with a clear booking-system example.
  2. 84Entity-Relationship (ER) DiagramsRead and draw ER diagrams, translate one-to-many and many-to-many cardinality into SQL keys, and distinguish optional from required links.
  3. 85One-to-One, One-to-Many and Many-to-Many RelationshipsModel SQL relationship types using foreign keys, uniqueness, nullability, and junction tables with practical enrollment examples.
  4. 86Normalization: 1NF, 2NF, 3NF and BCNFUnderstand SQL normalization through functional dependencies, update anomalies, composite keys, and practical 1NF-to-BCNF examples.
  5. 87Data Integrity and Referential IntegrityProtect SQL data with types, NOT NULL, CHECK, UNIQUE, primary keys and foreign keys, including null rules and concurrency limits.
  6. 88SQL Data Cleaning and DeduplicationClean SQL data with explicit normalization rules, duplicate grouping, ROW_NUMBER review, deterministic survivors, and safe staging.
Show all 10 lessonsShow fewer
  1. 89Importing and Exporting CSV DataImport and export CSV safely with staging, explicit columns, PostgreSQL COPY, MySQL LOAD DATA, and clear file-access differences.
  2. 90Database Backup and Restore BasicsUnderstand logical and physical database backups, recovery objectives, safe restore testing, and PostgreSQL, MySQL, SQL Server and SQLite differences.
  3. 91SQL Security, Roles and PermissionsDesign SQL roles and permissions with least privilege, separate runtime and migration accounts, and understand PostgreSQL, MySQL and SQL Server differences.
  4. 92Parameterized Queries and SQL Injection PreventionPrevent SQL injection by binding values, allowlisting identifiers, validating business input, and testing safe parameter behavior.
10

Dialects and SQL practice

Engine-specific starter guides, dialect comparisons, interviews, exercises and analytics projects.

  1. 93MySQL tutorialMySQL is a relational database server with its own SQL dialect, connection accounts and InnoDB transaction and relationship features.
  2. 94PostgreSQL tutorialPostgreSQL is a relational database server with strong type support, schemas, transactional features and a rich SQL dialect.
  3. 95SQL Server and T-SQLT-SQL is SQL Server’s SQL dialect, extending relational queries with variables, batches, identity columns and procedural features.
  4. 96SQLite tutorialSQLite is an embedded relational database engine that usually stores a database in a file and runs inside the application rather than as a separate server.
  5. 97SQL dialect differencesSQL dialect differences are variations in syntax, types and semantics between database systems that must be checked when translating a query or schema.
  6. 98SQL interview questionsSQL interview preparation combines relational concepts, precise result-shape reasoning and queries whose behaviour is tested on ties, NULL values and missing matches.
Show all 10 lessonsShow fewer
  1. 99SQL coding challengesSQL coding challenges practise transforming a precise result requirement into a query and validating it with deliberately chosen edge-case records.
  2. 100SQL exercises by difficultyDifficulty-based SQL exercises build from row filters to relationship summaries and window calculations, with clear prerequisites and checkable expected results.
  3. 101SQL business query problemsBusiness SQL problems require translating metric definitions, record relationships and completeness rules into queries that can be reconciled with their source events.
  4. 102SQL reporting projectsA SQL analytics project combines defined metrics, reproducible source data, layered queries and validation so report values can be explained and maintained.

What is SQL?

SQL (Structured Query Language, often pronounced "sequel") is the language used to talk to relational databases: programs that store data in tables made of rows and columns, a bit like very powerful spreadsheets.

Almost every app you use keeps its data in a database. Your bank balance, the products in an online shop, the messages in a chat app and the scores in a game are all stored in tables, and SQL is how developers, analysts and data scientists read and change that data.

How the course is organised

The course has a core path of 25 chapters in three stages, followed by seven reference stages:

  • Beginner: tables and keys, SELECT, WHERE, NULL values, sorting and summarising, functions, CASE, and adding, changing and removing rows.
  • Intermediate: dates, creating tables, constraints, every kind of JOIN, UNION, subqueries, cleaning messy data and relationships between tables.
  • Advanced: normalisation, views, CTEs, indexes, transactions, window functions, triggers and procedures, and database security.

The reference stages go deeper into syntax and commands, functions and aggregates, database and table definitions, joins and advanced queries, window functions and performance, and practical topics such as design from requirements, data cleaning, CSV import, backups and permissions. The final stage covers MySQL, PostgreSQL, SQL Server and SQLite individually, dialect differences, interview questions, exercises by difficulty and analytics projects.

How to follow this course

Work through the 25 core chapters in order. They use one small shop database with customers, products and orders, so you always know what each query should return. The reference lessons use their own small, self-contained datasets, which you can create with the setup script at the top of each lesson. Every lesson has worked examples with their results, common mistakes, exercises, a quiz and frequently asked questions.

Practise with SQLite, which needs no server, or with the database you use at work. Where MySQL, PostgreSQL, SQL Server and SQLite behave differently, the lesson tells you. Check your progress with the SQL exercises and the course quiz, then apply what you've learned in the business query problems and the analytics projects.

SQL pairs naturally with a programming language: Python for data analysis and backends, PHP and Java for web applications. The learning paths show where SQL fits in each route.

<!-- php-sql-reference-guide --> Each reference lesson names its prerequisite chapter, so you can always tell what to read first, and every reference adds practice questions to the course quiz.

What you will learn

10 practical skills, built one lesson at a time

  • Explain tables, rows, columns, primary keys and foreign keys
  • Read, filter, sort and summarise data, and handle NULL correctly
  • Transform text, numbers and dates with functions and CASE
  • Add, change, remove and clean data safely
  • Combine tables with every type of JOIN, UNION and subqueries
  • Design related tables with constraints and normalization
  • Write readable complex queries with CTEs and recursive queries
  • Speed up queries with indexes and keep data safe with transactions
  • Rank rows and build running totals with window functions
  • Automate rules with triggers and prevent SQL injection with parameterized queries
102 lessons157 examples202 exercises

Practise SQL your way

Learning sticks when you use it. Pick a mode.

SQL FAQ

Is SQL a programming language?

SQL is a query language. Instead of writing step-by-step instructions, you describe the result you want, such as "the names of customers in Leeds", and the database works out how to get it. That makes it quicker to learn than most programming languages.

Which database should I install to practise SQL?

SQLite is the easiest: it's a single small program with no server to set up, and tools such as DB Browser for SQLite give you a friendly window to run queries. MySQL and PostgreSQL are the most common choices for websites and are also good to learn.

How long does it take to learn SQL?

With about five hours a week, the beginner stage takes one to two weeks and the 25 core chapters about one to two months. Writing fast queries for very large datasets takes longer, but the core chapters cover what most jobs in data and web development need day to day, and the reference lessons go deeper.

Do I need SQL for web development?

Most websites store their data in a database, so back-end developers use SQL all the time, often from languages like Python or PHP. Front-end developers benefit from knowing the basics too.

Is SQL useful for data analysis?

Very. Analysts use SQL every day to pull data out of company databases, and advanced features such as window functions and CTEs are a standard part of data analyst interviews.

Is this SQL course free?

Yes. Every lesson, exercise, quiz and the cheat sheet is free to use, with no account or sign-up needed.

Which database does this course use?

The core chapters are written in standard SQL and tested on SQLite, and they also work on MySQL, PostgreSQL and SQL Server, with any differences explained. The reference stage on dialects has starter guides for each of the four systems.

Do I need to know a programming language before learning SQL?

No. SQL is a good first technical skill on its own, especially for analysts. Developers use it from languages such as Python, PHP and Java, and the parameterized queries lesson shows how to do that safely.

Does this course prepare me for SQL interviews?

It covers what SQL interviews usually test: joins, grouping, subqueries, window functions, NULL handling and indexes. Practise with the interview questions and coding challenges, explaining each step of your query aloud.

More tutorials