SQL Full Course for Beginners - Learn SQL from Scratch (1 HOUR!)

Timestamps

  • - Intro
  • - What is SQL?
  • - An example query
  • - When to use the native database procedural language
  • - ORMs
  • - Projection and selection
  • - Select and insert statements
  • - DDL and DML
  • - Creating a table
  • - Transactions
  • - Data types
  • - Constraints
  • - Another create table example
  • - Intermediate queries
  • - Functions, alias, CASE
  • - Sums and aggregate functions
  • - GROUP BY
  • - HAVING vs WHERE
  • - Joining data across tables
  • - Three table join
  • - Views
  • - What's next?

SQL is the language you use to talk to a relational database. Even if you've never written a query before you can follow along, and we'll gradually get in to the more intermediate stuff. If you know the basics already, use the timestamps to jump around.

The video is all on a chalkboard, so there's no database to look at. For these notes I filled in some sample rows and ran everything on Postgres 18, so the result tables are real output. If primary keys, foreign keys and relationships are new to you, go through the database design course first.

What is SQL?

SQL stands for Structured Query Language. It's a standard, so you learn it once and it works with pretty much any relational database, so anything that works with tables. Even databases that aren't relational often have some language that's very similar.

Not every database follows the standard 100% though. MySQL is slightly different than Postgres, but it's not like you learn 25% here and then have to go study the other 75%. Most of this is the same everywhere, 90 to 99%, and then you might have slightly different names for data types, or a feature that only exists in one database.

These variations are called dialects. Postgres, MySQL, Oracle, SQL Server, DB2, SQLite, and the list just goes on and on.

An example query

When you use SQL to ask the database for something it's called a query. Here's a quick one to see what it looks like:

SQL
SELECT video_id
FROM videos
WHERE duration > 90;

It reads pretty much like English. Give me the video IDs from the videos table where the duration is over 90.

SQL is declarative, which means you say what you want, not how to get it. You give the query to the database management system and its query planner figures out the actual steps to get that data.

Most of the time you can just let the database do its job. If you need to see the details to optimize something, put EXPLAIN in front:

SQL
EXPLAIN SELECT video_id
FROM videos
WHERE duration > 90;

On a small test table in Postgres I get this (your cost numbers will be different):

 Seq Scan on videos  (cost=0.00..25.00 rows=400 width=4)
   Filter: (duration > 90)

Seq Scan means it's reading through the table. The Postgres EXPLAIN docs go through how to read these.

The opposite of declarative is imperative, where you write out every step, similar to Python or JavaScript. Databases usually have one of these too, a procedural language that runs inside the database:

database procedural language
Postgres PL/pgSQL
SQL Server T-SQL
Oracle PL/SQL

We're focusing on the declarative part here. For most of the logic you'd use a regular programming language that connects to the database through a library, also called an adapter or driver. So you'd use a Postgres library in Python, send it SQL, and do whatever you want with the results.

When to use the native database procedural language

If you're building a custom app that works with the database (most likely the case), use your programming language.

The procedural language comes in when you need something in the database that you can't easily do through a driver, like a custom trigger or a database function. And even then, you can often write it in a language you already know. Postgres has PL/Python for example.

So there are three different things going on:

  • SQL, the declarative language for the database
  • procedural languages like PL/pgSQL or PL/Python, which are specific to the database
  • your application language, like Python, JavaScript, Rust or Go, which connects to the database

ORMs

Within your programming language you'll usually go one of two ways. Either a direct connection through the driver where you write the SQL, or an ORM (object relational mapper), which is a library that abstracts away some of the SQL so you work with objects.

Instead of the query above, you might have something like this:

JavaScript
videos.findMany({ where: { duration: { gt: 90 } } })

The exact syntax is different for every library, so don't memorize that one. It's still based on the same ideas as SQL.

                programming language
                  /              \
       direct connection         ORM
         (driver, SQL)      (library, objects)
                  \              /
                        SQL
                         |
                      database

