SELECT, WHERE, and ORDER BY

Reading data is the foundation of SQL. Every query you write will eventually come back to these three clauses.

SELECT — What to retrieve

SQL
-- Everything from a table
SELECT * FROM students;

-- Specific columns
SELECT name, email, grade FROM students;

-- Aliases (rename columns in the result)
SELECT name AS student_name, grade AS class FROM students;

-- Distinct values (removes duplicates)
SELECT DISTINCT grade FROM students;

-- Expressions
SELECT name, age, age + 1 AS next_year_age FROM students;

WHERE — Filtering rows

SQL
-- Comparison operators: =  !=  <  >  <=  >=
SELECT * FROM students WHERE age > 20;
SELECT * FROM students WHERE grade != 'B';

-- AND / OR
SELECT * FROM students WHERE grade = 'A' AND age >= 21;
SELECT * FROM students WHERE grade = 'A' OR grade = 'B';

-- BETWEEN (inclusive on both ends)
SELECT * FROM students WHERE age BETWEEN 18 AND 22;

-- IN (matches any value in the list)
SELECT * FROM students WHERE grade IN ('A', 'B');

-- LIKE (pattern matching)
SELECT * FROM students WHERE name LIKE '%Ram%';     -- contains Ram
SELECT * FROM students WHERE name LIKE 'S%';        -- starts with S
SELECT * FROM students WHERE name LIKE '____';       -- exactly 4 chars

-- IS NULL
SELECT * FROM students WHERE email IS NULL;
SELECT * FROM students WHERE email IS NOT NULL;

ORDER BY — Sorting results

SQL
-- Ascending (default)
SELECT * FROM students ORDER BY name;

-- Descending
SELECT * FROM students ORDER BY age DESC;

-- Multiple columns (tie-breaker)
SELECT * FROM students ORDER BY grade ASC, age DESC;

LIMIT and OFFSET — Paging results

SQL
-- First 5 rows
SELECT * FROM students ORDER BY name LIMIT 5;

-- Skip 10, then take 5 (page 3 if page size is 5)
SELECT * FROM students ORDER BY name LIMIT 5 OFFSET 10;

Practical example

SQL
-- Find all students named Ram, sorted by age (youngest first)
SELECT name, age, grade
FROM students
WHERE name LIKE '%Ram%'
ORDER BY age ASC
LIMIT 10;

Tips

  • SELECT * is fine for exploration, but in production code list the columns you actually need — it's faster, and your code won't break if someone adds a column.
  • Use LIMIT whenever you don't need every row.
  • WHERE filters rows before they're returned; ORDER BY sorts the results after filtering.

Next: joins.