Concepts / Writing Efficient SQL Queries

Writing Efficient SQL Queries

Correct relationships and efficient execution depend on how the tables are constructed.

  • Programming
Interactive lab

Try it: JOIN Step by Step

How a JOIN combines rows from two tables by testing the ON condition for every pair (a nested loop), how LEFT and RIGHT JOIN keep unmatched rows by padding with NULL, and how a junction table links a many-to-many relationship with two joins.

How it works

  1. Take the first row of the outer (left) table.
  2. Compare its key with the key of every row of the inner table using the ON condition; every TRUE comparison produces one combined row. NULL = anything is NULL, never a match.
  3. INNER JOIN drops an outer row with no match; LEFT JOIN keeps it with the inner columns set to NULL. RIGHT JOIN is the mirrored LEFT JOIN; CROSS JOIN pairs every row with every row.
  4. Repeat for every outer row. A second JOIN treats the rows produced so far as its outer table — this is how student → member → course crosses a junction table.

Default run (18 steps): SELECT artist.name, album.title FROM artist JOIN album ON artist.id = album.artist_id. A nested loop: for each outer row, test the ON condition against every inner row. … Result: 3 joined rows (15 ON comparisons).

Simplified: A toy relational engine in the browser, not SQLite itself: a small structured query model built from the controls (no SQL text is parsed or executed), typed INTEGER/TEXT/NULL values, and tables of at most a few rows. Results were checked against Python's sqlite3 (SQLite 3.49). The join is shown as a plain nested loop; real SQLite may reorder tables or build a temporary index, but the rows produced are the same. Result order here is outer row, then inner row (SQL promises no order without ORDER BY).

Educational simulation

Loading the simulation…

Reconstructing Related Data

A relational database may store connected information in separate tables. An Artist table can store artist records, while an Album table stores album records. A JOIN reconstructs related information by following the connection between a primary key in one table and a foreign key in another.

Key point

The JOIN clause combines rows. The ON clause tells the database which rows are related and therefore may be combined.

Artist rowid = 7Combined result rowmatching artist and albumAlbum rowartist_id = 7primary-key matchON condition
How does a JOIN use the ON condition to match rows from two separate tables and produce one combined result row?

Following a One-to-Many Link

A one-to-many relationship has one parent record connected to multiple child records. In the source example, Artist is the parent table and Album is the child table. Each album row has a foreign key pointing to one artist, but one artist can be referenced by several album rows.

Worked example

One Artist, Several Albums

Suppose an Artist row has primary-key value 7. Three Album rows contain artist_id value 7.

  1. 1
    Find the parent key

    The Artist row contributes the primary-key value 7.

  2. 2
    Inspect child keys

    Each of the three Album rows contains artist_id value 7, so each points to the same Artist row.

  3. 3
    Trace the JOIN result

    The JOIN produces one result row for each matching Album row. The same artist information can therefore appear in three result rows, once alongside each related album.

Result

One parent Artist row produces three JOIN result rows because it matches three child Album rows.

Artistid = 7Album 1artist_id = 7Result row 1Artist + Album 1Album 2artist_id = 7Result row 2Artist + Album 2Album 3artist_id = 7Result row 3Artist + Album 3referenced byreferenced byreferenced bymatchmatchmatch
Why does one row in a parent table correspond to multiple rows in the JOIN result when it matches several related child rows?

Primary Keys as Connection Points

Definition

A primary key is a unique identifier assigned to each row in a table. In the Album table, each album has its own id. The Album table also contains artist_id, a foreign key that points to a specific row in the Artist table.

The foreign key is the bridge between the tables. Its value comes from the primary-key values of the related table. When the database compares Album.artist_id with Artist.id, a matching value identifies the Artist row connected to that Album row.

Artist.idprimary keyArtist and Albumrelated rowsAlbum.artist_idforeign keypoints to matching valueidentifiesconnects
What contains what, and how does a foreign-key value in one table point to the matching primary-key row in another table?

Reading the JOIN Structure

A basic JOIN query names the columns to return, identifies the first table, names the table to join, and then states the matching condition. The ON condition should compare the foreign key in one table with the primary key in the related table.

sql
Query partRole
SELECT columnsChooses which columns appear in the result
FROM table1Names the starting table
JOIN table2Adds rows from another table
ON table1.foreign_key = table2.primary_keyDefines which rows are related

The parts of the basic JOIN pattern

