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:

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:

User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement