1. Home
  2. Explore
  3. Computer Science
  4. SQL Full Course Tutorial

Study methods

Flashcards
Quiz
Fill in the blanks
Written test
Lesson
Notes
Podcast
Content

SQL Full Course Tutorial

SQL for Data Engineering – Comprehensive Study Notes

Course Overview

This course teaches SQL from a data engineering perspective, covering both fundamental query writing and production-level pipeline building. The course is split into two halves:

  • First Half: SQL basics (SELECT, WHERE, GROUP BY, JOINs), environment setup (MotherDuck, DuckDB, VS Code, Terminal), dimensional modeling, and an exploratory data analysis (EDA) project.

  • Second Half: Production SQL (DDL/DML for table creation, data loading, and incremental updates), advanced data modeling (star schema, slowly changing dimensions), CTEs, subqueries, window functions, nested data, Git/GitHub branching, and a final end-to-end data warehouse and data mart pipeline project.

The course uses DuckDB as the database engine (fast, free, open‑source, analytics‑focused) with MotherDuck as the cloud platform. All tools used are free and open‑source.


What is SQL?

SQL (Structured Query Language) is the language used to communicate with relational databases. The acronym CRUD summarizes the operations:

  • Create – add new records (e.g., INSERT)

  • Read – retrieve data (e.g., SELECT)

  • Update – modify existing records (e.g., UPDATE)

  • Delete – remove records (e.g., DELETE)

SQL commands are grouped into three categories:

  • DQL (Data Query Language): Reading data (SELECT)

  • DML (Data Manipulation Language): Creating, updating, deleting data in existing tables (INSERT, UPDATE, DELETE, MERGE)

  • DDL (Data Definition Language): Creating or deleting schemas and tables (CREATE, ALTER, DROP)


Databases: Relational vs. Non‑Relational

  • Relational databases: Store data in rows and columns with relationships (e.g., foreign keys). Used in analytics and business applications. Examples: PostgreSQL, MySQL, DuckDB.

  • Non‑relational (NoSQL): Store data in various forms – key‑value, document, graph, column‑family. The term “NoSQL” stands for “Not Only SQL.”

This course focuses on relational databases and uses DuckDB, a column‑oriented, embeddable SQL database optimized for analytical queries.


DuckDB and MotherDuck

  • DuckDB: A free, open‑source, in‑process SQL database designed for analytics. It runs locally on your machine and can be used via CLI, Python, or the MotherDuck UI.

  • MotherDuck: A commercial SaaS platform that hosts DuckDB databases in the cloud. It provides a web‑based UI (notebook) and allows sharing databases with other tools (Tableau, Power BI, etc.). The free tier is sufficient for the entire course.

Installation: For Windows, use WinGet (e.g., winget install DuckDB.CLI). For Mac, use Homebrew (brew install duckdb). Always check MotherDuck’s supported DuckDB version to avoid incompatibility.


SQL Environment Setup

MotherDuck (Browser‑Based)

  • Sign up at loopb.co/motherduck (no credit card required).

  • Use the Notebook interface to write and execute SQL cells.

  • Attach databases (e.g., the provided data_jobs database) using the ATTACH command.

  • The UI includes an Inspector panel for exploring column statistics.

Terminal & DuckDB CLI

  • Mac: Terminal app (Z‑shell). Install DuckDB via Homebrew.

  • Windows: Windows Terminal with Git Bash (installed with Git for Windows). Install DuckDB via WinGet.

  • Basic terminal commands: pwd (print working directory), ls (list), cd (change directory), mkdir (make directory), touch (create file), rm (remove), cat (display file contents), echo (output text), nano (text editor).

  • Run DuckDB in memory: duckdb

  • Connect to a database file: duckdb mydatabase.duckdb

  • Execute SQL from command line: duckdb -c "SELECT 42;"

  • Read a SQL script: .read path/to/file.sql

