SQL for Data Analysis · Lesson 1 of 5
SELECT, WHERE and the order things happen
Write a query and know why it works.
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.
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.
کسی بھی ٹیبل پر LIMIT کے ساتھ SELECT چلائیں، پھر WHERE شامل کریں، پھر GROUP BY کے بعد HAVING۔ نوٹ کریں کہ ہر فلٹر کس جگہ آیا۔
Check what you learned
Create your free BvLogic ID to take the quiz and record your score.
Create your BvLogic ID