There are pros and cons to both, but both end up as SQL that's given to the database. There's a very small chance you'll only ever write SQL directly to the database. Even database administrators are often building scripts or wrappers so they aren't always connecting directly.

Table and column names

OK, back to the query. The table is in the FROM, so ours is called videos. You'll see singular and plural table names, I prefer plural.

videos

video_id video_name duration
12 funny cats 30
13 funny dogs 120
14 funny babies 90

I use underscores in names, because in Postgres videoName is turned in to lowercase unless you put it in quotes. So if you make a column with quotes and forget them later:

SQL
CREATE TABLE casing_example ("videoName" text);

SELECT videoName FROM casing_example;
ERROR:  column "videoname" does not exist
HINT:  Perhaps you meant to reference the column "casing_example.videoName".

Now you have to put quotes all over the place, which is super annoying to type and easy to mess up. Casing rules vary by database, but you avoid the whole thing with snake case.

  • custom names (tables, columns): lowercase snake_case
  • keywords: uppercase, like SELECT, FROM and WHERE

The uppercase isn't required. I don't know why they decided on that, but it's pretty universal.

Result set

videos is the source table, and what you get back is the result set. With the query from above, only funny dogs has a duration over 90, and we only asked for the ID:

video_id
13

If we change funny babies to 190 and add duration to the select:

SQL
SELECT video_id, duration
FROM videos
WHERE duration > 90;
video_id duration
13 120
14 190

If you want every column, use an asterisk:

SQL
SELECT *
FROM videos
WHERE duration > 90;
video_id video_name duration
13 funny dogs 120
14 funny babies 190

Projection and selection

Two formal terms you might run in to:

  • projection - deciding what columns are retrieved (the SELECT list)
  • selection - deciding what rows are retrieved (the WHERE)

These come from relational algebra, which is also where words like join and union come from. Mostly what I care about is how to store data and get it back out, so I'll leave it at that and you can do additional research if you're interested.

Select and insert statements

A SELECT retrieves data, so that's a query. What about creating a table or updating data? Technically I don't think that's a query, since a query is asking for data, but in practice people say query for pretty much anything you send to the database.

If we're being technical, everything is a statement. A SELECT statement is a query, and an INSERT statement isn't, it puts data in to the database.

DDL and DML

It helps me to group things so I can reason about all the different options. There are two main categories:

  • DDL (data definition language) works with the structure
  • DML (data manipulation language) works with the actual data

I wouldn't really think of them as separate languages, it's all SQL. They're categories. You'll also see a few others:

category stands for statements
DDL data definition language CREATE, ALTER, DROP
DML data manipulation language INSERT, UPDATE, DELETE, SELECT
DQL data query language SELECT (some people put it here instead of in DML)
DCL data control language GRANT, REVOKE
TCL transaction control language BEGIN, COMMIT, ROLLBACK

DCL is for permissions, like letting a database user select from a certain table. I don't use it super often since I'm usually going through a programming language instead of individual database users, but you might do it once or twice for the initial setup.

Creating a table

Start with the table name, then each column with its data type and any constraints:

SQL
CREATE TABLE videos (
    video_id integer GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
    duration integer NOT NULL,
    title text NOT NULL
);

(this is a new videos table, so if you made the one above, drop it or use a separate database).

Data types are often lowercase in Postgres and uppercase in other databases. GENERATED ALWAYS AS IDENTITY is Postgres having the world's longest name for auto increment, it just counts up 1, 2, 3 for each row. NOT NULL means the column is required, since null means no value.

ALTER TABLE

Use ALTER to change a table that already exists:

SQL
ALTER TABLE videos
ADD COLUMN description text;

Every row in a table has the same structure. If there are 1000 videos in there, all 1000 now have a description, and it's null. That's different from a lot of NoSQL databases, where the structure can vary between entries.

