ORDER BY sorts query results by one or more fields. Always pair ORDER BY with a LIMIT clause — without it, the engine must sort the entire result set, which degrades performance significantly.
Syntax
SELECT [ DISTINCT ]
{ projectItem [, projectItem ]* }
FROM tableExpression
ORDER BY { orderByItem [ASC|DESC] [, orderByItem [ASC|DESC]]* }
LIMIT N
OFFSET MParameters:
| Parameter | Description |
|---|---|
orderByItem | A field to sort by. Specify multiple fields separated by commas. |
ASC | DESC | Sort direction. ASC (ascending) is the default when no direction is specified. |
LIMIT N | Maximum number of records to return. Required when using ORDER BY. |
OFFSET M | Number of records to skip before returning results. Use with LIMIT for pagination. |
Examples
The following examples use a phone table with fields nid, brand, price, and size.
Sort by a single field (default ascending)
SELECT nid, brand, price, size FROM phone ORDER BY price LIMIT 1000Returns up to 1,000 records sorted by price from lowest to highest. Omitting ASC or DESC defaults to ascending order.
Sort by a single field in ascending order (explicit)
SELECT nid, brand, price, size FROM phone ORDER BY price ASC LIMIT 1000Equivalent to the previous example. Use ASC explicitly when you want to make the sort direction clear in your query.
Sort by multiple fields
SELECT nid, brand, price, size FROM phone ORDER BY size DESC, price DESC LIMIT 1000Sorts first by size in descending order. When two records have the same size, they are sorted by price in descending order. Each subsequent field acts as a tie-breaker for the previous one.
Paginate through sorted results
SELECT nid, brand, price, size FROM phone ORDER BY price DESC LIMIT 10 OFFSET 10Returns records 11–20 from a price-descending sort. OFFSET 10 skips the first 10 records; LIMIT 10 returns the next 10.
Return records without sorting
SELECT nid, brand, price, size FROM phone LIMIT 10Returns 10 records in an unspecified order. Use this when sort order does not matter and you want the fastest possible response.