Select First Matching Row For All Variations of Condition

Note: If this doesn’t meet what you’re looking for in terms of selecting first matching rows, leave a comment below and I’ll look into it. Alternatively, you can go back to the index page of SQL queries.

Situation: You have a table called Products. Inside there are 3 fields: id, category_id, status. And the dummy data looks like this:

idcategory_idstatus
11
active
21inactive
32active
42inactive
51active
61inactive
72active
83active

You want to select all the first matching rows that have the same status and category_id. Which means you want :

idcategory_idstatus
11
active
21inactive
32active
42inactive
83active

As you can see, I use the id field to determine which matching rows are considered as first. The fields I look at for matching criteria are category_id and status.

MySQL

TBD

Postgres

SELECT category_id, status, MIN(id)
FROM Products
GROUP BY category_id, status