DROP TABLE

This removes the table and all of the data in it, no oopsies. I have it commented out so you can keep it in a script without running it:

SQL
/* DROP TABLE videos; */

There's also DROP DATABASE, if you're feeling like getting fired.

INSERT

You list the columns, then each row goes in its own parentheses. We skip video_id because it's generated for us. Strings use single quotes:

SQL
INSERT INTO videos (title, duration)
VALUES ('SQL Basics', 720), ('SQL Advanced', 750);

SELECT * FROM videos;
video_id duration title description
1 720 SQL Basics null
2 750 SQL Advanced null

Leave out something that's NOT NULL and the database says no:

SQL
INSERT INTO videos (title) VALUES ('Git');
ERROR:  null value in column "duration" of relation "videos" violates not-null constraint

UPDATE

SQL
UPDATE videos
SET title = 'SQL'
WHERE video_id = 1;

Do NOT forget the WHERE. If you leave it off, it matches everything and every video in the table gets the title SQL. I feel like the statement should just fail, or you should have to explicitly say match all, but that's not the case.

If you're only updating one row, match it by ID.

DELETE

Very similar, and the same danger:

SQL
DELETE FROM videos
WHERE video_id = 2;
video_id duration title description
1 720 SQL null

Before you modify data, run a select with the same WHERE so you can see exactly which rows match. If you expect five rows and get 500, you probably did something wrong. Get the select right and then switch it to an update or delete:

SQL
SELECT * FROM videos
WHERE video_id = 2;

If you only care about how many rows, use a count. Say you want to delete all the videos under a minute:

SQL
SELECT count(*) FROM videos
WHERE duration < 60;
count
0

None of ours are, so a delete with that condition would remove nothing.

💡 Tip[!tip]
If you mix up the words, DDL always has TABLE in it here: CREATE TABLE, ALTER TABLE, DROP TABLE. DML doesn't: INSERT INTO videos, UPDATE videos, DELETE FROM videos.

Transactions

Say you have a three step process. The first step works and the second one fails. You don't want to go on to the third, you want to undo everything, so either it all works or none of it does. That's what a transaction is for.

There are two ways they help. One is grouping a multi-step process like that. The other is wrapping your own work, where you start a transaction, go line by line, and only commit once you're confident the changes are what you wanted. That one can also help you keep your job.

Let's say both SQL videos are still in the table, and you forget the WHERE:

SQL
BEGIN;

DELETE FROM videos;

SELECT count(*) FROM videos;
count
0

Oh no. But you haven't committed, so roll it back:

SQL
ROLLBACK;

SELECT count(*) FROM videos;
count
2

If you were happy with it, you'd say COMMIT; instead of ROLLBACK; and that completes the transaction. You can put as many steps as you want between BEGIN and COMMIT.

How you run it matters. In a terminal you send one command at a time, so you can decide what to do after seeing what happened. If it's a script, the whole thing runs in one go.

The classic example is money. You subtract $500 from one account, and adding it to the other account fails for some reason. Now you just deleted $500. Both need to work or both need to fail.

If nothing errors but the result isn't what you wanted, it's not going to automatically roll back. Logic like that might get you in to the procedural language.

💡 Tip[!tip]
In Postgres, an error inside a transaction means nothing in it will be saved, but you still have to end it. Until you do, every command gives you current transaction is aborted, commands ignored until end of transaction block. Run ROLLBACK (even a COMMIT at that point does a rollback). Other databases handle an error differently, MySQL for example can keep the earlier statements, so check yours.

If you're using a driver or an ORM, look up how transactions work in that library. Some have a transaction object you need to use, and some might be using transactions automatically. The Postgres transactions tutorial is a good short read too.

Data types

Data is stored as binary, so how do we know if that binary is a number or a letter? That's the data type, and it also determines how things behave.

A good example is sorting. If you store numbers in a text column and sort them:

