When working with SQL databases, often you only need the first row of each group of duplicate or similar data. This is where the SQL command 'LIMIT 1' or introducing a 'ROWNUM' or 'ROW_NUMBER()' function with a condition can be beneficial. This article will guide you through using SQL to select only the first row of each group.

Before diving into the specific SQL commands, it's essential to understand that different databases support different functions. In MySQL, you might use 'LIMIT 1', while in Oracle, you'd use 'ROWNUM'. Meanwhile, Microsoft SQL Server and SQL Server Azure would utilize 'ROW_NUMBER()'. Let's explore each of these.

MySQL: Using LIMIT 1
MySQL offers the 'LIMIT' clause to restrict the number of rows in a result set. By using 'LIMIT 1', you can fetch only the first row. However, this won't give you the first row of each group, so we need a combination with 'ORDER BY' and a subquery.

Here's an example: Imagine you have a table 'sales' with 'product', 'price', and 'sale_date' columns. You want to get the first sale of each product.
Getting the first sale of each product

In this case, you can achieve this by ordering the sales by product and sale_date, then limiting the result to one row per group.
SELECT * FROM (SELECT product, price, sale_date FROM sales ORDER BY product, sale_date) AS subquery GROUP BY product LIMIT 1;
Getting the earliest sale of the day

Similarly, if you want to get the earliest sale of each day, you would order by 'sale_date' and 'product', and again, limit to one per group.
SELECT * FROM (SELECT product, price, sale_date FROM sales ORDER BY sale_date, product) AS subquery GROUP BY product LIMIT 1;
Oracle: Using ROWNUM

Oracle's 'ROWNUM' function can be used to select the first row of each group, but it has a limitation - it doesn't filter out duplicate rows. So, you'll need to combine it with a 'WHERE' clause to fetch the first row of each group.
SELECT * FROM (SELECT product, price, sale_date, ROWNUM as rn FROM sales ORDER BY product, sale_date) WHERE rn = 1;









As we can see, each of these SQL solutions offers a unique approach to selecting the first row of each group. Each can be tailored to fit your specific needs. Now that you've understood how to select the first row only using SQL, it's time to apply this knowledge to your own database queries.