SQL ORDER BY sorts the rows returned by a SELECT statement. Place ORDER BY after FROM/WHERE; list one or more columns and an optional ASC (default) or DESC keyword. Multiple columns create secondary sort levels. NULLS FIRST/NULLS LAST is supported in some dialects. Add LIMIT for top-n queries. Avoid ordering unnecessary rows for speed.
ORDER BY sorts the final result set of a SELECT statement so rows appear in a predictable sequence. Without it, SQL returns rows in an arbitrary order based on the query plan.
Write ORDER BY after FROM, JOIN, WHERE, GROUP BY, and HAVING but before LIMIT or OFFSET. This position guarantees the sort acts on the already filtered and aggregated rows.
Use ASC for ascending order and DESC for descending order. ASC is the default, so specifying it is optional unless you want DESC.
Yes. List columns separated by commas. SQL applies sorts from left to right, creating secondary, tertiary, and further ordering layers.
ANSI SQL treats NULL as unknown and places it after non-NULL values in ASC order. Many databases let you add NULLS FIRST or NULLS LAST for explicit control.
Sorting requires memory and possibly disk IO. Indexes on the ORDER BY columns or limiting rows with WHERE can reduce resource use.
Combine ORDER BY with LIMIT (TOP in T-SQL, FETCH FIRST) to fetch the "first n" rows in a defined order, such as the latest 10 orders.
You may sort by calculations, functions, or a SELECT column alias. Use the alias name, the expression again, or its ordinal position.
GROUP BY clusters rows before ORDER BY. To sort on aggregated results, reference the aggregate expression or its alias in ORDER BY.
Order only the rows you actually return, ensure supporting indexes, avoid sorting large blobs, and always use ORDER BY when deterministic output is required.
Window functions contain their own ORDER BY clause inside OVER() to define row order for the window. This internal order is independent of the final ORDER BY, so you can have two different sorts in one query.
Core syntax is portable, but options like NULLS FIRST/LAST, COLLATE, or case-insensitive ordering vary. Check your database documentation.
Always specify ORDER BY for predictable results, define direction with ASC/DESC, manage NULL placement explicitly, leverage indexes, and limit rows when possible for performance.
Sorting can add CPU, memory, and temporary disk usage. Indexes on the sorted columns or limiting the row set keeps overhead low.
Yes. ORDER BY columns do not have to appear in the SELECT list unless you later reference them in client code.
Add a COLLATE clause (e.g., COLLATE NOCASE in SQLite) or use a LOWER() function around the column in ORDER BY.
Without ORDER BY, row order is non-deterministic. Changes in optimizer, storage, or partitioning can reshuffle rows. Always specify ORDER BY when order matters.