text sort integer sort
1 1
11 2
2 11
22 22

The text one is a lexicographic sort, it goes character by character, so 11 comes before 2 because 1 is less than 2. If you need to sort by value, use a number type.

Here are the main ones for Postgres. Names vary by database but you'll have similar ones, and the full list is in the docs:

kind types
whole numbers integer, bigint
fractional numbers float, numeric
strings text, varchar, char
true or false boolean
dates and times date, time, timestamp, timestamptz
unique identifiers uuid
other jsonb, bytea, arrays like integer[]

Numbers

bigint is 64 bit, so it allows much larger numbers than integer.

For fractional numbers, numeric is exact and float can have rounding errors:

SQL
SELECT 0.1::float + 0.2::float AS with_float,
       0.1::numeric + 0.2::numeric AS with_numeric;
with_float with_numeric
0.30000000000000004 0.3

float in Postgres is 64 bit, which might be confusing if your programming language uses float for 32 bit and double for 64. If you want 32 bit there's float4, but I'd use 64 unless you have a specific reason.

In a lot of scenarios I prefer not to use decimals at all. When I'm storing money, I always store it in cents as an integer, with a name like cost_in_cents. So 500 is $5.00, and the app divides it by 100.

Strings

In Postgres, generally just use text. In other databases you'll see varchar (or varchar2 in Oracle) for variable length and char for strings that are always the same length.

Dates and times

It depends on what you care about. A birthday is a date. The time you go to bed is a time. If you need both, like the moment a user logged in, it's a timestamp.

So what's the difference between timestamp and timestamptz? timestamptz is converted to UTC (Coordinated Universal Time). I don't know why it's not CUT. I guess there was a disagreement over the English and French versions so they went with one that's wrong for both of them, which is just fabulous.

SQL
SET timezone = 'UTC';

SELECT timestamptz '2026-11-25 18:00 America/New_York' AS with_tz,
       timestamp '2026-11-25 18:00' AS without_tz;
with_tz without_tz
2026-11-25 23:00:00+00 2026-11-25 18:00:00

6 PM Eastern becomes 11 PM UTC (10 PM during daylight saving time). The plain timestamp is just 6 PM with no time zone attached, no matter where you look at it.

If something releases at 6 PM local time everywhere, use timestamp. If it's the same moment across the whole world, use timestamptz, which is what you'll want most of the time. Just know it does not save the original time zone, so if you need that, store it separately.

A common use is having the database record when a row was created with now(), plus another column for when it was last updated:

SQL
CREATE TABLE timestamps_example (
    id integer GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
    created_at timestamptz NOT NULL DEFAULT now(),
    updated_at timestamptz NOT NULL DEFAULT now()
);

The default only covers the insert, so updated_at needs changed by your app (or a trigger) on each update.

UUID

uuid is the type, a universally unique identifier, and then there's a function you call to generate one:

SQL
SELECT uuidv4(), uuidv7();
uuidv4 uuidv7
0a2b0143-624b-464b-bb3e-1039482e3f15 01a21421-f0a0-74ce-b3a1-20066532c81c

Version 4 is random. Version 7 has a timestamp in it, so you can also sort by time.

💡 Tip[!tip]
uuidv7() and uuidv4() need Postgres 18. On 13 through 17 use gen_random_uuid(), which is version 4. See the UUID functions.

When would you use this over auto increment? If you have multiple database nodes generating IDs, they could conflict. With UUIDs each node can just make its own. You'll also see the UUID generated in the app and then inserted, that usually works as well.

JSONB, bytes and arrays

jsonb stores JSON, like a snapshot of API data or anything where the structure varies. I've had situations where I had just an ID and a jsonb column with everything in it. It's not something I'd typically recommend because you lose a lot of what the database gives you, but it helps when you don't know what the structure is going to be.

