SQL exercises

Every graded exercise in the course, grouped by chapter — 98 queries on the record-store database. Open one and run it in your browser.

1. First Queries

  • Meet the artists — Every journey starts with a look around. Ask the artists table for everything it has — all columns, all rows.
  • Just the names — Asking for everything is fine for exploring, but usually you only need a piece. Get just the names of our artists — o…
  • Two will do — You can ask for several columns at once, separated by commas. From the employees table, get each person's first and l…
  • Call them by another name — Column names in results don't have to match the table. Using AS, you can rename anything. Show album title and releas…
  • How long is a song, really? — Durations in tracks are stored in seconds — not very human. Show each track title alongside its length in minutes, in…
  • No repeats — Our artists come from all over — but several share a country. List the different countries in artists, each one only…
  • The invoice header — Boss exercise. The accounting tool that reads our exports expects very specific column names. From invoices, produce…

2. Filtering

  • Songs for a long drive — The boss is building a playlist for a long road trip and only wants the long songs. From tracks, get title and durati…
  • The Spanish newsletter — The shop prints a newsletter in Spanish and only sends it to customers in Spain. From customers, get first_name and l…
  • The budget shelf — The bargain shelf gets the cheap songs — but only if they're long enough to be worth it. From tracks, get title for e…
  • Premium rock — or something very long — The boss is curating a wall display: Rock tracks (genre_id = 1) priced 1.29, plus any track longer than 360 seconds,…
  • Recent classics — The "recent classics" display needs albums released between 2005 and 2015, both years included. Get title from albums…
  • The international shelf — The international shelf is being restocked with artists from the UK, Sweden and Brazil. Get name from artists for eve…
  • Anniversary calls — Boss exercise. The owner is calling customers for the store's anniversary: everyone from Spain or Brazil who joined a…

3. Pattern Matching

  • Starts with N — A customer hums a tune and swears the title starts with the letter "N" — nothing else useful. Get title from tracks f…
  • Something about winter — Another customer remembers only that the word "winter" appears somewhere in the title — start, middle or end. Get tit…
  • The mysterious Midnight Train — A customer heard "Midnight Train" on the radio — capital M — but the catalog spells it all lowercase. Find every trac…
  • Nocturne No. what? — A customer asks for the track "Nocturne No." followed by a single digit — they can't remember which. Get title from t…
  • Too many "The"s — The owner jokes that half the bands are named "The Something" and wants to see the rest. Get name from artists for ev…
  • The apostrophe — The boss found a note from a customer: the song starts with "Don't" followed by something. From tracks, get title for…
  • The DJ's budget playlist — Boss exercise. The DJ needs cheap songs: every track whose title starts with "N" or ends with "e", but only the ones…

4. Sorting & Limiting

  • Shortest first — The listening kiosk plays tracks from shortest to longest. Get title and duration_sec from tracks, sorted by duration…
  • Newest hire first — The staff wall shows the team with the most recently hired employee at the top. Get first_name, last_name and hire_da…
  • The album rack — The shelf in the shop is arranged by artist, and within each artist by year. Get title, artist_id and release_year fr…
  • Longest in minutes — A customer wants the longest songs in units they can understand. Show each track's title and its length in minutes (d…
  • The mystery album — The history wall lists albums from oldest to newest. Get title and release_year from albums, sorted by release_year a…
  • Page two of the catalog — The shop's website lists tracks 5 per page, longest first. Get title and duration_sec from tracks for page two — that…
  • The Rock display case — Boss exercise. The Rock display case fits exactly 3 tracks — the longest ones. Get title from tracks for the 3 longes…

5. Aggregates

  • How big is the catalog? — Before we count money, let's count records. The owner wants a single number: how many tracks the store sells. Ask the…
  • The missing founding years — Two bands — Nocturne Quartet and The Paper Cranes — never reported the year they formed, so their formed_year is NULL…
  • The price of the whole catalog — If a fan bought every track once, what would the store take in? Compute the total value of all tracks and their avera…
  • Shortest and longest — The longest track in the store grinds past six minutes; the shortest barely clears three. Show the shortest and the l…
  • Tracks per genre — The catalog spans eight genres. For each genre, how many tracks does it hold? Group the tracks table by genre_id and…
  • Genres pulling their weight — Some genres barely fill a playlist; others carry the store. Which genres have more than 5 tracks? Group by genre_id,…
  • The catalog report — Boss exercise. The owner wants a per-album report: how many tracks each album has, its total duration in seconds, and…