VS Code (Code Editor)

  • Install VS Code from code.visualstudio.com.

  • Open a project folder, create .sql files.

  • Use the integrated terminal (`Ctrl + ``) to run DuckDB commands.

  • Key binding: Set Shift+Enter to send selected SQL text to the terminal (Preferences > Keyboard Shortcuts > search “terminal run selected text in active terminal”).

  • Optionally install GitHub Copilot (can be turned off during learning).

Connecting DuckDB to MotherDuck

  • Obtain an access token from MotherDuck Settings > Access Tokens.

  • Set the environment variable MOTHERDUCK_TOKEN in your shell profile (e.g., ~/.zshrc for Mac, ~/.bashrc for Windows Git Bash) to avoid repeated login.

  • Connect: duckdb md:data_jobs (replaces data_jobs with your database name).

  • The token is stored permanently by adding export MOTHERDUCK_TOKEN='your_token_here' to the shell config file.


Basic SQL Keywords

SELECT and FROM

SELECT column1, column2 
FROM table_name;
  • SELECT * returns all columns.

  • Indentation and line breaks improve readability but do not affect execution.

LIMIT

  • Restricts the number of rows returned.

  • Always use LIMIT when building queries on large datasets to avoid high costs.

DISTINCT

  • Returns unique values from a column.

SELECT DISTINCT job_title_short FROM job_postings_fact;

WHERE

  • Filters rows based on conditions.

  • Text values must be enclosed in single quotes.

  • Numeric values are written without quotes.

  • Use IS NULL or IS NOT NULL to check for null values (do not use = NULL).

Comments

  • Single line: -- comment

  • Multi‑line: /* comment */

ORDER BY

  • Sorts result set. Default ascending (ASC); specify DESC for descending.

  • Placed after WHERE (or after FROM if no WHERE), before LIMIT.

Clause Order (SQL Sequence)

SELECT 
FROM 
WHERE 
GROUP BY 
HAVING 
ORDER BY 
LIMIT

Violating this order produces a parser error.

Semicolons

  • End each SQL statement with a semicolon (;). Important when running multiple statements or in scripts.


Operators

Comparison Operators

  • =, !=, <> (not equal), >, <, >=, <=

  • IS NULL, IS NOT NULL

  • LIKE – pattern matching with wildcards (see below)

  • BETWEEN – inclusive range (e.g., salary BETWEEN 100000 AND 200000)

  • IN – check against a list of values (e.g., job_title_short IN ('Data Engineer', 'Data Analyst'))

Logical Operators

  • AND – all conditions must be true.

  • OR – at least one condition must be true.

  • NOT – negates a condition (e.g., NOT job_work_from_home).

Parentheses () are used to group conditions for clarity and correct evaluation order.


Wildcards and LIKE

  • _ – matches exactly one character.

  • % – matches zero or more characters.

Use LIKE with wildcards to search for patterns in text.

SELECT job_title FROM job_postings_fact 
WHERE job_title LIKE '%Data%Engineer%';

Aliases

Renaming columns or tables for readability.

  • Column alias: Use AS (optional) after the column name.

SELECT job_id AS id, job_location AS location FROM job_postings_fact;
  • Table alias: Defined after the table name, often used in JOINs.

SELECT jpf.job_id FROM job_postings_fact AS jpf;
  • Aliases can be used in ORDER BY but not in WHERE or GROUP BY in most databases (DuckDB is more permissive).


Arithmetic Operators

  • +, -, *, /, % (modulus)

  • Used in SELECT, WHERE, and other clauses.

  • Example: salary_year_avg * 1.2 to compute a 20% higher salary.

  • Modulus (%) returns the remainder of division; useful for checking even/odd.


Aggregate Functions

  • COUNT(* – counts all rows including nulls.

  • COUNT(column) – counts non‑null values.

  • SUM(column) – adds up non‑null numeric values.

  • AVG(column) – average of non‑null numeric values.

  • MIN(column) – smallest non‑null value.

  • MAX(column) – largest non‑null value.

  • MEDIAN(column) – median value (DuckDB extension). Less affected by outliers than average.

GROUP BY

  • Groups rows with the same values in specified columns into summary rows.

  • All columns in SELECT that are not aggregated must appear in GROUP BY.

  • DuckDB allows GROUP BY ALL to automatically include all non‑aggregated columns.

HAVING

  • Filters groups after aggregation (cannot use WHERE on aggregate results).

  • Placed after GROUP BY, before ORDER BY.

Using Aliases with Aggregates

  • DuckDB allows alias usage in GROUP BY and HAVING; many other databases do not. Write full column names for portability.


Data Modeling (Part 1)

Database Hierarchy

Database
  ├── Schema
  │     ├── Table
  │     ├── View
  │     └── Semantic Layer (functions, macros, metrics)
  └── Security (users, roles, permissions)
      └── Metadata (information schema)

Primary Keys and Foreign Keys

  • Primary Key (PK): Unique identifier for each row in a table.

  • Foreign Key (FK): A column that references the primary key of another table, establishing a relationship.

Entity Relationship Diagram (ERD)

  • Shows tables (entities), their columns, and relationships (lines).

  • One‑to‑One: One record in Table A links to exactly one in Table B.

  • One‑to‑Many: One record in Table A links to many in Table B (most common).

  • Many‑to‑Many: Avoid if possible; use a bridge table.

Star Schema

  • Central fact table contains measurable business data (e.g., job postings).

  • Surrounding dimension tables contain descriptive attributes (e.g., company, skills).

  • Fact tables have foreign keys to dimension tables.

Information Schema

  • A set of read‑only views that describe the database metadata.

  • Common across databases (SQL standard).

  • Query: SELECT * FROM information_schema.tables WHERE table_catalog = 'data_jobs';

  • Other useful views: columns, table_constraints, key_column_usage.

DuckDB‑Specific Metadata Commands

  • DESCRIBE table_name; – shows column names, data types, nullability, key constraints.

  • PRAGMA show_tables; – lists tables in the current schema.


Joins

Combining rows from two or more tables based on related columns.

INNER JOIN

  • Returns only rows where there is a match in both tables.

  • Default join (can be written as just JOIN).

LEFT JOIN (or LEFT OUTER JOIN)

  • Returns all rows from the left table, and matched rows from the right table. Unmatched right side is NULL.

RIGHT JOIN

  • Returns all rows from the right table, and matched rows from the left. Unmatched left side is NULL. Less common; can be rewritten as LEFT JOIN by swapping tables.

FULL OUTER JOIN

  • Returns all rows when there is a match in either table. Unmatched sides are NULL. Useful for finding orphan records.

JOIN Syntax

SELECT a.column, b.column
FROM table_a AS a
LEFT JOIN table_b AS b ON a.key = b.key;

Using Joins with Multiple Tables

  • Example: Connect job postings to skills via bridge table.

  • Use aliases for clarity (e.g., job_postings_fact AS jpf).


Order of Execution (SQL Query Processing)

The database engine processes queries in the following logical order (not the same as writing order):

  1. FROM / JOIN – identifies source tables and combines them.

  2. WHERE – filters rows.

  3. GROUP BY – groups rows.

  4. HAVING – filters groups.

  5. SELECT – selects columns and computes expressions.

  6. ORDER BY – sorts results.

  7. LIMIT – limits rows.

EXPLAIN and EXPLAIN ANALYZE

  • EXPLAIN shows the query plan (estimates, not executed).

  • EXPLAIN ANALYZE executes the query and shows actual execution statistics (times, row counts).

  • Reading the plan: start from the bottom (table scans) and move up (joins, filters, aggregations).


DDL and DML Basics

DDL (Data Definition Language)

  • CREATE DATABASE, CREATE SCHEMA, CREATE TABLE, ALTER TABLE, DROP, TRUNCATE.

DML (Data Manipulation Language)

  • INSERT, UPDATE, DELETE, MERGE.

CREATE TABLE

CREATE TABLE schema_name.table_name (
    column1 INTEGER PRIMARY KEY,
    column2 VARCHAR(100),
    column3 DOUBLE,
    FOREIGN KEY (column1) REFERENCES other_table(other_column)
);
  • Include IF NOT EXISTS for idempotency.

DROP TABLE / TRUNCATE TABLE

  • DROP TABLE removes the table schema and data completely.

  • TRUNCATE TABLE removes all rows but keeps the table structure (faster than DELETE without WHERE).

INSERT INTO

INSERT INTO table (col1, col2) VALUES (val1, val2);

UPDATE

UPDATE table SET column = new_value WHERE condition;

MERGE (Upsert)

Combines INSERT, UPDATE, and DELETE in one statement.

MERGE INTO target_table AS t
USING source_table AS s ON t.key = s.key
WHEN MATCHED THEN UPDATE SET t.column = s.column
WHEN NOT MATCHED THEN INSERT (columns) VALUES (s.columns)
WHEN NOT MATCHED BY SOURCE THEN DELETE;
  • Used for incremental (batch) updates to maintain a snapshot table.

ALTER TABLE

  • ADD COLUMN, DROP COLUMN, RENAME COLUMN, RENAME TO, ALTER COLUMN ... TYPE.


Data Types

Numeric

  • INTEGER – whole numbers.

  • BIGINT, SMALLINT – larger/smaller ranges.

  • DOUBLE – approximate decimal with high precision (64‑bit).

  • FLOAT – lower precision (32‑bit).

  • DECIMAL(precision, scale) – exact decimal (e.g., DECIMAL(10,2)).

Character (Text)

  • CHAR(n) – fixed length, padded with spaces.

  • VARCHAR(n) – variable length.

  • TEXT – unbounded length.

Boolean

  • BOOLEAN – TRUE or FALSE; stored as 0/1.

Date/Time

  • DATE – year, month, day.

  • TIME – hours, minutes, seconds.

  • TIMESTAMP – date and time (without time zone).

  • TIMESTAMP WITH TIME ZONE – includes time zone information.

Casting

  • Convert between types using CAST(expr AS type) or ::type (PostgreSQL‑style).

  • Example: CAST(123 AS VARCHAR) or 123::VARCHAR.

  • Not all conversions are allowed (e.g., 'abc'::INTEGER fails).


Data Modeling (Part 2) – Design Patterns

Source Systems vs. Analytical Systems

  • Source systems: OLTP (Online Transaction Processing) – optimized for high‑velocity writes, normalized schemas. Examples: ERP (Oracle, SAP), CRM (Salesforce).

  • Analytical systems: OLAP (Online Analytical Processing) – optimized for large scans and aggregations, star schemas. Examples: DuckDB, Snowflake, BigQuery, Redshift.

Star Schema (most common for DWH)

  • One central fact table, multiple dimension tables.

  • Fact table contains quantitative measures; dimensions contain descriptive attributes.

Normalized Schema (common in OLTP)

  • Data split into many related tables to avoid duplication. Hundreds of tables.

Other Schemas

  • Galaxy/Constellation: Multiple fact tables sharing dimensions.

  • Snowflake: Dimension tables further normalized into sub‑dimensions (less common).

  • Factless Fact Table: Contains only foreign keys, no measures.

  • Bridge Table: Resolves many‑to‑many relationships between fact and dimension tables.

  • Flat/Wide Table: Denormalized single table, fast for read‑heavy reporting.

Slowly Changing Dimensions (SCD)

Method to track historical changes in dimension tables.

  • Type 0: Fixed, immutable.

  • Type 1: Overwrite – no history kept.

  • Type 2: Add new row – tracks full history.

  • Type 3: Add new attribute column – tracks only the last change.

  • Type 4: History table – current data in main table, history moved to a separate table.


Case Expressions

Apply conditional logic within a query.

CASE 
    WHEN condition1 THEN result1
    WHEN condition2 THEN result2
    ELSE default_result
END AS alias

Common Use Cases

  1. Bucketing: Group values into categories (e.g., low/medium/high salary).

  2. Handling NULLs: Explicitly map NULL to a meaningful value.

  3. Categorizing text: Classify job titles using LIKE (e.g., WHEN job_title LIKE '%Data%Analyst%' THEN 'Data Analyst').

  4. Conditional Aggregation: Use inside aggregate functions to compute separate measures for different conditions (e.g., MEDIAN(CASE WHEN salary < 100000 THEN salary END) AS median_low).


Date Functions

EXTRACT

  • Pulls a specific part from a date/timestamp (e.g., YEAR, MONTH, DAY, HOUR, QUARTER).

EXTRACT(YEAR FROM job_posted_date) AS job_year

DATE_TRUNC

  • Rounds a date down to the start of a specified precision (e.g., MONTH, YEAR, WEEK).

DATE_TRUNC('month', job_posted_date) AS month_start

AT TIME ZONE

  • Converts a timestamp from one time zone to another.

  • For TIMESTAMP (no time zone), use two AT TIME ZONE calls: first to set the source time zone, then to convert to target.

job_posted_date AT TIME ZONE 'UTC' AT TIME ZONE 'EST' AS est_time
  • Useful for analyzing data in local time zones.


Set Operators

Combine results from two or more queries.

  • UNION – returns distinct rows from both queries.

  • UNION ALL – returns all rows, including duplicates.

  • INTERSECT – returns rows common to both queries, duplicates removed.

  • INTERSECT ALL – returns common rows preserving duplicates (row‑by‑row match).

  • EXCEPT (or MINUS) – returns rows from the first query not in the second, duplicates removed.

  • EXCEPT ALL – removes matching rows one‑by‑one, preserving unmatched duplicates.

Rules:

  • Both queries must have the same number of columns.

  • Corresponding columns must have compatible data types.

  • Column names come from the first query.


Text and NULL Functions

Text Functions

  • LENGTH(string) – number of characters.

  • LOWER(string), UPPER(string) – case conversion.

  • TRIM(string) – removes leading/trailing whitespace.

  • LEFT(string, n), RIGHT(string, n) – extract first/last n characters.

  • SUBSTRING(string, start, length) – extract part of a string.

  • CONCAT(string1, string2) – concatenate strings (or use || operator).

  • REPLACE(string, old, new) – replace occurrences.

  • REGEXP_REPLACE – regular expression replacement.

NULL Functions

  • NULLIF(expr1, expr2) – returns NULL if both expressions are equal; otherwise returns expr1. Useful for converting zeros to NULL.

  • COALESCE(expr1, expr2, ...) – returns the first non‑NULL expression. Great for combining multiple columns (e.g., COALESCE(salary_year_avg, salary_hour_avg * 2080) to get a standardized yearly salary).


Window Functions

Perform calculations across a set of rows related to the current row without collapsing the result set.

Syntax

window_function(column) OVER (
    PARTITION BY column
    ORDER BY column
)
  • PARTITION BY – divides rows into groups (like GROUP BY but preserves rows).

  • ORDER BY – defines the order within each partition (required for ranking and running totals).

Types of Window Functions

  1. Aggregate: SUM, AVG, COUNT, MIN, MAX – compute running totals or averages.

  2. Ranking: RANK(), DENSE_RANK(), ROW_NUMBER() – assign a rank or sequential number.

    • RANK() leaves gaps when there are ties.

    • DENSE_RANK() does not leave gaps.

    • ROW_NUMBER() gives each row a unique number (even if ties).

  3. Navigation: LAG(column) – get the value from the previous row; LEAD(column) – get the value from the next row. Useful for time‑series comparisons.


Nested Data Types

  • Array (List): Ordered collection of same‑type values, indexed starting from 1. Syntax: [1, 2, 3].

  • Struct (Record): Composite type with named fields. Syntax: {'field1': value1, 'field2': value2}.

  • Array of Structs: An array where each element is a struct. Common for storing multiple related attributes per row.

  • Map (Dictionary): Key‑value pairs; order not guaranteed. Less common for analytics.

  • JSON: Text‑based format often received from APIs. Needs to be parsed into structs or arrays for efficient querying.

Key Functions

  • Creating arrays/structs: ARRAY_AGG(...), STRUCT_PACK(...)

  • Unnesting: UNNEST(array) to expand an array into multiple rows.

  • Accessing array elements: array[1] (1‑based index in DuckDB).

  • Accessing struct fields: struct.field_name

  • JSON to struct: json_extract_string(json, '$.key') or struct_pack with extracted values.


Project 1: Exploratory Data Analysis (EDA)

Objective

Act as a job market analyst to answer three questions about data engineering jobs (remote positions in the US, or adapt to your preference):

  1. Top demanded skills – count of job postings per skill.

  2. Highest paying skills – median salary per skill (use MEDIAN), include demand count for context.

  3. Most optimal skills – balance demand and salary using a calculated optimal score (e.g., LN(demand_count) * median_salary / 1e6).

Queries Use

  • Inner joins (to filter jobs with skills).

  • Aggregations (COUNT, MEDIAN, ROUND).

  • GROUP BY, HAVING (to filter skills with sufficient demand).

  • ORDER BY and LIMIT.

Deliverables

  • Three .sql files with problem statement, query, results (commented), and insights.

  • A README.md in the 1_EDA folder with:

    • Executive summary (for hiring managers).

    • Problem context.

    • Tech stack (DuckDB, SQL, VS Code, Git/GitHub).

    • Analysis overview with links to queries.

    • Key insights.

    • SQL skills demonstrated (joins, aggregations, etc.).


Git and GitHub

Git Basics

  • Working Directory – where you edit files.

  • Staging Area – prepare changes for commit.

  • Local Repository – stores committed snapshots.

  • Remote Repository (GitHub) – central location for collaboration.

Essential Git Commands

  • git init – initialize a repo.

  • git status – view status.

  • git add . – stage all changes.

  • git commit -m "message" – commit staged changes.

  • git push – push local commits to remote.

  • git pull – fetch and merge remote changes.

  • git remote add origin <url> – link local repo to remote.

Branching

  • Create a branch: git branch feature/my-branch or git switch -c feature/my-branch.

  • Switch branch: git switch branch-name.

  • Merge: git merge feature-branch (while on target branch).

  • Delete branch: git branch -d feature-branch (local); git push origin --delete feature-branch (remote).

Pull Requests (PR)

  • Used to propose changes and request code review.

  • Branches are merged via PR after approval.

.gitignore

  • Lists files/directories that Git should ignore (e.g., .duckdb, *.csv, .env, data/, __pycache__/).

  • Add early in the project to avoid accidentally committing large or sensitive files.


Project 2: Production Data Pipeline

Objective

Build an end‑to‑end SQL pipeline:

  1. Data Warehouse (star schema) – fact table (job_postings_fact) and dimension tables (company_dim, skills_dim, skills_job_dim).

  2. Flat Mart – denormalized, single‑table mart with skills as array of structs.

  3. Skills Mart – dimensional mart with fact table aggregated by skill, month, and job title; includes star schema design with foreign keys.

  4. Priority Mart – mart that maintains a snapshot of priority jobs, updated incrementally using MERGE.

Git Workflow for Project 2

  • main – stable final code.

  • develop – integration branch for project 2.

  • Feature branches from develop (e.g., feature/data-warehouse, feature/flat-mart).

  • Commit each major addition; merge into develop when complete.

Key Files

  • 01_create_tables_dw.sql – DDL to create warehouse tables.

  • 02_load_schema_dw.sql – DML to insert data from CSV files (hosted on Google Cloud Storage) using read_csv with auto_detect.

  • 03_create_flat_mart.sql – CTAS to create denormalized flat mart.

  • 04_create_skills_mart.sql – DDL + DML for skills fact and dimension tables.

  • 05_create_priority_mart.sql – DDL + DML for priority roles and initial snapshot.

  • 06_update_priority_mart.sql – Simulated update to priority roles + incremental merge.

  • build_dw_mart.sql – Master script that calls all above .sql files with .read commands, enabling one‑command pipeline rebuild.

Cloud Deployment

  • Once built locally, the same master script can be run on MotherDuck by switching the DuckDB command to duckdb md:warehouse_name.

  • Share the database via MotherDuck’s sharing feature (generate an ATTACH command).


Final Steps: Certificate and LinkedIn

  1. Certificate: Complete the end‑of‑course survey to receive a certificate. Add it to LinkedIn under Licenses & Certifications.

  2. Add Project to Profile: Under Projects, add the GitHub repo link, description, and skills (SQL, Git, DuckDB, Data Modeling, ETL).

  3. Make a LinkedIn Post: Announce completion, tag the instructor, include a project image or snippet, and link to the repository. Engage with comments to increase visibility.


“Many thanks for completing this course. You now have the SQL skills and two portfolio projects to demonstrate your data engineering capabilities. Keep building and sharing!”

Ask anything

We've read this whole study set, so questions about it get the best answers.

FlashcardsQuizFill in the blanksWritten testLessonNotesPodcastContent