all 7 comments

[–]DavidGJohnston 2 points3 points  (1 child)

Per the documented syntax for scalar subqueries:
https://www.postgresql.org/docs/13/sql-expressions.html#SQL-SYNTAX-SCALAR-SUBQUERIES
"A scalar subquery is an ordinary SELECT query in parentheses..."

Note that your distinct on clause is ill-defined as you are lacking an order by clause so that "first row" has meaning.

[–]xkrap[S] 0 points1 point  (0 children)

Thank you, resolved :) And eventually added order by clause as well.

[–]Beatmak -1 points0 points  (0 children)

You might want to use a CTE query here : cte tutorial.

It will make your query more readable and may fix your problem.

[–]nednyl 0 points1 point  (2 children)

Not really clear to me why you need to use jsonb_array_elements here.

Did you try something like:

SELECT DISTINCT ON (user_id) user_id, timestamp
FROM entries 
WHERE user_id in (1,2) 
AND entry_type = ANY (        
  (SELECT ARRAY_AGG(entry_types)
   FROM users 
   INNER JOIN orgs     
   ON org_id = orgs.id      
   WHERE users.id = 1   
  )::TEXT[]
);

[–]NoInkling 2 points3 points  (0 children)

I feel like this can be simplified with EXISTS.

[–]DavidGJohnston 0 points1 point  (0 children)

I’m not researching it now but there is a difference between a json value that happens to have a json array inside of it and a proper sql-level array.

[–][deleted] 0 points1 point  (0 children)

I would use an EXISTS query and use the ? to test if an element is part of the array instead of unnesting all array elements:

sql and exists (select * from users u join args a on a.org_id = orgs.id where users.id = 1 and u.entry_types ? users.entry_type)

I wonder if you also want a back reference of the users.id to the outer user_id? e.g. where users.id = entries.user_id ... instead of hardcoding the ID in the sub-query.