How to Select the First Row of Each Group by Group in SQL

Have you ever wanted to select the first row of each group in a SQL query? If so, you're in luck! SQL has a handy way of doing this that can help you get the results you need.

The Solution

The solution is to use the ROW_NUMBER() function. This function takes two arguments, the first being the column you want to group by and the second being the column you want to select. For example, if you wanted to select the first row of each group in the name column of your database, you would use the following query:

SELECT * FROM (SELECT *, ROW_NUMBER() OVER (PARTITION BY name ORDER BY name) AS row_num FROM table_name) t WHERE t.row_num = 1;

Examples

Let's look at a few examples of how this function can be used. Suppose you have a table called users with the following data:

users
nameage
John25
Jane30
John25
Bob20

If you wanted to select the first row of each group in the name column, you would use the following query:

SELECT * FROM (SELECT *, ROW_NUMBER() OVER (PARTITION BY name ORDER BY name) AS row_num FROM users) t WHERE t.row_num = 1;

This query would return the following result:

users
nameage
John25
Jane30
Bob20

Additional Info

The ROW_NUMBER() function is supported by most major databases, including MySQL, PostgreSQL, and SQL Server. However, the syntax may vary slightly depending on the database you are using. For more information, check out the documentation for your particular database. 🤓

Want to build your own LLM Apps with AirOps👇👇