In SQL, BY is never used alone. It forms part of three fundamental clauses that control result-set organization:1. GROUP BY tells the database engine to aggregate rows that share identical values in the listed columns or expressions. It works together with aggregate functions such as COUNT, SUM, AVG, MIN, and MAX.2. ORDER BY sorts the returned rows according to the listed columns or expressions, optionally using ASC (ascending) or DESC (descending) modifiers. ORDER BY always executes after SELECT, FROM, WHERE, and GROUP BY have produced the intermediate result set.3. PARTITION BY appears in window functions (OVER clause) and divides the window into subsets, allowing calculations such as running totals or rankings to restart for every partition.Because BY modifies how data is arranged, it can materially affect query performance. Appropriate indexes and selective column order matter, especially for ORDER BY and GROUP BY on large tables. In standard SQL you may reference column aliases in ORDER BY but not in GROUP BY. Most engines evaluate ORDER BY after DISTINCT and LIMIT/OFFSET, while GROUP BY occurs before these stages.Caveats:- All nonaggregated columns in the SELECT list must appear in GROUP BY (or be functionally dependent) to avoid errors.- ORDER BY on a view or subquery with its own ORDER BY is ignored unless combined with TOP, LIMIT, or FETCH.- PARTITION BY requires an accompanying ORDER BY inside the window for functions that depend on row order (e.g., LAG, LEAD, ROW_NUMBER).
column_list
(list) - One or more column names or expressions that dictate grouping, sorting, or partitioning.sort_direction
(keyword) - Optional ASC or DESC modifier for ORDER BY.rollup_cube
(keyword) - Optional ROLLUP or CUBE extensions to GROUP BY in some dialects.GROUP BY, ORDER BY, PARTITION BY, WINDOW FUNCTIONS, HAVING, DISTINCT, LIMIT
ANSI SQL-86
BY pairs with GROUP, ORDER, or PARTITION to define how rows are grouped, sorted, or partitioned.
No. Use BY only when you need GROUP BY, ORDER BY, or PARTITION BY. Simple selects that do not aggregate or sort do not need it.
Not necessarily. Some engines may output grouped rows in sorted order as a side effect, but the SQL standard does not guarantee this. Always add ORDER BY if order is essential.
All nonaggregated columns in the SELECT list must be present in the GROUP BY clause, or be functionally dependent on the grouped columns. Add the column to GROUP BY or wrap it in an aggregate function.