What ORDER BY does
Sort query results by one or more columns. SQL syntax can vary by database, but the pattern below is a useful starting point for reports and analysis.
Syntax or pattern
SELECT * FROM table_name ORDER BY column_name DESC;5 practical examples
Sort newest orders first
Put recent rows at the top.
SELECT order_id, order_date, total_amount
FROM orders
ORDER BY order_date DESC;DESC sorts largest or newest values first.
Sort customers alphabetically
Sort by last name and first name.
SELECT customer_id, last_name, first_name
FROM customers
ORDER BY last_name, first_name;Multiple sort columns create stable ordering.
Sort high-value products
Show highest-priced products first.
SELECT product_name, price
FROM products
ORDER BY price DESC;Useful for price audits and product reviews.
Sort grouped results
Sort categories by total sales.
SELECT category, SUM(amount) AS sales
FROM sales
GROUP BY category
ORDER BY sales DESC;You can sort by an aggregate alias in many SQL engines.
Sort nulls intentionally
Put missing dates last where supported.
SELECT ticket_id, due_date
FROM tickets
ORDER BY due_date NULLS LAST;Some databases support NULLS FIRST or NULLS LAST.
Common mistakes to avoid
- Forgetting that SQL dialects vary across PostgreSQL, SQL Server, MySQL, BigQuery and SQLite.
- Using SELECT * in production reports when only a few columns are needed.
- Not checking join keys, duplicate rows or NULL values before trusting results.
FAQ
Will this SQL work in every database?
The idea is portable, but function names and date syntax may vary. Check your database dialect if a function is not recognized.
Should I use this in a report query?
Yes, if the pattern matches the business question and you have checked filters, joins and row counts.
Why does my result have too many rows?
The most common reasons are duplicate join keys, missing filters or grouping at the wrong level of detail.
Here are some ideas for you
Optional resources that may help if you are learning SQL, building reports, writing queries or improving your data workflow.
- SQL books for beginnersSee ideas
Practice query patterns with structured examples and exercises.
- Database design booksSee ideas
Understand tables, keys, relationships and why joins behave the way they do.
- Mechanical keyboardsSee ideas
Useful if you write queries, code and documentation for long work sessions.
- External monitorsSee ideas
View query editor, result grid and documentation side by side.
- Developer notebooksSee ideas
Sketch table relationships, query logic and report ideas before coding.
- Desk lampsSee ideas
Keep your workspace comfortable while studying or debugging queries.
Some links in this section may be affiliate links. Choose only what is useful for your own work.