SQL from Zero › Module 1: How a database thinks

What happens when you run a query

Follow one question through the database engine: parse, plan, execute, return.

Lesson 3 of 33 · about 12 minutes

Video: Ordering at a restaurantThe narrated video for this lesson is coming soon. The lesson below covers the same ideas.

The lesson

Let's follow one question on its journey through the database: "Show me the titles of all Fantasy books." Think of it like ordering food at a restaurant.

1. You place your order. You write your SQL and press Run. That's like telling the waiter what you want.

2. The waiter checks the order makes sense. Is everything on the menu? Is the order written clearly? The database's parser does this. It checks your SQL's grammar and makes sure the table and columns you named really exist. If you misspell books as bokks, this is where you get an error, before any work starts.

3. The head chef plans the work. There's often more than one way to make a dish, and some are faster. The database's planner (also called the optimiser) looks at your question and picks the quickest route. Should it read every single book? Or is there a shortcut, like an index of genres? You never have to decide this. The planner does it for you.

4. The kitchen cooks. The executor follows the plan. It fetches the rows from storage, keeps the ones where the genre is Fantasy, and picks out just the title column.

5. Your food is served. The finished result comes back to you as a neat little table.

All of this usually takes a fraction of a second. And it's why SQL lets you say what you want rather than how: the planner and executor take care of the how.

Key ideas
  • A query goes through four steps: parse (check it), plan (choose the fastest route), execute (fetch the data), then return the result.
  • Spelling and grammar mistakes are caught at the parse step, before any data is touched.
  • The planner chooses how to find your data, so you only describe what you want.

Practise

Loading practice…

Quick check

1. Which step catches a misspelled column name?

2. Who decides the fastest way to find the data?

3. Do you need to tell SQL which order to search the rows in?