C.W.K.
Stream
Lesson 03 of 10 · published

INNER JOIN — The Default

~12 min · joins, inner-join, querying

Level 0Scout
0 XP0/80 lessons0/10 achievements
0/120 XP to next level120 XP to go0% complete

Rows that match in both tables

An INNER JOIN returns one row for every pair of rows from the two tables where the join predicate is true. Rows in either table without a match are dropped from the result.

The shape:

SELECT cols FROM A INNER JOIN B ON A.x = B.x;

JOIN alone means INNER JOIN — the keyword is optional but writing it explicitly makes intent obvious to the next reader.

Tip: Always alias your tables (FROM authors a INNER JOIN posts p) and qualify column names. Unaliased queries with two columns named id are unreadable and silently ambiguous.

Code

Posts with their author info·sql
SELECT p.id, p.title, a.name AS author, a.email
FROM   posts p
INNER  JOIN authors a ON a.id = p.author_id
ORDER  BY p.created_at DESC
LIMIT  20;
Three-table inner join·sql
-- conversations + messages + brain stats
SELECT c.id, c.title, count(m.id) AS msg_count, c.brain
FROM   conversations c
INNER  JOIN messages m ON m.conversation_id = c.id
GROUP  BY c.id
HAVING count(m.id) > 5;

External links

Exercise

Build authors + posts + comments. Insert sample data including: one author with no posts, one post with no comments. Write three INNER JOIN queries: (1) posts with authors, (2) posts with comments, (3) all three tables joined. For each, count how many rows the no-match cases lost — and confirm with manual COUNTs.

Progress

Progress is local-only — sign in to sync across devices.
Spotted a bug or have feedback on this page?Report an Issue

Comments 0

🔔 Reply notifications (sign in)
Sign inPlease sign in to comment.

No comments yet — be the first.