Skip to content
Advertisement

How to specify a limit on Postgres json_agg

I want a JSON output having the distinct values of a column and also a limited number of rows.

This is the sample table that I have in a Postgres Database:

I want to write an SQL query that returns a list of all the unique author names and also every row but with a limit of 3

This is the SQL query that I have so far

This gives me the following output:

In the above output, the only Authors in the list are James and Alex. However, I want the names of all three authors but still limiting “book_details” to the first three. i.e. I want Amanda to be on the list too.

Basically, this is the output I want:

How do I get all distinct values of a column and still have a limit on the query?

Advertisement

Answer

here is how you can do it;

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