bytea is a byte array, so you could put an image right in the database. Generally you'd store the file somewhere else (locally or in object storage like S3) and keep a pointer to it in the database.

Arrays like integer[] let you store multiple values in one cell. I know that kinda goes against the design principles, but if you only need a few values it can save you a whole other table.

There are also specialized types. vector isn't in standard Postgres, it's from the pgvector extension and it's used for embeddings if you're doing RAG.

Constraints

Constraints are when the database says no and makes you do something else.

constraint what it does makes an index
NOT NULL the column is required no
UNIQUE values can't repeat yes
PRIMARY KEY unique and not null, one per table yes
FOREIGN KEY has to match a row in the other table no (in Postgres)
CHECK the value has to pass a condition no

You'll see DEFAULT grouped with these, but it doesn't force anything, it's just the value to fall back to.

In some databases the primary key also determines how the data is stored on disk. In others it works the same as any other index.

A foreign key has ON DELETE to think about (and ON UPDATE, much less common). A check is a form of data validation, like rejecting a number that's too large. You can also do that in the application before you insert anything.

Another create table example

This one brings a lot of that together. Here's the design:

channels                    videos
--------                    ------
channel_id  PK  <----+      video_id    PK
name                 |      title
                     |      slug        UNIQUE
                     +----- channel_id  FK

one channel has many videos (1:M)

We assume channels already exists in the video, so here it is if you're following along in a fresh database:

SQL
CREATE TABLE channels (
    channel_id integer GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
    name text NOT NULL
);

Then videos. The slug is the part of the URL after the slash:

SQL
CREATE TABLE videos (
    video_id integer GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
    title text NOT NULL,
    slug text NOT NULL UNIQUE CHECK (length(slug) BETWEEN 1 AND 50),
    channel_id integer NOT NULL REFERENCES channels (channel_id) ON DELETE CASCADE
);

You just keep adding constraints one after another. The foreign key can be nullable or not, that's our choice.

ON DELETE is what happens to the video if you delete its channel. You can delete the videos too (CASCADE), error, or set the column to null or a default. With CASCADE, deleting a channel deletes all of its videos. The constraints docs have each option.

Here's some data to work with. I'm adding duration back, and it's nullable this time because the next queries need a missing one:

SQL
ALTER TABLE videos
ADD COLUMN duration integer;

INSERT INTO channels (name)
VALUES ('codebreakthrough'), ('codebreak'), ('empty channel');

INSERT INTO videos (title, slug, channel_id, duration)
VALUES
    ('SQL Basics', 'sql-basics', 1, 720),
    ('SQL Advanced', 'sql-advanced', 1, 750),
    ('Rust Basics', 'rust-basics', 1, 990),
    ('Git', 'git', 2, 900),
    ('Docker Basics', 'docker-basics', 2, NULL);

channels

channel_id name
1 codebreakthrough
2 codebreak
3 empty channel

videos

video_id title slug channel_id duration
1 SQL Basics sql-basics 1 720
2 SQL Advanced sql-advanced 1 750
3 Rust Basics rust-basics 1 990
4 Git git 2 900
5 Docker Basics docker-basics 2 null

Now try to break it. A slug that's taken, an empty slug, and a channel that doesn't exist:

SQL
INSERT INTO videos (title, slug, channel_id) VALUES ('Copy', 'sql-basics', 1);
INSERT INTO videos (title, slug, channel_id) VALUES ('No Slug', '', 1);
INSERT INTO videos (title, slug, channel_id) VALUES ('No Channel', 'no-channel', 99);
ERROR:  duplicate key value violates unique constraint "videos_slug_key"
ERROR:  new row for relation "videos" violates check constraint "videos_slug_check"
ERROR:  insert or update on table "videos" violates foreign key constraint "videos_channel_id_fkey"

Indexes

Some databases let you put indexes inside the create table. Here it's a separate statement:

SQL
CREATE INDEX ON videos (channel_id);

