Skip to content
Justice Tech School

SQL Tutorial

Ask questions of your data.

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