6. String Functions

  • Full names — Our customers are split into first_name and last_name, but the newsletter needs one field. Glue them into a single fu…
  • How long are the titles? — The sleeve designer wants to know how long the track titles are. Show each title and its length in characters — LENGT…
  • Shout it from the speakers — Track 6 sits in the catalog typed all lowercase: midnight train. Show that track's title in all caps (UPPER) and all…
  • Trim the stray spaces — Track 17 arrived with padding: ' solstice ' — stray spaces on both sides. Show its title cleaned up with TRIM(), in a…
  • Initials — The receipt printer can only fit four characters per customer. Produce the initials of every customer — first letter…
  • No ampersands — The web player's URL builder chokes on the & in Static & Honey. For that track, show its title with every & replaced…
  • The email toolkit — Boss exercise. Marketing wants every customer email split into its local part (before the @) and its domain (after it…

7. Numbers & Dates

  • The average invoice — The accountant wants one tidy number: the average invoice total, rounded to 2 decimals. AVG(total) returns a long dec…
  • Close to five minutes — A radio show only plays songs near the five-minute mark. For every track, show its title and how far its duration is…
  • Days with us — The loyalty team wants how many days each customer has been with us, counted from joined_date until today. SQLite's j…
  • Invoices per year — Time to group by time. strftime('%Y', invoice_date) extracts the year from a date. Show how many invoices each year p…
  • How long is the history? — The store cut its first invoice on 2022-01-15 and its latest on 2024-03-05. How many days apart are the first and las…
  • The best year — Now the money. For each year, compute total revenue — SUM(total) rounded to 2 decimals — extracting the year with str…
  • The monthly report — Boss exercise. The accountant wants the full monthly revenue report: for every month that produced invoices — the mon…

8. Conditional Logic

  • Two price tags — Our tracks come in two flavors: 0.99 and 1.29. The budget ones are the ones that fly off the shelf. Show each track's…
  • Short, medium, or long? — Depending on how long a song is, the store tags it differently: under 200 seconds is 'short', from 200 to under 300 i…
  • Filling the gaps — Two of our artists — Nocturne Quartet and The Paper Cranes — were formed so long ago that nobody wrote the year down:…
  • Only the special prices — The store's standard price is 0.99; anything else is a special price. Export the tracks catalog so that unit_price be…
  • A quick flag — A collector wants a quick pass: which songs clock in under three and a half minutes? Use the one-line shorthand IIF(c…
  • The owner's order — The store's homepage lists genres in a curated order: 'Bossa Nova' first, then 'Classical', and everything else alpha…
  • The support check-in — Boss exercise. Customer care wants a check-in on every support rep. For each rep (support_rep_id in customers), count…

9. Joins

  • Track to album — tracks only stores an album_id — a number that means nothing on its own. Join tracks with albums so that every row sh…
  • The full picture — Nice — but where's the band? Each track sits on an album, and each album belongs to an artist. Chain one more join so…
  • Employees with no one to help — Customers point at their support rep, but not every employee is a rep. Find the employees who support no customers at…
  • Who manages whom — employees.reports_to holds the id of each person's manager — one employee pointing at another. Join the table with it…
  • Revenue per artist — Money time. Each row of invoice_lines is one song sold, with a quantity and a unit_price. Follow the chain invoice_li…
  • Revenue by month — The finance team reviews the books by month. Join invoices with invoice_lines and group by the year-month of the invo…
  • The sale ledger — Boss exercise. The owner wants the raw sale ledger — every line sold, newest first. Start from invoice_lines and join…

10. Subqueries

  • Longer than average — The playlist team wants every track that runs longer than the average track. Write one query that finds the average d…
  • Made in Spain — A radio show wants to profile our Spanish artists. List the titles of the albums whose artist comes from Spain, using…
  • Not from the USA — Same idea, flipped. List the album titles whose artist is not from the USA. NOT IN is IN's mirror image — same shape,…
  • Has at least one album — EXISTS asks a yes/no question for each row. List the names of the artists that have at least one album. (Every artist…
  • Albums with more than two tracks — A correlated subquery that counts. For each album, count its tracks and keep the ones with more than 2 tracks — that…
  • The average customer — Marketing wants one number: how much the average customer spends across all of their invoices. First build each custo…
  • The genre that pays the rent — Boss exercise. Sales wants the single most profitable genre — the one whose sold tracks earned the most money. Each r…

11. Set Operations

  • Every featured title, once — Every year the store highlights ten titles on a wall display; the lists live in featured_2023 and featured_2024. The…
  • Count the duplicates — The inventory team needs the raw numbers: every title that was displayed, including the overlaps twice. UNION ALL ski…
  • Featured both years — Four titles were lucky enough to stay on the wall for both years. Find them with INTERSECT: the titles that appear in…
  • Only in 2023 — Some titles were taken down. Show the titles featured in 2023 but not in 2024 with EXCEPT, sorted alphabetically — pu…
  • Only in 2024 — Now the other direction: the titles that joined the wall in 2024 and were not there in 2023. Flip the two tables and…
  • Label the years — The exhibition catalog needs to know which year each title was featured. Select each list's title together with a lit…
  • One year only — Boss exercise. The curator wants the titles that were featured in exactly one of the two years — the ones that tell a…

12. Modifying Data

  • A new genre — The store is expanding into reggaeton. Add it to genres with id 9 and name 'Reggaeton' — one new row.
  • Two new artists — Two fresh signings just landed. Add them in a single statement: Los Fuegos (id 13, from Mexico, formed 2016) and Soni…
  • Copy the wall — The 2024 wall was set up before the 2023 one came down, and the manager wants every 2023 title on the 2024 display to…
  • Price of fame — "Golden Hour" keeps selling out, so it deserves a raise. Update track id 1 so its unit_price is 1.49. Two clauses to…
  • A 10% raise — The label wants every Electronic track (genre_id 5) 10% more expensive. Compute the new price inside SET: multiply un…
  • Trim the wall — The 2023 wall should only keep titles that are still relevant: those that also made it to 2024. Delete every featured…
  • New arrival — Boss exercise. Marina Sol's new album just arrived at the warehouse and needs cataloguing. It is album id 18, titled…

13. Window Functions

  • The marathon queue — The store app is getting a "longest songs" screen. Number every track from 1 (longest) to 49 (shortest), ordering the…
  • One price, many ranks — Our catalog lives on just two prices — 1.29 and 0.99 — so ties are everywhere. For every track show title, unit_price…
  • Genre-local rankings — A global ranking is fine, but shoppers compare inside a genre. Rank every track within its own genre_id, by duration_…
  • The till that never stops — The owner wants to watch sales pile up. For each invoice_date, show total and a running_total column: the sum of ever…
  • How many days in between? — Sales arrive irregularly. For each invoice in date order, compute days_since_last: the gap in days between it and the…
  • Three-month smoothing — Monthly revenue swings hard from month to month. Smooth the curve: for every month show revenue and moving_avg — the…
  • The podium — Boss exercise. It's end of year — build the top 3 customers by total spend, each with a rank column (ties share a ran…

14. CTEs & Capstone

  • Months that mattered — With a WITH clause you can name a subquery and treat it like a table. Define monthly_revenue (one row per month: mont…
  • The album sales report — Two CTEs, chained. First track_sales: units and revenue per track from invoice_lines. Then album_sales, which reads t…
  • The regulars, ranked — Define a totals CTE that computes how much each customer has spent (from invoices), then join it back to customers so…
  • Climbing the org chart — Jane Foster runs the store; everyone else reports to someone. Use WITH RECURSIVE to walk the org chart from reports_t…
  • The months nobody shopped — The store opened in January 2022, and the owner wants the full timeline from 2022-01 to 2024-03 — every month, even t…
  • 2023: the year in review — Capstone. Produce the annual report for 2023: one row per month (month as YYYY-MM) with revenue, a running_total (the…
  • Genre power ranking — Capstone. End-of-year presentation: rank the 8 genres by revenue. For each genre show name, track_count (tracks in th…