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:
name | age |
---|---|
John | 25 |
Jane | 30 |
John | 25 |
Bob | 20 |
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:
name | age |
---|---|
John | 25 |
Jane | 30 |
Bob | 20 |
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. 🤓