CertSafari
    Databricks Certified Data Analyst Associate· Lessons

    Domain 4 · Lesson 15/39

    Sorting and filtering query results in Databricks SQL

    Perform sorting and filtering operations on a table.

    19 min read
    2.22% of exam
    9 sources
    Published 22 Oct 2026
    Docs as of 17 Oct 2026

    What you will be able to do

    • Write ORDER BY clauses with explicit direction, multiple sort keys, column positions and ORDER BY ALL, and predict the resulting row order
    • Control where NULLs land in a sort with NULLS FIRST and NULLS LAST, and state the defaults for ASC and DESC
    • Explain why SORT BY does not produce a globally ordered result and when ORDER BY is required instead
    • Slice a sorted result with LIMIT and OFFSET, and recognise the cost of paging this way
    • Choose between WHERE, HAVING and QUALIFY based on whether the filter applies to rows, groups or window function results
    • Filter a result set in the SQL editor results panel without editing the query

    Key concept

    Filter and sort stages — Each clause works at a fixed stage of a query. WHERE removes rows coming out of FROM, HAVING removes groups after GROUP BY, QUALIFY removes rows after window functions are computed, and ORDER BY then LIMIT/OFFSET shape the final result. If you know which stage a value exists at, you know which clause can test it or sort by it.

    1.Ordering rows with ORDER BY

    A query returns rows in no guaranteed order until you add ORDER BY. That clause is how a report shows the biggest customers first or a dashboard lists the newest orders at the top. ORDER BY sorts the complete result set, across all the partitions the engine split the work into, so the order you write is the order you get.

    Each sort expression can take a direction, ASC or DESC. If you leave it out, the sort is ascending. Writing ORDER BY revenue therefore means smallest first. To put the largest values on top you have to write DESC.

    With multiple keys, sorting runs left to right. All rows are first sorted by the first expression. The second expression only breaks ties among rows that share a value of the first, and so on down the list. Each key has its own direction, so ORDER BY name ASC, age DESC is valid. If two rows tie on every key, their relative order is not deterministic, and one run can return them differently from the next. Add a unique column such as an id as the last key when the order must be stable.

    Two sort keys with different directions: name ascending, then age descending within equal namessql
    -- Sort rows based on more than one column with each column having different
    -- sort direction.
    > SELECT * FROM person ORDER BY name ASC, age DESC;
     500    Dan   50
     400  Jerry NULL
     100   John   30
     200   Mary NULL
     300   Mike   80

    There are two shorthands. An integer literal such as ORDER BY 2 refers to a column position in the select list. A position that doesn't exist raises ORDER_BY_POS_OUT_OF_RANGE, so SELECT name FROM person ORDER BY 2 fails. ORDER BY ALL stands for every expression in the SELECT list, in the order they appear, and a direction written after ALL applies to each of them. With SELECT * on a table whose first column is id, ORDER BY ALL ASC sorts by id first, and the remaining columns only matter for ties. Some types can't be ordered at all. Sorting by a MAP raises DATATYPE_MISMATCH.INVALID_ORDERING_TYPE.

    ORDER BY forms and what they mean
    FormMeaning
    ORDER BY ageAscending by age (the default direction)
    ORDER BY age DESCDescending by age
    ORDER BY name ASC, age DESCBy name; age breaks ties among equal names
    ORDER BY 2By the second column of the select list; out of range raises ORDER_BY_POS_OUT_OF_RANGE
    ORDER BY ALL ASCBy every select-list expression, left to right, each ascending

    Checkpoint 1 of 9· Fill the gap

    The output below is sorted by name first, with age breaking ties. Which keyword completes the first sort key so the query returns exactly these rows?

    -- Sort rows based on more than one column with each column having different
    -- sort direction.
    > SELECT * FROM person ORDER BY name  ? , age DESC;
     500    Dan   50
     400  Jerry NULL
     100   John   30
     200   Mary NULL
     300   Mike   80

    Sources1

    2.Where NULLs land: NULLS FIRST and NULLS LAST

    A NULL is a missing value rather than a number or a date, so comparisons involving it follow NULL three-valued logic in comparisons. Sorting still needs to put those rows somewhere, and Databricks SQL does that with a fixed default that you can override.

    The default follows the direction. Under ASC NULLs come first, and under DESC they come last. A plain ORDER BY revenue therefore opens with every NULL revenue row, above the smallest real amount. NULLs aren't left out of the sort and don't keep their storage position, and a numeric column that contains NULLs sorts without error and without COALESCE.

    Default ascending sort: NULL ages appear before every numbersql
    -- Sort rows by age. By default rows are sorted in ascending manner with NULL FIRST.
    > SELECT name, age FROM person ORDER BY age;
     Jerry NULL
      Mary NULL
      John   30
       Dan   50
      Mike   80

    NULLS FIRST and NULLS LAST override the default for one sort key, whichever direction that key uses. ORDER BY age NULLS LAST keeps ascending order but moves the missing ages to the end. ORDER BY age DESC NULLS FIRST puts the largest ages first and the NULLs above them.

    Here is a case that combines both ideas. A dashboard should show the newest orders first, and within one order date it should group a missing ship_date with the earliest-shipped orders. Newest first means order_date DESC. Earliest-shipped first within a day means ship_date ASC. Writing NULLS FIRST on that second key puts the missing ship dates at the front of each same-day group. The result is ORDER BY order_date DESC, ship_date ASC NULLS FIRST. Ascending would put NULLs first anyway, but the explicit keyword records the requirement in the query, so anyone who later flips that key to DESC won't silently move the NULLs to the end. Making order_date ascending breaks the newest-first requirement, and making ship_date descending sends its NULLs to the end of each group by default.

    Checkpoint 2 of 9· Check yourself

    A finance report should list the highest revenue first. Rows where revenue is NULL must appear at the very top so analysts review them before anything else. Which clause does this?

    Checkpoint 3 of 9· Exam question

    An analyst runs SELECT region, revenue FROM sales ORDER BY revenue; against a table where some rows have a NULL revenue value. In the returned result set, where do those NULL revenue rows appear relative to the numeric values?

    Checkpoint 4 of 9· Exam question

    A dashboard designer wants the newest orders to always appear first, and among orders placed on the same day, wants missing ship_date values grouped with the earliest-shipped orders rather than trailing at the end. Which clause satisfies both requirements?

    Sources1

    3.Why SORT BY is not a global sort

    SORT BY looks like ORDER BY. It has the same direction keywords, the same NULLS FIRST/NULLS LAST options and the same left-to-right handling of multiple keys. The difference is how much of the result it orders. SORT BY sorts the rows within each Spark partition separately. When the data is spread across several partitions, the output is only partially ordered: each partition's block is sorted, but the blocks aren't sorted against one another.

    SORT BY name after repartitioning by zip_code: names are sorted within each zip code, not across the whole resultsql
    -- Sort rows by `name` within each partition in ascending manner
    > SELECT /*+ REPARTITION(zip_code) */ name, age, zip_code FROM person
        SORT BY name;
       Anil K   27    94588
       Dan Li   18    94588
       John V NULL    94588
      Zen Hui   50    94588
     Aryan B.   18    94511
      David K   42    94511
     Lalit B. NULL    94511

    In that output, "Aryan B." comes after "Zen Hui". Each zip code partition is in order, but the result as a whole isn't alphabetical. Use ORDER BY whenever a person or a LIMIT relies on the order. SORT BY only fits when order inside each partition is all you need. The two can't be combined in one query: ORDER BY excludes SORT BY, CLUSTER BY and DISTRIBUTE BY. CLUSTER BY has the same effect as DISTRIBUTE BY and SORT BY together, so it also orders only within partitions.

    Checkpoint 5 of 9· Check yourself

    Which statement about SORT BY in Databricks SQL is accurate?

    Sources231

    4.Slicing a sorted result with LIMIT and OFFSET

    LIMIT caps how many rows a query returns, and OFFSET skips a number of rows before the returned ones start. Both run after the sort, which is why they're almost always paired with ORDER BY. Without a total order, "the first ten rows" isn't a well-defined set.

    Rows 4 and 5 in alphabetical order: skip three, return twosql
    -- Select the 4th and 5th rows by alphabetical order.
    > SELECT name, age FROM person ORDER BY name LIMIT 2 OFFSET 3;
      Mike A  25
     Shone S  16

    The LIMIT value has to be a constant integer expression. LIMIT length('SPARK') works because it folds to 5. LIMIT length(name) depends on each row, so it raises INVALID_LIMIT_LIKE_EXPRESSION, as do a negative value and NULL. LIMIT ALL applies no limit, which is handy when a parameter or template always emits a LIMIT clause.

    Paging with LIMIT and OFFSET hides rows but doesn't avoid the work of producing them. To return page 50, the engine still processes every row on pages 1 to 49 and then suppresses them. On a cheap query that's harmless. On a resource-intensive one, every later page costs more than the one before it, so this way of paging isn't advised there.

    Checkpoint 6 of 9· Fill the gap

    Which LIMIT argument makes this query run and return exactly the five rows shown?

    -- A function expression as an input to LIMIT.
    > SELECT name, age FROM person ORDER BY name LIMIT  ? ;
      Anil B  18
      Jack N  16
      John A  18
      Mike A  25
     Shone S  16

    Sources43

    5.WHERE, HAVING and QUALIFY: filtering at the right stage

    A SELECT has three filtering clauses, and each one tests rows at a different point in the query. WHERE filters the rows produced by FROM, before any grouping. HAVING filters the groups produced by GROUP BY. QUALIFY filters rows after window functions have been computed. Which clause you can use depends on whether the value you're testing exists yet at that stage.

    No. WHERE runs on individual rows before aggregation, and at that point no total_spent exists for it to read. An aggregate, window or generator function inside WHERE raises INVALID_WHERE_CONDITION. The condition belongs in HAVING, which runs after GROUP BY and can use aggregate functions, grouping columns, constants, and an aggregate's alias from the select list. WHERE and HAVING aren't interchangeable. Neither LIMIT nor ORDER BY depends on HAVING being present, so taking HAVING out doesn't break or silently disable them.

    HAVING filters groups and can refer to an aggregate by its aliassql
    -- `HAVING` clause referring to aggregate function by its alias.
    > SELECT city, sum(quantity) AS sum FROM dealer GROUP BY city HAVING sum > 15;
      Dublin  33
     Fremont  32

    HAVING has limits of its own. Referring to a column that's neither in GROUP BY nor inside an aggregate raises MISSING_AGGREGATION. HAVING without GROUP BY is allowed and treats the whole table as one group: SELECT sum(quantity) FROM dealer HAVING sum(quantity) > 10 returns the single total or nothing.

    QUALIFY handles a filter that neither of the others can: keeping rows based on a window function such as RANK() OVER (...). That covers "top seller per model" style questions. At least one window function must appear in the select list or in the QUALIFY clause itself, and QUALIFY can't contain aggregate functions, because aggregates belong to HAVING. It saves you from wrapping the query in a subquery just to filter on a rank.

    QUALIFY keeps only the rows where the window function returns rank 1sql
    -- QUALIFY with window functions in the QUALIFY clause.
    SELECT city, car_model
    FROM dealer
    QUALIFY RANK() OVER (PARTITION BY car_model ORDER BY quantity) = 1;
     city     car_model
     -------- ------------
     San Jose Honda Accord
     Dublin   Honda CRV
     San Jose Honda Civic
    Which filter clause applies at which stage
    ClauseFiltersCan use aggregates?Typical error when misused
    WHERERows from the FROM clause, before groupingNoINVALID_WHERE_CONDITION
    HAVINGGroups produced by GROUP BYYesMISSING_AGGREGATION
    QUALIFYRows after window functions are computedNoRequires a window function in SELECT or QUALIFY

    Checkpoint 7 of 9· Match them up

    Match each filtering requirement to the clause that can express it directly in one SELECT on the dealer table.

    Tap a term, then the definition that fits it.

    Checkpoint 8 of 9· Exam question

    An analyst writes SELECT customer_id, SUM(amount) AS total_spent FROM orders GROUP BY customer_id HAVING SUM(amount) > 500 ORDER BY total_spent DESC LIMIT 5; to find the five biggest spenders. A teammate suggests replacing the HAVING clause with an equivalent WHERE total_spent > 500 before the GROUP BY. Why does that suggested change fail?

    Sources5678

    6.Filtering in the results panel without changing the SQL

    Sometimes the question changes after the query has finished, for example "only the EMEA rows" or "just the ones above 1,000". The SQL editor results panel lets you filter the returned result set without editing and re-running the statement. Results filters narrow what's displayed to a subset of the data. The query text stays the same.

    To add a filter, click the filter icon and describe in words the filter you want. Genie Code turns that into a named filter applied to the result set. To change it, click the filter's name and adjust the drop-downs and text fields. From there you can make the match case sensitive or add an OR condition for an additional filter.

    The new SQL editor supports many more filter types than the legacy editor. Equality, "is one of", contains, starts with, between, and true/false filters work in both. Negations, ends-with, null checks, numeric comparisons such as greater than, date before/after, and OR conditions need the new editor.

    Selected results-panel filter types and legacy editor support
    Filter typeSupported in legacy editor
    Is equal toYes
    Is one ofYes
    ContainsYes
    BetweenYes
    Is nullNo
    Greater thanNo
    BeforeNo
    OR conditionsNo

    Checkpoint 9 of 9· Check yourself

    An analyst runs a query that ends in LIMIT 100 and only wants to see the EMEA rows. They could add a results-panel filter for region equals EMEA, or add WHERE region = 'EMEA' to the query and run it again. How do the two results differ?

    Sources9

    Sources

    (9)

    Every claim above is drawn from one of these pages, quoted as it was written on the date shown.

    1. 1.
      “If sort direction is not explicitly specified, then by default rows are sorted ascending.”
      ↩︎ Ordering rows with ORDER BY
      “The resulting order not deterministic if there are duplicate values across all order by expressions.”
      ↩︎ Ordering rows with ORDER BY
      “A shorthand equivalent to specifying all expressions in the SELECT list in the order they occur.”
      ↩︎ Ordering rows with ORDER BY
      “If the expression is a literal INTEGER value it is interpreted as a column position in the select list.”
      ↩︎ Ordering rows with ORDER BY
      “NULLs sort first if sort order is ASC and NULLS sort last if sort order is DESC.”
      ↩︎ Where NULLs land: NULLS FIRST and NULLS LAST
      “NULL values are returned first regardless of the sort order.”
      ↩︎ Where NULLs land: NULLS FIRST and NULLS LAST
      “Unlike the SORT BY clause, this clause guarantees a total order in the output.”
      ↩︎ Why SORT BY is not a global sort
      “NULLs sort first if sort order is ASC and NULLS sort last if sort order is DESC.”
      ↩︎ Exam trap 1
      “NULLS FIRST: NULL values are returned first regardless of the sort order.”
      ↩︎ Checkpoint
    2. 2.
      “When the data is spread across multiple Spark partitions, SORT BY might return a partially ordered result.”
      ↩︎ Why SORT BY is not a global sort
      “When the data is spread across multiple Spark partitions, SORT BY might return a partially ordered result.”
      ↩︎ Exam trap 2
    3. 3.
      “This parameter is mutually exclusive with SORT BY, CLUSTER BY, and DISTRIBUTE BY and cannot be specified together.”
      ↩︎ Why SORT BY is not a global sort
      “Pagination with this technique is not advised for resource-intensive queries.”
      ↩︎ Slicing a sorted result with LIMIT and OFFSET
      “When paging through a result set using LIMIT and OFFSET the skipped rows still get processed.”
      ↩︎ Exam trap 4
    4. 4.
      “In general, this clause is used in conjunction with ORDER BY to ensure that the results are deterministic.”
      ↩︎ Slicing a sorted result with LIMIT and OFFSET
      “If the expression is not foldable, is not of integer type, evaluates to NULL, or evaluates to a negative value, Databricks raises INVALID_LIMIT_LIKE_EXPRESSION.”
      ↩︎ Slicing a sorted result with LIMIT and OFFSET
    5. 5.
      “Filters the result of the FROM clause based on the supplied predicates.”
      ↩︎ WHERE, HAVING and QUALIFY: filtering at the right stage
      “If you specify HAVING without GROUP BY, it indicates a GROUP BY without grouping expressions (global aggregate).”
      ↩︎ WHERE, HAVING and QUALIFY: filtering at the right stage
      “The HAVING clause is used to filter rows after the grouping is performed.”
      ↩︎ Key concept
      “The HAVING clause is used to filter rows after the grouping is performed.”
      ↩︎ Checkpoint
      “WHERE Filters the result of the FROM clause based on the supplied predicates.”
      ↩︎ Checkpoint
    6. 6.
      “If the expression contains an aggregate function, a window function, or a generator function, Databricks raises INVALID_WHERE_CONDITION.”
      ↩︎ WHERE, HAVING and QUALIFY: filtering at the right stage
      “If the expression contains an aggregate function, a window function, or a generator function, Databricks raises INVALID_WHERE_CONDITION.”
      ↩︎ Exam trap 3
    7. 7.
      “If the expression references columns that are neither in the GROUP BY clause nor wrapped in aggregate functions, Databricks raises MISSING_AGGREGATION.”
      ↩︎ WHERE, HAVING and QUALIFY: filtering at the right stage
    8. 8.
      “To use QUALIFY, at least one window function is required to be present in the SELECT list or the QUALIFY clause.”
      ↩︎ WHERE, HAVING and QUALIFY: filtering at the right stage
      “The expressions specified in the QUALIFY clause cannot contain aggregate functions.”
      ↩︎ WHERE, HAVING and QUALIFY: filtering at the right stage
    9. 9.
      “Filters allow you to limit the result set after a query has run.”
      ↩︎ Filtering in the results panel without changing the SQL
      “You can apply filters to selectively show different subsets of the data.”
      ↩︎ Filtering in the results panel without changing the SQL
      “(Optional) Click Add OR condition to add an additional filter.”
      ↩︎ Filtering in the results panel without changing the SQL

    Ready to test yourself?

    Practise the 10 questions on this subdomain.

    Spotted a mistake, or was something unclear? Tell us.