How do you select only the first row within each GROUP BY group in SQL? | A1Lab@HumairaM to SQLEnglish • 2 days ago

How do you select only the first row within each GROUP BY group in SQL?

message-square
0

o select the first row within each group in SQL, pair a window function such as ROW_NUMBER() with a PARTITION BY clause instead of relying on GROUP BY alone. GROUP BY collapses rows to one per group, so selecting non-grouped columns requires aggregation or a top-N-per-group pattern.

  1. Standard Pattern: ROW_NUMBER() OVER (PARTITION BY … ORDER BY …) Wrap the ranked query in a Common Table Expression or derived table and filter rn = 1.

SQL WITH ranked_orders AS ( SELECT order_id, customer_id, order_date, total_amount, ROW_NUMBER() OVER ( PARTITION BY customer_id ORDER BY order_date ASC, order_id ASC ) AS rn FROM dbo.orders ) SELECT order_id, customer_id, order_date, total_amount FROM ranked_orders WHERE rn = 1 ORDER BY customer_id; PARTITION BY customer_id restarts numbering for each customer (playing the grouping role).

ORDER BY order_date ASC, order_id ASC defines which row is “first”—add a tie-breaker column (like order_id) so ties are deterministic.

  1. Alternative: CROSS APPLY with TOP (1) (SQL Server) For a small number of parent rows or when fetching one latest child row per parent, CROSS APPLY with TOP (1) can use an index on (parent_key, sort_col) directly:

SQL SELECT c.customer_id, c.customer_name, latest_ord.order_id, latest_ord.order_date, latest_ord.total_amount FROM dbo.customers AS c CROSS APPLY ( SELECT TOP (1) o.order_id, o.order_date, o.total_amount FROM dbo.orders AS o WHERE o.customer_id = c.customer_id ORDER BY o.order_date DESC, o.order_id DESC ) AS latest_ord; Use OUTER APPLY instead of CROSS APPLY if you want to keep parent rows that have zero matching child rows (returning NULLs for the child columns).

  1. Handling Ties: ROW_NUMBER() vs. RANK() / DENSE_RANK() ROW_NUMBER(): Always assigns 1 to exactly one row per partition even if two rows share the exact same ORDER BY sort key.

RANK() / DENSE_RANK(): Assigns 1 to all tied top rows in a partition; use these only when you intentionally want multiple tied rows for a group.

  1. Operational Checklist Include a deterministic tie-breaker in ORDER BY (such as a primary key or timestamp + ID) so “first” does not vary across runs.

Index the partition and sort columns (e.g., (customer_id, order_date DESC, order_id DESC)) to avoid expensive sorts on large tables.

Avoid SELECT * inside the CTE when only a subset of columns is needed.

Test edge cases with NULLs in partition or sort columns (NULLs group together in PARTITION BY and sort first or last depending on dialect/settings).