SELECT retrieves rows and columns from one or more MySQL tables, optionally filtering, sorting, limiting, and joining data.
SELECT returns tabular results from a database. It can pull all columns, specific columns, or derived values, and supports filters, joins, sorting, grouping, and limits.
Use an asterisk when you need all columns. Example: SELECT * FROM Customers;
Keep queries fast by switching to explicit columns once you know what you need.
List the columns in order: SELECT id, name, email FROM Customers;
Naming columns reduces network traffic and makes the intent clear.
Attach a WHERE clause: SELECT * FROM Orders WHERE total_amount > 500;
Combine multiple conditions with AND
, OR
, and parentheses for clarity.
Append ORDER BY column [ASC|DESC]
: SELECT name, price FROM Products ORDER BY price DESC;
Always specify direction for deterministic output.
Use explicit JOIN syntax: SELECT o.id, c.name, o.total_amount FROM Orders o JOIN Customers c ON o.customer_id = c.id;
Prefix columns to avoid ambiguity.
Cap results with LIMIT: SELECT * FROM OrderItems LIMIT 10;
Combine with OFFSET
for pagination: LIMIT 10 OFFSET 20
.
Project only needed columns, use indexes in filter predicates, prefer explicit joins, and add comments for complex logic. Measure query plans with EXPLAIN
.
No. Aliases defined in the SELECT list are unavailable in the WHERE clause but can be referenced in ORDER BY or HAVING. Wrap the query in a subquery if you need the alias earlier.
Yes. DISTINCT applies to the entire selected row. SELECT DISTINCT customer_id, product_id FROM OrderItems;
returns each unique customer-product pair.
Use indexed keyset pagination when possible: filter with a > last_seen_id condition instead of OFFSET, which grows slower with large offsets.