How do you know what to index? Primary keys and unique constraints get one by default, so with this one there are three on the table:

videos_pkey            PRIMARY KEY (video_id)
videos_slug_key        UNIQUE (slug)
videos_channel_id_idx  (channel_id)

There's a downside to too many indexes, so don't index everything, index your common access patterns. Ours is all videos by channel ID, like when you go to someone's channel and see their recent videos.

You can think of the index finding that channel ID very quickly, and then it goes and grabs the rest of the columns from the table. It doesn't have to scan the whole table to find them.

If you're always grabbing the same column you can include it in the index, so it may not have to go to the table at all. You'd do this instead of the one above:

SQL
CREATE INDEX ON videos (channel_id) INCLUDE (title);

I had INCLUDE in the wrong spot on the board at first, it goes right after the parentheses here. More on that in the covering index docs.

Intermediate queries

That's the data definition stuff, now let's write some better queries:

SQL
SELECT title, duration
FROM videos
WHERE title LIKE '%Basics'
    AND duration IS NOT NULL
ORDER BY duration DESC
LIMIT 2 OFFSET 0;
title duration
Rust Basics 990
SQL Basics 720

Docker Basics matches the title, but its duration is null so it's left out.

LIKE

LIKE finds similar strings. It's case sensitive in Postgres, use ILIKE if you want case insensitive (that one's Postgres specific).

  • % is any number of characters
  • _ is exactly one character

So '%Basics' matches SQL Basics and Rust Basics. '_at' matches cat but not chat, and '__at' matches chat but not cat. Since the % is only on the left, the string has to end with Basics. Put one on the right or in the middle if it can be different there too.

It's basically a super simplified regular expression. You can use real ones with a tilde:

SQL
SELECT title FROM videos
WHERE title ~ 'Basics$';
title
SQL Basics
Rust Basics
Docker Basics

Without the $ it matches anything containing Basics, and with it the title has to end in Basics. You can go learn the details if you want, kinda boring though.

AND and OR

AND means both have to be true, OR means one or the other (or both). Anything that doesn't pass isn't in the result set. There are a bunch of other comparisons you can look up too.

ORDER BY

DESC puts the biggest first, so the longest video is on top. ASC goes the other way, and it's the default.

LIMIT and OFFSET

LIMIT 2 gives you two rows, and OFFSET skips however many you say. If you want rows three and four, it's OFFSET 2:

SQL
SELECT title, duration
FROM videos
WHERE duration IS NOT NULL
ORDER BY duration DESC
LIMIT 2 OFFSET 2;
title duration
SQL Advanced 750
SQL Basics 720

This is a very common way to do pagination. It has its limitations with larger data sets, and the alternative is cursor-based pagination, where you use a WHERE instead of the offset. I have a video on both.

Functions, alias, CASE

Now let's customize what comes back:

SQL
SELECT
    upper(title) AS title,
    COALESCE(duration, 0) / 60 AS mins,
    CASE
        WHEN duration >= 900 THEN 'long'
        WHEN duration < 900 THEN 'short'
        ELSE 'unknown'
    END AS size
FROM videos;
title mins size
SQL BASICS 12 short
SQL ADVANCED 12 short
RUST BASICS 16 long
GIT 15 long
DOCKER BASICS 0 unknown

(the Git video on the board is 90 minutes, mine is 15 so the numbers work out in the next section).

upper is a function that uppercases the text. It only changes what's returned, not what's stored.

AS is an alias, which is what the column shows up as. Without it, the column is named after the function (just upper in Postgres, some databases show the whole upper(title)), and the result set gets sloppy pretty quick with complex queries.

COALESCE gives you the first value that isn't null. So it's the duration, or 0 if that's missing, and then we divide by 60 to get minutes. 600 would give you 10.

💡 Tip[!tip]
Dividing two integers in Postgres drops the decimal, which is why 750 seconds and 720 seconds are both 12 here. Use / 60.0 if you want 12.5.

