I would like to query a table which has few columns (such as 4 below) from where i would like to create a snapshot table which can provide insight on the attribute count everyday
| userId | attr1 | attr2 | attr3 |
|---|---|---|---|
| 1 | true | Hello | Dog |
| 2 | false | Hi | |
| 3 | Hello | ||
| 4 | false | Cat | |
| 5 | true | Hi | Dog |
| 6 | false | Cat | |
| 7 | Hi | ||
| 8 | false | Dog | |
| 9 | Cat | ||
| 10 | false | Hello | Cat |
Such as from above
| userIdCount | attrName | dateWhenSnapshotInserted |
|---|---|---|
| 7 | attr1 | April 16, 2024 |
| 6 | attr2 | April 16, 2024 |
| 7 | attr3 | April 16, 2024 |
In this case, we may have millions of rows in original table with more than 100 columns and we would like to populate snapshot table everyday with count of user with non null values for each attribute and date when this snapshot created.
I am framing my query as below :-
select COUNT(DISTINCT userId) as userIdCount from orig_table where attr1 IS NOT NULL UNION Select COUNT(DISTINCT userId) as userIdCount from orig_table where attr2 IS NOT NULL UNION Select COUNT(DISTINCT userId) as userIdCount from orig_table where attr3 IS NOT NULL; Is there a optimized way to write multiple select query together. I started with creating multiple select query and inserting it to output table one by one but that seems like a bad pattern. Please suggest how to achieve this so as this can be scaled.
ps: Newbie (who is exploring DB queries first time)
materialized view. A regularviewwould recalculate the query on eachselectfrom it, whereas amaterialized viewkeeps a snapshot of the result until yourefreshit. The multiple selects part of the problem can be handled with dynamic SQL in a PL/pgSQL block.