Skip to content
Advertisement

PostgreSQL: How to get only the first result from a SELECT

In my database, I have two columns, products, and products_photos, where products can have many products_photos. What I want to do is a query that returns the products but with only one photo. I manage to write a query like this:

SELECT products.*, file
FROM products, products_photos
WHERE products.id = products_photos.product_id
ORDER BY products.id

But still, this returns the same product, multiple times, because of the photos. I already tried to use DISTINCT and LIMIT but does not work properly.

Advertisement

Answer

First, learn to use proper, explicit, standard, readable JOIN syntax. Never use commas in the FROM clause.

Second, Postgres has a very convenient extension, DISTINCT ON, that does what you want:

SELECT DISTINCT ON (p.id) p.*, pp.file
FROM products JOIN
     products_photos pp
     ON p.id = pp.product_id
ORDER BY p.id
User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement