SQL Topic 1 - SELECT, WHERE, DISTINCT, ORDER BY, LIMIT


Concept

SQL retrieval follows a strict logical order:

SELECT (what columns) → FROM (which table) → WHERE (filter rows) → ORDER BY (sort) → LIMIT/TOP (restrict output)

Mental Model: You're ordering food - SELECT is what dish, FROM is which restaurant, WHERE is your dietary restrictions, ORDER BY is the course sequence, and LIMIT is taking only 2 bites.

Execution order (not writing order):

FROM → WHERE → SELECT → ORDER BY → LIMIT

This means you cannot use a SELECT alias inside WHERE. WHERE runs before SELECT, so the alias does not exist yet.


Syntax Template

sqlSELECT [DISTINCT] col1, col2, ... FROM table_name WHERE condition ORDER BY col [ASC | DESC] LIMIT n; -- MySQL / PostgreSQL

Dialect variants for row limiting:


Examples

`sql-- Example 1: Basic filter and sort SELECT first_name, score FROM customers WHERE country = 'Germany' AND score > 500 ORDER BY score DESC;

-- Example 2: BETWEEN + IN + DISTINCT SELECT DISTINCT country FROM customers WHERE score BETWEEN 300 AND 800 OR country IN ('USA', 'UK');

-- Example 3: LIKE + NULL check + TOP (SQL Server) SELECT TOP 3 customer_id, first_name, score FROM customers WHERE first_name LIKE 'M%' AND score IS NOT NULL ORDER BY score DESC;`


All Variations