Skip to main content

ORDER BY

Use ORDER BY to sort results by one or more columns, each ascending or descending. Set the sort direction for each column, and rely on the query's ordering behavior when you combine ORDER BY with TIMESERIES. You can sort by columns from SHOW or by generated columns that clauses like WITH and COMPARE TO add.

Syntax

ORDER BY column [ASC | DESC][, ...]

ORDER BY sorts each column ascending by default. Add ASC to sort ascending or DESC to sort descending. When you list more than one column, ShopifyQL sorts by each in turn, using later columns to order rows that are equal on the earlier ones.

Examples

ShopifyQL

FROM customers
SHOW new_customer_records
GROUP BY month
SINCE startOfYear(0y) UNTIL today
ORDER BY month ASC

The order a query returns depends on whether it uses TIMESERIES, ORDER BY, or both:

  • When a query uses TIMESERIES without ORDER BY, results are ordered by the time dimension.
  • When a query uses TIMESERIES with ORDER BY, the time dimension stays the primary order, then ORDER BY columns break ties.
  • When a query uses ORDER BY without TIMESERIES, rows are sorted by the specified dimensions or metrics.
  • When a query has neither TIMESERIES nor ORDER BY, results are ordered by the first SHOW column.
Examples

ShopifyQL

FROM sales
SHOW net_sales
GROUP BY sales_channel
TIMESERIES day
DURING last_week
ORDER BY net_sales DESC

Anchor to Sorting generated columnsSorting generated columns

ORDER BY can sort the columns that other clauses generate, such as comparison columns from COMPARE TO and totals or cumulative columns from WITH. Reference a generated column by the name that the generating clause defines.

Examples

ShopifyQL

FROM sales
SHOW gross_sales
GROUP BY product_type
DURING this_year
COMPARE TO previous_year
ORDER BY comparison_gross_sales__previous_year DESC
LIMIT 10

Was this page helpful?