For working with data yourself

6 chapters · 18 lessonsAbout 2 h

SQL Fundamentals

Beginner

Go from reading a database to shaping it. Build the queries day-to-day analysis needs, then create tables, indexes, and views of your own.

This course continues from SQL Introduction

Coming Soon

About this course

The introductory course taught you to read a database with SQL. Now you shape one.

Every lesson starts from a situation you will meet at work: sales by month, customers who never ordered, month-over-month change. Solving it is what makes the new syntax necessary.

The database is a simulation checked byte for byte against real PostgreSQL 17, down to the query planner. When you add an index, it speeds things up (or does not) exactly as the real thing would.

Sample Lessons

Skills you'll learn

Build the Everyday Queries

CASE, dates, subqueries, CTEs, and window functions: the shapes real analysis is made of.

Create Tables That Cannot Break

Types, constraints, and foreign keys keep bad data out from the start.

Check the Speed and Fix It

Read a query plan and see for yourself whether an index helped.

Who this course is for

Finished SQL Introduction

Beyond filter, summarize, and join: build the queries you will actually be asked for every day.

Always Asking for the Monthly Numbers

Group by month, rank rows, compare with the previous period. The everyday shapes of analysis, written by you.

Ready to Own the Tables

Constraints, indexes, views. Build tables that cannot break, make them fast, and give the queries you use a name.

Syllabus

6 chapters · 18 lessons

1Changing Values by Condition
2Changing Types
3Summarizing by Date
4Filtering by a Recent Period

Keys and commands

Changing Values by Condition

CASE WHEN price >= 200 THEN 'premium' WHEN price >= 50 THEN 'standard' ELSE 'budget' END AS tier
Values by condition
CASE status WHEN 'paid' THEN 'to ship' WHEN 'shipped' THEN 'done' ELSE status END AS status
Map the values of one column
sum(CASE WHEN status = 'cancelled' THEN 1 ELSE 0 END)
Count rows that match
COALESCE(coupon_code, 'none')
Replace NULL

Changing Types

round( sum(CASE … END)::numeric * 100 / count(*), 1)
Cast to numeric before dividing (integers truncate)

Summarizing by Date

date_trunc('month', order_date)::date
Group by month

Filtering by a Recent Period

WHERE order_date >= current_date - interval '14 days'
The last 14 days

Filtering by Another Query's Result

WHERE price > ( SELECT avg(price) FROM products)
Subqueries
WHERE id IN ( SELECT customer_id FROM orders
In another query’s result
WHERE code NOT IN ( SELECT coupon_code FROM orders WHERE coupon_code IS NOT NULL)
Drop NULLs before NOT IN (one NULL gives 0 rows)

Naming an Intermediate Result

WITH monthly AS ( SELECT … GROUP BY month) SELECT round(avg(sales), 2) FROM monthly;
Name a step
SELECT month, sales FROM monthly WHERE sales > ( SELECT avg(sales) FROM monthly)
Read the same name more than once

Stacking and Subtracting Results

UNION
Stack, without duplicates
UNION ALL
Keep duplicates
EXCEPT
First minus second
SELECT o.customer_id FROM orders o … UNION SELECT customer_id FROM page_views WHERE product_id = 16 AND customer_id IS NOT NULL;
Buyers and viewers, one row each

Ranking Rows

rank() OVER (ORDER BY units DESC)
Ties share a rank
dense_rank() OVER (ORDER BY units DESC)
Ties share a rank, with no gaps

Ranking Within Groups and Keeping the Top Rows

row_number() OVER ( PARTITION BY category ORDER BY sales DESC)
Number and rank rows
SELECT name, category, units, sales, place FROM in_category WHERE place <= 2
Name the numbers first, then filter outside

Previous Rows and Running Totals

lag(sales) OVER (ORDER BY month)
Previous row, running total
sum(sales) OVER (ORDER BY month)
Previous row, running total
sales - lag(sales) OVER (ORDER BY month)
Change from the previous month
lead(sales) OVER (ORDER BY month)
Value from the next row
lag(sales) OVER ( PARTITION BY category ORDER BY month)
Previous month, per category

Creating a Table

CREATE TABLE reviews ( id integer GENERATED ALWAYS AS IDENTITY PRIMARY KEY, … created_at timestamptz NOT NULL DEFAULT now() );
Create a table
INSERT INTO reviews (product_id, customer_id, rating, body) VALUES (9, 1, 5, 'Sharp and bright.');
Leave out id and created_at (filled in)
ALTER TABLE reviews ADD COLUMN title text;
Add a column

Adding Constraints

WHERE NOT EXISTS ( SELECT 1 FROM products p WHERE p.id = r.product_id)
No matching row exists
ALTER TABLE reviews ADD FOREIGN KEY (product_id) REFERENCES products (id);
Constraints
ADD CHECK (rating >= 1 AND rating <= 5)
Constraints
ADD UNIQUE (product_id, customer_id)
No pair twice
DELETE FROM customers WHERE id = 13;
A customer that reviews point to cannot be deleted

Reading the Plan and Creating an Index

CREATE INDEX ON page_views (product_id);
Find fast (indexes)
EXPLAIN SELECT id, product_id FROM page_views WHERE viewed_on = '2026-08-15';
See which scan it uses
EXPLAIN ANALYZE SELECT id, viewed_on FROM page_views WHERE product_id = 7;
Run it and show the actual rows
WHERE viewed_on::text = '2026-08-15'
Changing the column stops the index
DROP INDEX orders_coupon_code_idx;
Drop an index

Creating Views

CREATE VIEW in_stock AS SELECT id, name, price, stock FROM products WHERE stock > 0;
Save a query (views)
UPDATE in_stock SET stock = 10 WHERE id = 10;
A simple view can be updated (it changes the table)
// READY?

BEGIN YOUR
JOURNEY

Join thousands of developers who've mastered the terminal. Your first lesson awaits.

Get Started →