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.
Beginner
What a database is, reading and filtering data, NULL values, sorting, summarising, functions, CASE and changing rows.
- 1IntroductionWhat databases, tables, rows and columns are, and how to write your first SQL query.
- 2SELECTRead exactly the columns you need, rename them, calculate new values and remove duplicates.
- 3WHERE (Filtering)Return only the rows you need with comparisons, AND, OR, NOT, IN, BETWEEN, LIKE and IS NULL.
- 4NULL ValuesUnderstand what NULL means, test for it with IS NULL, replace it with COALESCE, and avoid the surprises NULL causes in comparisons, counts and NOT IN.
- 5ORDER BY & GROUP BYSort results, return only the top rows, and summarise data with COUNT, SUM, AVG and GROUP BY.
- 6FunctionsTransform values inside a query with string, number, date and NULL-handling functions.
Intermediate
Dates, table design, constraints, joins of every kind, UNION, subqueries, data cleaning and relationships.
- 9Dates & TimesStore, filter, group and calculate with dates in SQL, with the SQLite, MySQL and PostgreSQL versions side by side.
- 10CREATE & ALTER TABLEDesign your own tables: choose data types, create tables, change them with ALTER TABLE and remove them safely.
- 11Constraints & KeysProtect your data with NOT NULL, UNIQUE, DEFAULT, CHECK, PRIMARY KEY and FOREIGN KEY constraints.
- 12JOINCombine rows from related tables with INNER JOIN and LEFT JOIN, using keys and table aliases.
- 13More JoinsGo beyond INNER and LEFT JOIN: find unmatched rows, join a table to itself, combine everything with FULL OUTER and CROSS JOIN, and avoid the ON versus WHERE trap.
- 14UNION & Set OperationsStack the results of several queries with UNION and UNION ALL, and find overlaps and differences with INTERSECT and EXCEPT.
Show all 9 lessonsShow fewer
- 15Subqueries & CTEsUse the result of one query inside another with subqueries, IN, EXISTS, derived tables and WITH clauses.
- 16Data CleaningTidy messy data with SQL: trim spaces, standardise capitals, find and remove duplicates, turn blanks into NULL, convert text to numbers and spot invalid values.
- 17Table RelationshipsDesign tables that link together correctly: one-to-one, one-to-many and many-to-many relationships, foreign keys and junction tables.
Advanced
Normalization, views, CTEs, indexes, transactions, window functions, triggers and security for real-world databases.
- 18NormalizationDesign tables that avoid repeated data and update mistakes, using first, second and third normal form, and know when to denormalise.
- 19ViewsSave a query as a named view, query it like a table, and use views to simplify reports and limit access.
- 20CTEs & Recursive QueriesBreak complex queries into readable named steps with WITH, chain several CTEs, and use recursive CTEs for hierarchies and series of dates.
- 21Indexes & PerformanceSpeed up searches, joins and sorting with indexes, and check how a query runs with EXPLAIN.
- 22TransactionsGroup changes into all-or-nothing transactions with BEGIN, COMMIT and ROLLBACK, and understand ACID.
- 23Window FunctionsCalculate rankings, running totals and comparisons with previous rows using OVER, PARTITION BY and ORDER BY.
Show all 8 lessonsShow fewer
- 24Triggers & ProceduresRun SQL automatically when data changes with triggers, and save reusable routines in the database with stored procedures and functions.
- 25Security & PermissionsProtect databases from SQL injection with parameterized queries, give each user only the access they need with GRANT and roles, and follow everyday security habits.
Syntax and commands reference
Companions for reading SQL, filtering values, aliases and limiting result sets.
- 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.
- 27SQL operators and precedenceSQL operators compare or calculate values; precedence decides how a compound expression is grouped when parentheses do not specify the grouping.
- 28SELECT DISTINCTSELECT DISTINCT removes duplicate rows from a query result by comparing the complete combination of selected expressions.
- 29SQL aliasesAn SQL alias gives a column expression or table reference a temporary name within a query without renaming the stored database object.
- 30LIKE and wildcard patternsLIKE compares text with a pattern in which percent matches zero or more characters and underscore matches exactly one character.
- 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
- 32EXISTS and NOT EXISTSEXISTS is true when a subquery returns at least one row; NOT EXISTS is true when it returns no rows.
- 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.
- 34LIMIT, TOP and FETCH FIRSTLIMIT, TOP and FETCH FIRST restrict the number of returned rows, using syntax that depends on the database system.
- 35SQL keywords and commandsSQL keywords form statements that read data, change rows, define database objects, control transactions and manage permissions.
Functions and querying reference
Individual aggregate guides, functions, NULL policies, grouping and ordering.
- 36MIN()MIN() returns the smallest non-NULL value in a group of rows, or NULL when no known value is available.
- 37MAX()MAX() returns the largest non-NULL value in a group, with NULL returned when the group contains no known candidate.
- 38COUNT()COUNT(*) counts input rows, COUNT(expression) counts rows with a non-NULL expression, and COUNT(DISTINCT expression) counts different known values.
- 39SUM()SUM() adds the non-NULL numeric values in an input group, returning NULL when there are no known values to add.
- 40AVG()AVG() calculates the arithmetic mean of non-NULL input values, with a denominator equal to the number of known values.
- 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
- 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.
- 43SQL string functionsString functions transform, measure or extract text, allowing queries to clean labels and produce consistent display values without changing stored data.
- 44SQL numeric and mathematical functionsNumeric functions calculate or reshape numbers, while input types and rounding rules determine the precision of their results.
- 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.
- 46COALESCE and NULLIFCOALESCE returns the first non-NULL expression, while NULLIF returns NULL when its two expressions compare equal.
- 47Conditional aggregationConditional aggregation applies CASE inside an aggregate to calculate selected categories or measures in one grouped query.
- 48CAST() and CONVERT()CAST converts an expression to a specified type; CONVERT provides database-specific conversion features whose syntax and meaning vary.
- 49Multiple-column and NULL sortingORDER BY compares its expressions in sequence, and an explicit NULL sort key makes missing-value placement predictable across engines.
Database and table reference
Database objects, data types, keys, constraints, temporary tables and metadata.
- 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.
- 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.
- 52SQL data typesA data type defines how a column represents values and which ranges, comparisons and calculations are appropriate for those values.
- 53INSERT INTO SELECTINSERT INTO SELECT adds rows to an existing target table using the result of a query rather than a literal VALUES list.
- 54SELECT INTOSELECT INTO has dialect-specific meanings: SQL Server can create a table from a query, while other contexts use it to assign variables.
- 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
- 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.
- 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.
- 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.
- 59Temporary tablesA temporary table stores intermediate rows with an engine-defined session or transaction lifetime, separate from ordinary persistent application tables.
- 60Database schema and metadataA schema describes database objects and relationships, while metadata catalogs expose information about those objects, their columns and constraints.
Joins and advanced queries reference
Focused join and set-operation guides, subqueries, CTEs, recursion and pivoting.
- 61INNER JOININNER JOIN returns combinations of input rows that satisfy the join condition, excluding input rows that have no qualifying match.
- 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.
- 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.
- 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.
- 65UNION vs UNION ALLUNION combines compatible query results and removes duplicate selected rows, while UNION ALL preserves every row from each branch.
- 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
- 67Correlated subqueriesA correlated subquery references a value from an enclosing query, making its logical result depend on the current outer row.
- 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.
- 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.
- 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.
- 71Pivoting and conditional aggregationPivoting reshapes category values into separate output columns, often using conditional aggregation for a fixed set of categories.
Windows and performance reference
Ranking, comparisons, frames, execution plans, indexes, transactions and database routines.
- 72Ranking FunctionsNumber rows, rank tied values and select a dependable top result within each group.
- 73LAG and LEADCompare neighboring observations with explicit ordering, partitions and missing-value policies.
- 74Running Totals and AveragesCalculate cumulative values and rolling averages with explicit row frames and reliable ordering.
- 75Window Frames and PartitionsSeparate partitions, ordering and frames so window calculations use the intended rows.
- 76Index Types and Composite IndexesChoose indexes from query patterns and understand column order, coverage and write costs.
- 77EXPLAIN and Execution PlansRead access paths, row estimates and expensive operations without confusing estimates with measured time.
Show all 11 lessonsShow fewer
- 78Query OptimizationImprove a slow query through correctness checks, measured plans and indexes that fit its workload.
- 79ACID and Isolation LevelsUnderstand transaction guarantees, concurrent reads and why a complete transaction may need a retry.
- 80Deadlocks and LockingRecognize ordinary waiting, reproduce a deadlock safely and design short transactions with bounded retries.
- 81Procedures vs FunctionsChoose a database routine from its return contract, side effects, call site and engine restrictions.
- 82Trigger Use CasesUnderstand automatic database actions, row-versus-statement behavior and trigger side effects.
Practical SQL
Design from requirements, relationships, integrity, cleaning, data transfer, recovery and security.
- 83Database Design from RequirementsTurn business requirements into SQL tables, keys, relationships, constraints, and queries with a clear booking-system example.
- 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.
- 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.
- 86Normalization: 1NF, 2NF, 3NF and BCNFUnderstand SQL normalization through functional dependencies, update anomalies, composite keys, and practical 1NF-to-BCNF examples.
- 87Data Integrity and Referential IntegrityProtect SQL data with types, NOT NULL, CHECK, UNIQUE, primary keys and foreign keys, including null rules and concurrency limits.
- 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
- 89Importing and Exporting CSV DataImport and export CSV safely with staging, explicit columns, PostgreSQL COPY, MySQL LOAD DATA, and clear file-access differences.
- 90Database Backup and Restore BasicsUnderstand logical and physical database backups, recovery objectives, safe restore testing, and PostgreSQL, MySQL, SQL Server and SQLite differences.
- 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.
- 92Parameterized Queries and SQL Injection PreventionPrevent SQL injection by binding values, allowlisting identifiers, validating business input, and testing safe parameter behavior.
Dialects and SQL practice
Engine-specific starter guides, dialect comparisons, interviews, exercises and analytics projects.
- 93MySQL tutorialMySQL is a relational database server with its own SQL dialect, connection accounts and InnoDB transaction and relationship features.
- 94PostgreSQL tutorialPostgreSQL is a relational database server with strong type support, schemas, transactional features and a rich SQL dialect.
- 95SQL Server and T-SQLT-SQL is SQL Server’s SQL dialect, extending relational queries with variables, batches, identity columns and procedural features.
- 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.
- 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.
- 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
- 99SQL coding challengesSQL coding challenges practise transforming a precise result requirement into a query and validating it with deliberately chosen edge-case records.
- 100SQL exercises by difficultyDifficulty-based SQL exercises build from row filters to relationship summaries and window calculations, with clear prerequisites and checkable expected results.
- 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.
- 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,NULLvalues, 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
Practise SQL your way
Learning sticks when you use it. Pick a mode.
SQL Exercises
Fill in blanks, predict output and fix broken code with instant feedback.
202 exercisesSQL Quiz
5, 10 or 20 questions with a timer and explanations after every answer.
279 questionsSQL Cheat Sheet
Every important piece of syntax on one printable page.
Open cheat sheetLearning Paths
See where SQL fits in a complete roadmap, and what to learn next.
View learning pathsSQL 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?
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
MongoDB
The popular document database for flexible, JSON-like data at any scale.
Start MongoDBGit
Track every change to your code and never lose work again.
Start GitGitHub
Host your code online, collaborate with others and publish websites.
Start GitHubHTML
The skeleton of every web page. Start here.
Start HTMLCSS
Colours, fonts, spacing and layouts that make pages beautiful.
Start CSSJavaScript
The programming language that makes web pages interactive.
Start JavaScript