SQL Tutorial
Ask questions of your data.
Getting started2 lessons
Querying data7 lessons
Filtering4 lessons
Changing data3 lessons
Functions6 lessons
Grouping2 lessons
Joins and combining data6 lessons
Subqueries4 lessons
Creating databases and tables4 lessons
Constraints and keys6 lessons
AdvancedPremium7 lessons
- 45ViewsSaved queries that act like tables.
- 46TransactionsAll or nothing changes.
- 47SQL InjectionThe attack that tricks your queries.
- 48SQL OperatorsArithmetic, comparison and logical operators.
- 49CommentsNotes in SQL.
- 50Database Design BasicsNormalisation and relationships.
- 51What Next?Where to go after the basics.
Advanced SQLPremium19 lessons
- 52Window FunctionsA window function calculates across related rows without collapsing them like GROUP BY.
- 53PARTITION BYPARTITION BY splits the window into groups, so the calculation restarts for each group.
- 54Running Totals and Moving AveragesAn aggregate with OVER and ORDER BY accumulates row by row.
- 55LAG and LEADLAG reads a value from a previous row and LEAD from a following row.
- 56NTILE and FIRST_VALUENTILE splits ordered rows into equal buckets such as quartiles.
- 57Common Table ExpressionsWITH names a temporary result you can use like a table in the main query.
- 58Chaining CTEsSeparate several CTEs with commas.
- 59Recursive CTEsA recursive CTE refers to itself, which handles hierarchies and sequences.
- 60Generating Series with RecursionRecursive CTEs can create numbers or dates without a table.
- 61Conditional Aggregation and PivotsPut CASE inside SUM or COUNT to count by condition in one pass.
- 62Correlated SubqueriesA correlated subquery refers to the outer row, so it runs once per row.
- 63EXISTS versus IN and NOT EXISTSEXISTS checks whether any matching row exists and stops at the first.
- 64UNION, INTERSECT and EXCEPTSet operators combine results of two queries with the same columns.
- 65Aggregating TextGROUP_CONCAT (STRING_AGG in other databases) joins values from many rows into one string, .
- 66JSON in SQLModern databases store and query JSON.
- 67Dates and Time ArithmeticStore dates in a standard format such as ISO 8601.
- 68UPSERT: Insert or UpdateON CONFLICT lets an insert update the existing row when a unique key already exists.
- 69RETURNING and Bulk ChangesRETURNING gives back the rows an INSERT, UPDATE or DELETE changed, saving an extra query.
- 70TriggersA trigger runs SQL automatically when rows change.
SQL in practicePremium11 lessons
- 71NULL PitfallsNULL means unknown.
- 72Pagination: OFFSET and KeysetLIMIT with OFFSET is simple but slow for deep pages.
- 73Changing Data SafelyPreview an UPDATE or DELETE with a SELECT using the same WHERE.
- 74Indexing StrategyIndex columns used in WHERE, JOIN and ORDER BY, put equality columns before range columns .
- 75Avoiding Slow Query PatternsAvoid SELECT *, functions on indexed columns in WHERE, leading wildcards in LIKE, N+1 quer.
- 76SQL Injection and Least PrivilegeNever build SQL by joining strings with user input.
- 77Schema Design HabitsUse clear singular or plural names consistently, a primary key on every table, foreign key.
- 78Reporting Query PatternsReports combine joins, grouping, CTEs and windows.
- 79Migrations and Testing QueriesChange schemas with versioned migration scripts that can be repeated and reviewed.
- 80Differences Between DatabasesStandard SQL works almost everywhere, but details differ: LIMIT versus TOP, AUTOINCREMENT .
- 81SQL Best PracticesWrite readable queries with consistent capitals and indentation, name columns clearly, avo.
More SQL basics57 lessons
- 82Expressions in SELECTSELECT can calculate values, not just read columns.
- 83Sorting by Several ColumnsList several columns in ORDER BY.
- 84LIMIT and OFFSETLIMIT caps the rows returned and OFFSET skips rows first.
- 85COUNT DISTINCTCOUNT(DISTINCT col) counts unique values.
- 86Comparison OperatorsUse = <> != < > <= >= in WHERE.
- 87IN and NOT ININ tests membership in a list and is shorter than many ORs.
- 88BETWEEN with DatesBETWEEN is inclusive on both ends.
- 89LIKE Patterns% matches any run of characters and _ matches exactly one.
- 90IS NULL and IS NOT NULLNULL is unknown, so = NULL never works.
- 91CASE for LabelsCASE returns different values by condition, like if else.
- 92Aggregate Functions TogetherCOUNT, SUM, AVG, MIN and MAX summarise many rows into one.
- 93GROUP BY More Than One ColumnEach unique combination of the grouped columns becomes one row.
- 94HAVING versus WHEREWHERE filters rows before grouping.
- 95INNER JOIN in PracticeINNER JOIN keeps rows with a match in both tables.
- 96LEFT JOIN to Find GapsLEFT JOIN keeps every left row.
- 97Self JoinJoin a table to itself with two aliases to follow relationships inside one table.
- 98CROSS JOINCROSS JOIN pairs every row with every row.
- 99UNION and UNION ALLUNION removes duplicates and UNION ALL keeps them.
- 100Subquery in WHEREA subquery returns a value or list for the outer query to use.
- 101Subquery in FROMA subquery in FROM acts as a temporary table and needs an alias.
- 102Insert Several RowsOne INSERT can add many rows with comma separated value lists.
- 103UPDATE with WHEREWithout WHERE an UPDATE changes every row.
- 104DELETE SafelyDELETE removes rows.
- 105CREATE TABLEDefine columns, types and constraints.
- 106ALTER TABLE ADD COLUMNALTER TABLE changes structure.
- 107DEFAULT and CHECKDEFAULT fills missing values.
- 108Foreign KeysA foreign key links a column to a primary key in another table and keeps data consistent.
- 109IndexesAn index speeds up lookups on a column but slows writes a little.
- 110ViewsA view is a saved query you can select from like a table.
- 111TransactionsA transaction groups statements so they all succeed or all roll back.
- 112Joining TextUse || in SQLite and PostgreSQL, CONCAT in MySQL, to join text.
- 113SUBSTR, REPLACE and TRIMSUBSTR cuts text, REPLACE swaps parts and TRIM removes spaces.
- 114Numbers: ROUND, ABS, moduloROUND rounds, ABS removes the sign and % gives a remainder.
- 115COALESCE and NULLIFCOALESCE returns the first non-NULL value.
- 116Date BasicsStore dates as ISO text.
- 117Counting by MonthGroup by strftime to build time reports.
- 118Top N per GroupUse ROW_NUMBER in a subquery to get the best row per group.
- 119EXISTSEXISTS is true if the subquery returns any row.
- 120ANY and ALL AlternativesCompare with a list using MAX or MIN when ANY and ALL are missing, as in SQLite.
- 121INSERT ... SELECTCopy rows between tables by inserting the result of a query.
- 122Simple PaginationPage n of size s uses LIMIT s OFFSET (n-1)*s.
- 123DISTINCTDISTINCT removes duplicate rows from the result.
- 124Table AliasesShort aliases make joins easier to read.
- 125Counting Groups with NULLNULL values form their own group in GROUP BY.
- 126Sorting and NULLNULLs sort first in SQLite ascending.
- 127PercentagesMultiply by 100.0 to avoid integer division and ROUND the result.
- 128Finding DuplicatesGROUP BY with HAVING COUNT(*) > 1 shows repeated values.
- 129Joining Three TablesChain joins one at a time.
- 130Revenue ReportJoin and SUM to build money reports.
- 131CASE PivotSUM with CASE turns categories into columns.
- 132WITH for Readable QueriesA WITH clause names a step of the query.
- 133Sanity ChecksCompare counts before and after joins to catch duplicated rows.
- 134NULL and JoinsNULL never equals NULL, so rows with NULL keys do not join.
- 135Comments and Formatting-- starts a line comment and /* */ a block.
- 136Practice: Top StudentsCombine WHERE, ORDER BY and LIMIT to list the top three scorers.
- 137Practice: Average per CountryGROUP BY with AVG gives a per-group average.
- 138Practice: Unenrolled StudentsLEFT JOIN and IS NULL find rows with no match.