SQL for Data Analysis
Lesson 1 of 5 5 lessons · free
SQL for Data Analysis 5 lessons
  1. 1 SELECT, WHERE and the order things happen
  2. 2 Joining tables
  3. 3 Aggregation and the questions managers ask
  4. 4 Subqueries and CTEs
  5. 5 Queries somebody else can rely on
  1. ✎ Course lab6 tasks · marked out of 100
Course overview
Data: video · change

This lesson: 356KB

SQL for Data Analysis · Lesson 1 of 5

SELECT, WHERE and the order things happen

Write a query and know why it works.

That was a one-minute preview. The full course video is for signed-in learners. Sign in to watch it here, or create a free BvLogic ID.

SQL reads like English and that is slightly misleading, because it does not run in the order you write it.

You write SELECT, FROM, WHERE, GROUP BY, HAVING, ORDER BY, LIMIT. The database runs FROM first, then WHERE, then GROUP BY, then HAVING, then SELECT, and only then ORDER BY and LIMIT.

That single fact explains most beginner confusion. It is why you cannot use a column alias you created in SELECT inside your WHERE clause: when WHERE runs, that alias does not exist yet. It is also why filtering individual rows is WHERE and filtering groups is HAVING. They run at different moments.

Start every query the same way. SELECT star with LIMIT 10 to see what is actually in the table, because the column names in the documentation and the column names in the database are not always the same thing. Then narrow.

Three habits from the beginning.

Name your columns rather than using star in anything you keep. Star breaks quietly when somebody adds a column.

Filter early and specifically. A date range in WHERE on an indexed column is the difference between a query that returns and one that does not.

Beware NULL. It is not zero and it is not an empty string. Any comparison with NULL gives neither true nor false, so a row with NULL fails both a condition and its opposite. Use IS NULL, and remember this every time a row count comes out lower than you expected.

Exercise: try it yourself

On any table, run SELECT with a LIMIT, then add a WHERE, then a HAVING after a GROUP BY. Note which clause each filter belonged in.

Check what you learned

Create your free BvLogic ID to take the quiz and record your score.

Create your BvLogic ID

Up next: 2. Joining tables

Continue to lesson 2 Up next 2. Joining tables