ORDER BY

更新时间:
复制 MD 格式

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 M

Parameters:

ParameterDescription
orderByItemA field to sort by. Specify multiple fields separated by commas.
ASC | DESCSort direction. ASC (ascending) is the default when no direction is specified.
LIMIT NMaximum number of records to return. Required when using ORDER BY.
OFFSET MNumber 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 1000

Returns 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 1000

Equivalent 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 1000

Sorts 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 10

Returns 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 10

Returns 10 records in an unspecified order. Use this when sort order does not matter and you want the fastest possible response.