CASE is basic logic. You might think you could do one WHEN and then an ELSE, but a null duration would go to the ELSE and get called short, so we check both and leave ELSE for unknown. You need the END so it knows where the case stops, since spacing and indentation don't matter.

Sums and aggregate functions

SQL
SELECT
    count(*),
    count(duration),
    avg(duration),
    count(DISTINCT channel_id)
FROM videos;
count count avg count
5 4 840 2

(the board has 600 for the average, I was just making up numbers. Postgres also prints it with a bunch of zeros, 840.0000000000000000, so I trimmed the averages).

This comes back as one row because it's aggregating data across the whole table:

  • count(*) is the number of rows
  • count(duration) doesn't count nulls, so Docker Basics is skipped
  • avg(duration) skips nulls too, so it's the average of four videos
  • count(DISTINCT channel_id) is how many different channels there are

So some queries give you a bunch of rows and some give you an aggregate, and you can't just mix the two:

SQL
SELECT title, count(*) FROM videos;
ERROR:  column "videos.title" must appear in the GROUP BY clause or be used in an aggregate function

There's also sum, min and max, and the rest of the aggregate functions work the same way.

GROUP BY

Without a GROUP BY the whole table is one group. Add it and you get those aggregates per group, so here it's per channel:

SQL
SELECT
    channel_id,
    count(*),
    count(duration),
    avg(duration)
FROM videos
GROUP BY channel_id
ORDER BY channel_id;
channel_id count count avg
1 3 3 820
2 2 1 900

Now we can select channel_id, because it's what we're grouping by. Channel 2 has two videos but one is missing a duration, so the second count is 1. I added the ORDER BY because grouping doesn't guarantee an order.

This is super powerful stuff when you get in to data analytics.

HAVING vs WHERE

They're both filters, the difference is when they run. WHERE filters the rows before the aggregation and HAVING filters the groups after.

SQL
SELECT
    channel_id,
    count(*),
    count(duration),
    avg(duration)
FROM videos
WHERE duration >= 600
GROUP BY channel_id
HAVING count(*) > 1;
channel_id count count avg
1 3 3 820