Following Multiple Relationships

The same reasoning extends across more than two tables. With Artist, Album, and Track tables, one Artist can have many Albums, and one Album can have many Tracks. A query that joins all three tables follows both relationships.

Worked example

Reconstructing Track Context

Trace the meaning of one result row when Artist, Album, and Track are joined.

  1. 1
    Start with a Track row

    The result represents one track record at the most detailed level of this relationship chain.

  2. 2
    Connect the Track to an Album

    The Album relationship supplies the album information associated with that track.

  3. 3
    Connect the Album to an Artist

    The Artist relationship supplies the artist information associated with the album.

Result

Each result row represents one track while also carrying the related album and artist context.

This is data reconstruction: information that was stored in normalized tables is brought together in the query result by following each key-based connection. Because an album can have multiple tracks, the artist and album information may recur across several result rows, once for each related track.

Supporting Efficient Matching

Correct relationships and efficient execution depend on how the tables are constructed. Primary keys should have uniqueness constraints so that each primary-key value identifies one row. Foreign keys should have indexes so the database can quickly locate rows that match the ON condition instead of scanning the entire table.

Database featureHow it supports a JOIN
Uniqueness constraint on a primary keyEnsures the primary key is truly unique, which is essential for correct matching
Index on a foreign keyHelps the database quickly locate rows that match the ON condition

Two structural supports for correct and efficient joins

Common JOIN Mistakes

  • Common mistake

    Treating a one-to-many relationship as if it must produce one result row

    What it looks like

    Expecting one Artist row to appear only once even when several Album rows reference it

    Why it fails

    A JOIN produces one result row for each matching child record.

    Do this instead

    Count the matching child rows and expect the parent information to recur once per connected child.

  • Common mistake

    Matching unrelated columns in the ON condition

    What it looks like

    Using a column comparison that does not connect the foreign key to the related primary key

    Why it fails

    The ON condition determines which rows are combined, so an incorrect comparison does not follow the stored relationship.

    Do this instead

    Compare the foreign key from one table with the primary key of the related table.

  • Common mistake

    Assuming the foreign key contains the complete parent record

    What it looks like

    Treating Album.artist_id as if it were all of the Artist data

    Why it fails

    The foreign key stores the primary-key value that points to the related Artist row; it is the bridge, not the complete parent record.

    Do this instead

    Use a JOIN to bring the related parent-table columns into the result.

  • Common mistake

    Ignoring table structure when considering performance

    What it looks like

    Joining large tables without indexes on foreign keys

    Why it fails

    The database may need to scan the entire table to find rows matching the ON condition.

    Do this instead

    Use indexes on foreign keys and uniqueness constraints on primary keys when constructing the relationships.

Practice the Relationship Trace

MEDIUM

Write the structure of a JOIN between Artist and Album. Use the Album foreign key artist_id and the Artist primary key id in the ON condition. Then explain how many result rows one Artist row can produce when three Album rows reference it.

Hints
  • Begin with SELECT, FROM, JOIN, and ON.
  • The matching condition compares Album.artist_id with Artist.id.
  • A one-to-many relationship produces one result row for each matching child record.

What do you think happens?

An Artist row is referenced by four Album rows. How many JOIN result rows represent that artist?

  • One

  • Four

  • One for every Artist row in the table

Reveal answer
Answer:

Four

A one-to-many JOIN produces one result row for each matching child record. Four Album rows connected to the Artist row therefore produce four result rows for that artist.

Key Takeaways

  1. 1
    JOIN combines rows from separate tables, while ON defines which rows match.
  2. 2
    A foreign key stores the primary-key value that connects a child row to a parent row.
  3. 3
    A one-to-many relationship produces multiple result rows when one parent matches multiple child records.
  4. 4
    Joining Artist, Album, and Track follows multiple relationships to reconstruct the full context of each track.
  5. 5
    Uniqueness constraints on primary keys support correct matching, and indexes on foreign keys support efficient matching.

At a glance

  • JOIN and ON clauses reconstruct related data from separate tables.
  • Foreign keys point to primary keys and provide the bridge between tables.
  • One parent row can appear in multiple JOIN result rows when it has multiple related child rows.
  • Multiple JOIN clauses can follow a chain such as Artist to Album to Track.
  • Indexes on foreign keys and uniqueness constraints on primary keys support efficient and correct joins.

More concepts starting with W