// window reference

SQL alternatives to QUALIFY

Every QUALIFY query converts to a CTE filter, a derived-table filter, or a lateral top-N join; each shape fits a different case.

Catégorie
Fenêtre
Returns
filtered rows
In this category
66 of 79

Syntaxe

WITH r AS (... ) WHERE rn = 1 | JOIN LATERAL (...) LIMIT 1

Prise en charge des moteurs

MoteurSupportNotes
SQL Server Oui CROSS APPLY instead of LATERAL
PostgreSQL Oui Supported under this name.
MySQL Oui MySQL 8.0+; LATERAL since 8.0.14
SQLite Oui SQLite 3.25+; no LATERAL keyword; use correlated subqueries in SELECT
Oracle Oui LATERAL and CROSS APPLY since 12c

Exemples

PostgreSQL

-- lateral top-1: fastest when groups are small and numerous
SELECT c.customer_id, top_orders.id, top_orders.amount
FROM customers c
CROSS JOIN LATERAL (
  SELECT o.id, o.amount
  FROM orders o
  WHERE o.customer_id = c.customer_id
  ORDER BY o.amount DESC
  LIMIT 1
) top_orders;

Any engine

-- inline subquery form
SELECT *
FROM (
  SELECT o.*, ROW_NUMBER() OVER (PARTITION BY customer_id ORDER BY amount DESC) AS rn
  FROM orders o
) ranked
WHERE rn = 1;

Bon à savoir

  • The CTE shape wins for reuse (several filters on window columns) and readability; the subquery shape wins for one-shot rn = 1 filters in ORMs that fight CTEs.
  • LATERAL top-1 per group scales differently: it loops the outer row count times but touches few rows per iteration, often faster than windowing a huge partition when the outer side is small.
  • A correlated subquery in SELECT can fetch the top value per row (SELECT MAX(amount) FROM orders o WHERE o.customer_id = c.customer_id) without any window at all; it gets slow when it has to return more than one column.

Questions about QUALIFY Alternatives

Which alternative should I default to?

The CTE wrap: it ports everywhere window functions do, handles multiple window columns, and keeps the window logic in one visible place. Reach for LATERAL only on measured hot paths.

Can I emulate QUALIFY without wrapping the query?

Only with a scalar subquery per value, which loses the shared window. For a general rewrite, wrap the query in a CTE or derived table; that wrap is exactly what QUALIFY saves you.

Browse every function in the SQL function reference, or see what the SQLly desktop app does for your database.

Cheat sheets for the engines that have it: SQL Server, PostgreSQL, MySQL, SQLite, Oracle.

// fewer lookups

Functions your engine actually has

SQLly's completion lists the built-in functions of the engine you're connected to, whether that's SQL Server, PostgreSQL, MySQL, SQLite or Oracle. Hover a function for help, and signature hints show each argument as you type.