The WHERE cuts anything under 600 seconds (and the null one, since null isn't greater than or equal to anything). That leaves this, before the HAVING:

channel_id count count avg
1 3 3 820
2 1 1 900

Then HAVING removes any group without at least two videos. Channel 2 has two videos in the table, but only one of them made it past the WHERE, so it's gone.

What does this get us in English? How many videos of 10 minutes or more, and their average length, for channels that have at least two of those videos.

If you interview for a data analysis or software development role, you'll be given the English and your job is to turn it in to a query. It can be quite challenging. If you're not using this actively it's easy to forget, I had to refresh on some of these as well because I'm not writing these kinds of queries every day.

Joining data across tables

With foreign keys, a challenge is making the results understandable and not just a bunch of IDs. A join takes data from multiple tables:

SQL
SELECT c.name, v.title
FROM channels c
JOIN videos v
    ON c.channel_id = v.channel_id;
name title
codebreakthrough SQL Basics
codebreakthrough SQL Advanced
codebreakthrough Rust Basics
codebreak Git
codebreak Docker Basics

c and v are aliases for the tables. You can write channels AS c, but the AS is optional and it's common to leave it off with joins.

ON is how the rows connect. The primary key in channels has to equal the foreign key in videos, and this is why I like to keep the names the same.

LEFT JOIN

If something is missing on one side, it's left out. Our empty channel isn't in that result because it has no videos. To keep it, use a LEFT JOIN:

SQL
SELECT c.name, v.title
FROM channels c
LEFT JOIN videos v
    ON c.channel_id = v.channel_id;
name title
codebreakthrough SQL Basics
codebreakthrough SQL Advanced
codebreakthrough Rust Basics
codebreak Git
codebreak Docker Basics
empty channel null

Everything from the left table (the one in the FROM) is kept, and you get a null when there's no match.

For videos with no channel, I like to keep it as a left join and flip the tables. Our channel_id is NOT NULL so that can't happen right now, so I'm allowing it inside a transaction and rolling it back after:

SQL
BEGIN;

ALTER TABLE videos ALTER COLUMN channel_id DROP NOT NULL;

INSERT INTO videos (title, slug) VALUES ('Lost Video', 'lost-video');

SELECT c.name, v.title
FROM videos v
LEFT JOIN channels c
    ON c.channel_id = v.channel_id;

ROLLBACK;
name title
codebreakthrough SQL Basics
codebreakthrough SQL Advanced
codebreakthrough Rust Basics
codebreak Git
codebreak Docker Basics
null Lost Video

Whether you want that structure in your database is up to you.

Three table join

Those were one-to-many. For a many-to-many you join across more tables, and it can get sloppy pretty quick, so we'll keep this simple.

We have users, and users can subscribe to each other (so think of it as following, we're not splitting up users and channels here):

users

user_id username
1 Ana
2 Ben
3 Cam

subs

subscriber_id creator_id
1 2
1 3
2 1

I named them subscriber_id and creator_id instead of user_id so it's clear who's subscribing to who. Ana subscribes to Ben and Cam, and Ben subscribes back to Ana.

It's really only two tables but three logical ones, because both sides point back to users:

users (a)        subs                  users (b)
---------        ----                  ---------
user_id  <------ subscriber_id
                 creator_id  --------> user_id
username                               username
SQL
CREATE TABLE users (
    user_id integer GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
    username text NOT NULL UNIQUE
);

CREATE TABLE subs (
    subscriber_id integer NOT NULL REFERENCES users (user_id),
    creator_id integer NOT NULL REFERENCES users (user_id),
    PRIMARY KEY (subscriber_id, creator_id)
);

INSERT INTO users (username) VALUES ('Ana'), ('Ben'), ('Cam');

INSERT INTO subs (subscriber_id, creator_id)
VALUES (1, 2), (1, 3), (2, 1);

The goal is to replace those numbers with names. Start from the junction table and join to users twice, once for each side:

SQL
SELECT
    a.username AS subscriber,
    b.username AS creator
FROM subs s
JOIN users a
    ON a.user_id = s.subscriber_id
JOIN users b
    ON b.user_id = s.creator_id;
subscriber creator
Ana Ben
Ana Cam
Ben Ana

From here you can add a lot of the other stuff we already talked about, like filters and grouping. The Postgres joins tutorial has more examples.

Views

You might be thinking, I have to do this every single time? You can save your common queries and copy and paste them, or you can create a view. It's not actually a table, but you use it the same way as a table:

SQL
CREATE VIEW list AS
SELECT
    a.username AS subscriber,
    b.username AS creator
FROM subs s
JOIN users a
    ON a.user_id = s.subscriber_id
JOIN users b
    ON b.user_id = s.creator_id;

Notice the name goes before the AS here, which is a little confusing since with an alias the name goes after.

Now list has two columns and we don't have to deal with the joins:

SQL
SELECT * FROM list
WHERE subscriber = 'Ana';
subscriber creator
Ana Ben
Ana Cam

One thing to call out, filtering by name only works if the username is unique (that's why I put UNIQUE on it). If this was a first name, you'd get everyone named Ana. You can also add the IDs to the view and filter by those.

If you only need something like this temporarily, look in to a CTE, which lets you build a complex query in smaller steps. Here are the docs for those.

What's next?

I wanted to do this one on a chalkboard to focus on the concepts and the approach. For hands-on, my upcoming video will apply all of this to a real database.

We probably could have gone in to a lot more examples for any one of these, so if there's something specific you want me to go in to detail on, like data analytics, drop a comment on the video.

Powered by Course Catalyst