Reading Data: SELECT and Filtering
Reading Data: SELECT and Filtering
The Basic Query
SELECT is the workhorse of SQL. Its simplest form picks columns from a table:
SELECT username, email FROM users;
The asterisk returns every column (SELECT * FROM users), which is convenient while exploring but wasteful in production queries when you need only two columns.
Filtering with WHERE
WHERE keeps only rows that match a condition. Comparison operators work as expected: =, != or <>, <, <=, >, >=. Text comparisons are case-insensitive by default in MySQL's common collations.
SELECT username, email
FROM users
WHERE created_at > '2025-01-01';
Combine conditions with AND and OR. Use parentheses to group logic, because AND binds more tightly than OR. IN tests a list of values, and BETWEEN tests a range.
SELECT * FROM products
WHERE price < 20 OR price > 200;
SELECT * FROM products
WHERE price BETWEEN 20 AND 200;
SELECT * FROM products
WHERE category IN ('books', 'games');
Pattern Matching with LIKE
LIKE searches for patterns with two wildcards: % matches any sequence of characters, and _ matches exactly one. A search for all usernames starting with j looks like this:
SELECT username FROM users
WHERE username LIKE 'j%';
Note that % matches even an empty string, so 'j%' also finds the bare username j if it existed.
Ordering and Limiting
ORDER BY sorts results in ascending (default) or descending order when you add DESC after the column. LIMIT caps the number of returned rows and is how you page through a large set.
SELECT username FROM users
ORDER BY created_at DESC
LIMIT 10;
Key Points
- SELECT lists columns; WHERE filters rows by condition.
- AND, OR, IN, BETWEEN, and LIKE build richer filters.
- LIKE uses % for any text and _ for a single character.
- ORDER BY sorts, DESC reverses, and LIMIT caps the result.
- Run matching SELECTs before UPDATE and DELETE statements to check your WHERE.