I'm working on optimizing a query for a PostgreSQL database used in an educational platform.
The query retrieves distinct question_id
values along with their is_seen
status from the question_interaction
table based on specific user
, customer_id
, student_id
, and tag
criteria. Here's the query:
SELECT DISTINCT ON (question_id) question_id, is_seen
FROM question_interaction
WHERE user_id = 'USR234342'
AND customer_id = '39874513-8bb1-461e-a73f-9e73fa31870d'
AND student_id = '8179483214'
AND tags @> ARRAY ['history']::TEXT[]
AND is_seen IS NOT NULL
ORDER BY question_id, timestamp DESC;
Here is the selectivity order of the columns:
question_id > student_id > user_id > customer_id
Can someone provide guidance on how to create an effective index for this query?
Specifically, I'm looking for recommendations on:
- The choice of columns for the index
- The order of columns in the index
- Any additional conditions to consider
CREATE INDEX question_interaction_is_seen_pix ON question_interaction WHERE is_seen IS NOT NULL;
. What is the difference between a student, a user and a customer - how many records per table (I assume they are also in separate tables) and how many times do they apppear in the question_interaction table (PK)? The complete DDL of question_interaction would be good - I'd work under the assumption that the_id
fields are PKs of their respective tables!CREATE TABLE
statement), Postgres version, and cardinalities: Roughly how many rows total, how many distinct combinations of(user_id, customer_id, student_id)
, how many distinct elements in yourtags
array, how many in the according filter (you show one) and how manyis_seen IS NULL
. Also, how much write load vs. read, and how important is this particular query?