(have done this before, but memory fades, as does goggle)
wish to get select from users
with the tag.tag_id
s for each user returned as an array.
select usr_id, name, (select t.tag_id from tags t where t.usr_id = u.usr_id) as tag_arr from users u;
with the idea embedded query tag_arr
would be an array
A subquery or Inner query or Nested query is a query within another PostgreSQL query and embedded within the WHERE clause. A subquery is used to return data that will be used in the main query as a condition to further restrict the data to be retrieved.
PostgreSQL ARRAY_AGG() function is an aggregate function that accepts a set of values and returns an array where each value in the input set is assigned to an element of the array. Syntax: ARRAY_AGG(expression [ORDER BY [sort_expression {ASC | DESC}], [...]) The ORDER BY clause is an voluntary clause.
PostgreSQL SELECT statement syntax If you specify a list of columns, you need to place a comma ( , ) between two columns to separate them. If you want to select data from all the columns of the table, you can use an asterisk ( * ) shorthand instead of specifying all the column names.
You can easily create arrays in PostgreSQL by adding square brackets [] immediately after the data type for the column. create table employees ( first_name varchar, last_name varchar, phone_numbers integer[] ); In the above example, we have created column phone_numbers as an array of integers.
Use the aggregate function:
select usr_id, name, array_agg(tag_id) as tag_arr from users join tags using(usr_id) group by usr_id, name
or an array constructor from the results of a subquery:
select u.usr_id, name, array( select tag_id from tags t where t.usr_id = u.usr_id ) as tag_arr from users u
The second option is a simple one-source query while the first one is more generic, especially convenient when you need more than one aggregate from a related table. Also, the first variant should be faster on larger tables.
Note, that for better performance the usr_id
columns in both tables should be indexed. While typically users.usr_id
is a primary key, sometimes one may forget that the index of referencing column is also useful.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With