Lessons › SQL
170 free lessons
SQL lessons
SQL for data analysts: free lessons for entry-level and junior roles, from your first SELECT to window functions, data cleaning and advanced analytics.
Chapter 1: Reading data
- SELECT all columnsSee a whole table
- SELECT specific columnsPick the columns you need
- Column aliases with ASGive a column a new name
- DISTINCT for unique valuesEach value once
- ORDER BY with single column and multiple columnsPut rows in order
- LIMITJust the first few rows
Chapter 2: Filtering
- FILTERING with WHEREKeep only the rows you want
- Combining WHERE with AND and ORTwo rules at once
- NOT operatorEverything except
- INMatch any value in a list
- BETWEENKeep values in a range
- LIKE and wildcardsSearch text with a pattern
- IS NULL and IS NOT NULLFind empty cells
Chapter 3: Summarising
- COUNT(*), COUNT(column), COUNT(DISTINCT)Three ways to count
- SUM()Add up a column
- AVG()The average
- MIN() and MAX()The smallest and the biggest
- GROUP BYOne total per group
- GROUP BY with multiple columnsGroups within groups
- HAVINGKeep only some groups
Chapter 4: Shaping data
- ROUND()Tidy decimals
- CASE WHENLabel each row
- Pivoting data with CASE WHENPivoting Retail Revenue with CASE WHEN
- COALESCE()Fill in empty cells
- CAST() and type conversionTurn text into numbers
- EXTRACT DATEOne part of a date
- DATE_TRUNC() for rounding dates to year, month, week or dayRound dates down
- Date difference functionsDays between two dates
Chapter 5: Joins, subqueries and CTEs
- INNER JOINMatching Retail Orders to Customers with INNER JOIN
- LEFT JOINKeeping All Retail Orders with LEFT JOIN
- RIGHT JOINKeeping All Customers with RIGHT JOIN
- Anti-join with LEFT JOIN and IS NULLFinding rows that don't match
- Multi-table joins across three or more tablesJoining three tables in one query
- SubqueriesA query inside a query
- More ways to use a subqueryTwo at once, side by side, or as a table
- CTEs with WITHTwo easy steps instead of one hard one
- Two CTEs in a rowStep one, step two, then the answer
- UNION and UNION ALLStack two lists into one
Chapter 6: Window Functions
- ROW_NUMBER() / RANK() / DENSE_RANK()Giving every row its place
- SUM() OVER (PARTITION BY) - partition totalA group total on every row
- Running totals with SUM() OVERA total that grows row by row
- LAG() and LEAD()Look at the row above or below
- Top N analysisThe best in each group
- Comparison vs previous periodDid it go up or down?
Chapter 7: Creating and changing tables
- CREATE TABLEMake a new, empty table
- INSERT INTOAdd rows to a table
- CREATE TABLE AS SELECTSave a query's results as a new table
- ViewsSave a query under a name
- UPDATE SETChange values that are already there
- DELETE FROMRemove rows you don't want
- ALTER TABLEAdd or rename a column
- DROP TABLERemove a table you've finished with
Chapter 8: Text, dates and safe maths
- Joining text with CONCAT and ||Put text together
- Part of a text: LEFT, RIGHT and SUBSTRINGTake just the bit you need
- Today's date and date mathsDays since, and the last 30 days
- Month and weekday names with TO_CHARDates as words
- Safe maths: empty cells, zero and whole numbersRates that don't break
- Comparing rows in one table: self joinA table joined to itself
Chapter 9: Data Cleaning
- TRIM() / UPPER() / LOWER() for text cleanupTidy spaces and capitals
- REPLACE() for fixing inconsistent valuesSwap one bit of text
- IS NULL and COALESCE() for missing dataFind and fill the gaps
- Counting NULLs per column with SUM(CASE WHEN ... IS NULL)How many empty cells in each column?
- Data profiling with MIN, MAX, COUNT DISTINCT, and AVGA quick health check
- Detecting duplicates with GROUP BY and HAVING COUNT(*) > 1Find repeated rows
- Removing duplicates with ROW_NUMBER() and DELETEKeep one copy, delete the rest
- Standardizing categories with CASE WHEN and LOWER()One spelling for each value
- Cleaning date formats with TO_DATE() and TO_CHAR()Turn text into real dates
- NULLIF() for converting placeholder values to NULLTurn fake values into empty cells
- Range checks and flagging values outside expected boundsCatch impossible values
- Before-and-after validation comparing row counts and sums after cleaningCheck the cleaning worked
Go further in SQL: Business questions
- What has Lagos never sold?Never means a list minus another list
- Who bought Earbuds but never a Charger?A but not B
- What's the revenue for each customer city?Join first, then group
- What share of revenue does each store bring?A part divided by the whole
- How did each store do in March vs February?Two months side by side
- Which stores went down from February to March?Work it out, then label it
- What % of each store's orders used a coupon?A rate: some of them divided by all of them
- How many orders are small, medium and large?Give each row a band, then count
- Which customers came back?A rule about a total goes in HAVING
- Which orders were keyed in twice?Group by everything except the id
- What's the second-highest order?Rank first, then pick the rank
- What's the best-selling product in each store?Total, then rank inside each group
- Which orders beat their own store's average?Each group's average, then compare
- What was each customer's first order?Number each group's rows, keep number 1
- Which weekday sells the most?Turn the date into a label, then group
- Which customers have gone quiet?Each customer's last order, against a date
- What was each store's month-on-month growth?This month against last, as a share of last
- How does revenue build up through March?A running total, day by day
- What's the 7-day average of daily sales?A window frame: this row and the 6 before it
- Show every month's revenue, with 0 for empty monthsA list of all the months, then a LEFT JOIN
- How many days between each customer's orders?LAG on dates
- Which customers bought in both February and March?EXISTS: is there a matching row?
- Of February's new customers, how many came back?Retention: first month, then check later
- Visit, cart, purchase: where do people drop off?A funnel: each step against the one before
- Which products make up the top 80% of revenue?Pareto: biggest first, a running share, then a cut-off
- Which products are bought together most often?A self join on the order
- Do the till and the warehouse agree?FULL OUTER JOIN: keep both sides
- Split customers into four spend groupsNTILE: equal groups
- List each customer's products on one lineSTRING_AGG: many rows into one text
- What's our longest run of days with a sale?Gaps and islands: days in a row share a gap from their row number
Go further in SQL: Database Admin & ETL
- Multi-row INSERTInserting many rows in one statement
- TRUNCATE TABLEClearing a Retail Staging Table with TRUNCATE TABLE
- Temporary tablesBreaking Retail Analysis into Steps with Temporary Tables
- Stored procedures vs functionsChoosing Between Stored Procedures and Functions in Retail SQL
- Writing a reusable cleaning function with CREATE FUNCTIONWriting a cleaning rule once, as a function
- Scheduling automated cleaning with pg_cronWriting the clean-up job a schedule runs
- Trigger-based validation that rejects bad insertsStopping bad rows at the door with a trigger
- Documenting cleaning rules with COMMENT ON TABLE and COMMENT ON COLUMNLeaving notes on tables and columns
- Building a cleaning log table to track changesKeeping a record of every fix
- UPDATE SET for correcting values in placeCorrecting Retail Product Values with UPDATE SET
- SCD Type 1: overwriting a changeWhen the old value doesn't matter: overwrite it
- SCD Type 2: keeping the historyWhen the old value matters: keep it
- ETL concepts in SQLExtract, transform, load: a reporting table in three steps
- Star schema basics: fact tables and dimension tablesUnderstanding Retail Star Schemas with Fact and Dimension Tables
Go further in SQL: Text, Date & Number Functions
- OFFSET with LIMIT for paginationSkipping rows with OFFSET
- CEIL() and FLOOR() for rounding up and downRounding up and down to whole numbers
- ABS()Measuring Retail Return Differences with ABS()
- NULLIF()Turning Placeholder Values into NULL with NULLIF()
- ILIKE and case-insensitive searchFinding Retail Text Matches with ILIKE
- INITCAP() or equivalentCleaning Retail Name Casing with INITCAP()
- AGE() for date intervalsHow long ago something happened
- LENGTH() and CHAR_LENGTH() for text lengthMeasuring how long text is
- POSITION() and STRPOS() for substring indexFinding where a character sits inside text
- LPAD() and RPAD() for padding textPadding text to a fixed width
- Combining columnsCombining Retail Customer Columns
- MOD operator (%) for modulo arithmeticSplitting Retail Orders into Groups with MOD
- Date conversion basicsTurning timestamps into dates
Go further in SQL: Advanced Joins & Subqueries
- FULL OUTER JOINAuditing Catalogue and Inventory with FULL OUTER JOIN
- CROSS JOINCreating Product-Store Planning Matrices with CROSS JOIN
- Multi-column join conditionsJoining on two columns at once
- Aggregate-then-join with subquery in FROMTotal first, then join
- LEFT JOIN with WHERE vs ON filter trapThe LEFT JOIN trap with WHERE on the right side
- One-to-many vs many-to-one relationshipsUnderstanding One-to-Many Retail Relationships
- EXISTS and NOT EXISTSChecking Related Retail Records with EXISTS and NOT EXISTS
- Nested subqueriesUsing Nested Subqueries for Retail Benchmarks
- Correlated subqueriesComparing Each Retail Order with a Correlated Subquery
- INTERSECT and EXCEPTComparing Retail Customer Sets with INTERSECT and EXCEPT
- Recursive CTEsWalking Retail Product Hierarchies with Recursive CTEs
- LATERAL joins for per-row correlated subqueriesPer-row correlated subqueries with LATERAL
- RANDOM() and ORDER BY RANDOM() for random samplingTaking Retail QA Samples with ORDER BY RANDOM()
Go further in SQL: Advanced Window Functions
- NTILE() for ranking into equal bucketsSplitting rows into equal-sized buckets
- AVG() / COUNT() / MIN() / MAX() OVERAdding Category Context with Aggregate Window Functions
- Partitions in window functionsResetting Retail Window Calculations with PARTITION BY
- Moving averages with AVG() OVERSmoothing Retail Sales Trends with Moving Averages
- FIRST_VALUE() / LAST_VALUE() / NTH_VALUE()Navigating Customer Order Values with FIRST_VALUE(), LAST_VALUE(), and NTH_VALUE()
- PERCENTILE_CONT() and PERCENTILE_DISC()Finding Typical Retail Order Value with Percentiles
- PERCENT_RANK() and CUME_DIST()Segmenting Retail Products with PERCENT_RANK() and CUME_DIST()
- GROUPING SETSCreating Multiple Retail Subtotals with GROUPING SETS
- ROLLUP for hierarchical totalsBuilding Retail Hierarchical Totals with ROLLUP
- CUBE for cross-tabulationCreating Retail Cross-Tab Totals with CUBE
- FILTER clause for conditional aggregationConditional aggregation with FILTER
- Window FRAME specification with ROWS BETWEENControlling the window with ROWS BETWEEN
- STRING_AGG()Combining Retail Details with STRING_AGG()
Go further in SQL: Business Analytics Patterns
- GENERATE_SERIES() for date ranges and gap fillingFilling Retail Date Gaps with GENERATE_SERIES()
- Reconciliation queriesDo two systems agree?
- Correlation with CORR()Do two numbers move together?
- Trend lines with REGR_SLOPE() and REGR_INTERCEPT()How much do sales change per dollar?
- Gaps and islands patternFinding consecutive runs (gaps and islands)
- Sessionization with LAG and cumulative SUMGrouping visits into sessions
- Cohort retention analysisCohort retention
- Funnel conversion analysisFunnel conversion
- Pareto 80-20 cumulative analysisPareto analysis - finding the 80%
- Market basket analysis with self-joinMarket basket - products bought together
Go further in SQL: Data Validation
- DISTINCT ON for keeping one row per duplicate groupKeeping One Retail Order per Customer with DISTINCT ON
- Detecting negative values where only positives are expectedDetecting Impossible Negative Retail Values
- Regular expressions for email and phone validationValidating Retail Customer Contact Patterns with Regex
- Cross-field validationChecking Retail Fields Against Each Other
- Unit and format inconsistenciesOne unit, one format
- Referential integrity checks across tablesChecking Broken Retail Relationships Across Tables
- Unexpected category checksChecking Retail Products for Unexpected Categories