A query with theDocumentation Index
Fetch the complete documentation index at: https://private-7c7dfe99-test-mutation-observers.mintlify.app/llms.txt
Use this file to discover all available pages before exploring further.
LIMIT n BY expressions clause selects the first n rows for each distinct value of expressions. The key for LIMIT BY can contain any number of expressions.
ClickHouse supports the following syntax variants:
LIMIT [offset_value, ]n BY expressionsLIMIT n OFFSET offset_value BY expressions
LIMIT n BY expressions and returns the first n rows for each distinct combination of expressions. If OFFSET is specified, then for each data block that belongs to a distinct combination of expressions, ClickHouse skips offset_value number of rows from the beginning of the block and returns a maximum of n rows as a result. If offset_value is bigger than the number of rows in the data block, ClickHouse returns zero rows from the block.
LIMIT BY is not related to LIMIT. They can both be used in the same query.LIMIT BY clause, enable the setting enable_positional_arguments.
Examples
Sample table:SELECT * FROM limit_by ORDER BY id, val LIMIT 2 OFFSET 1 BY id query returns the same result.
The following query returns the top 5 referrers for each domain, device_type pair with a maximum of 100 rows in total (LIMIT n BY + LIMIT).
LIMIT BY also works with negative limits and offsets. Similar to the negative LIMIT clause, you can use negative values with LIMIT BY to select rows from the end of each group.
id. For id = 1 we get rows 11 and 12; for id = 2 both rows are returned because the group has only 2 rows.
id: the trailing OFFSET -1 drops the last row per group, and the leading -1 then keeps the last row of what remains.
Different sign LIMIT and OFFSET can be mixed as well. For example, to drop each group’s first row and then keep the last 2 of what remains:
id = 1, the first row (10) is skipped; the last 2 of 11, 12 are both returned. For id = 2, the first row (20) is skipped, leaving only 21.
LIMIT BY ALL
LIMIT BY ALL is equivalent to listing all the SELECT-ed expressions that are not aggregate functions.
For example:
LIMIT BY keys will contain the maximum non-aggregate fields we can extract from it.
For example:
Examples
Sample table:SELECT * FROM limit_by ORDER BY id, val LIMIT 2 OFFSET 1 BY id query returns the same result.
Using LIMIT BY ALL: