Skip to content
Advertisement

How to query for missing fields and associations and return what’s missing in PostgreSQL?

I am learning more raw SQL after coming from years of Rails and other ORMs, so have quite a ways to learn how to do complex queries efficiently. What I’m wondering here is _how to find all users which are missing some fields and associations, and returning which fields/associations they are missing.

I have a rough idea of how to write this in SQL but not exact (for PostgreSQL).

I have something like this data model, a table of users, a table of “social media links”, and an association mapping the link to the user, so a user can have many social media links, but there could be more than one user associated with one link (i.e. organizations):

The question is, how do you perform the query (with this pseudocode):

In natural language, “select the users which either don’t have a name or a description, or are missing a linkedin or facebook link (sociallinks.value), and return what fields they are missing”.

I can do this the naive, long and convoluted way or querying one thing at a time, but I’m wondering how to do this efficiently, in possibly just one query (or as few queries as possible).

Fetch those, then do:

Then the next query is more complex, but I would do one at a time.

How do you do it somewhat efficiently and in as few queries as possible? Fetching with a limit of say 100 users per query.

Input data would be:

Output data would be:

Advertisement

Answer

EXISTS() to the rescue:


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