SELECT users.id
FROM orders, users, "userEmailCollections", "reviewTracks", "loyaltyCampaignRedemptions"
WHERE (orders."restaurantTableId" IN (12,7,9,8,10,11,14,99,100,6)
AND users.id = orders."orderUserId")
OR ("userEmailCollections"."restaurantId" = 6
AND "userEmailCollections"."userId" = users.id)
OR ("reviewTracks"."restaurantId" = 6
AND users.email = "reviewTracks"."email")
OR ("loyaltyCampaignRedemptions"."restaurantId" = 6
AND "users".id = "loyaltyCampaignRedemptions"."userId");
I’m trying to run the above query to get me all the user ids for users which have relationships with any of the other tables – so for example if a user has an order
, or a userEmailCollection
I would like their id to show up in the query output.
However, this query hangs without producing a response and I’m not sure why.
3
Answers
I would say the query can look something like this
Echoing the above comments….be explicit in the join syntax and break the query into smaller sub queries. It’ll help the db to generate a more efficient execution plan. for example:
Here the each cte joins the 2 tables and filters on specific conditions vs a cartesian join. using distinct will help remove the duplicate rows from the results set. It’s also a bit easier to read and follow.
There’s no reason to join the tables because the query is about the presence of an association and not the attributes of the associations. The following query should return the desired result in reasonable time:
DISTINCT is included in the subqueries to improve performance in case there are a large number of duplicate user IDs or emails in the associated tables. Because these are inclusion tests, not using DISTINCT will not change the result set.