0

Setup: Postgresql table with a customer_id and a request_id column (+ additional not relevant data). The rows with customer_id set to NULL work as a fallback/default.

Example what the table looks like:

Example

Goal: I want to select all rows from the table for a given customer (e.g. where customer_id = 2).

For any existent request_id: If there are no entries for the given customer, return the fallback rows (where customer is null).

So the result should look like this:

example goal

Any idea how to write the select statement for postgresql? I'm kind of stuck and couldn't really find anything helpful so far. Thanks!

1

1 Answer 1

0

This is a strange requirement.

select t.*
from t
where t.customer_id = 2 or
      (t.customer_id is null and
       not exists (select 1 from t t2 where t2.request_id = t.request_id and t2.customer_id = 2)
      );

For performance, I would recommend an index on (request_id, customer_id).

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you, this does work, but is very slow (takes 1 to 3 seconds on my local db - compared to 4ms for a select * from t). Any way to optimize it? What is so strange about it? The way we handle default/fallback values? We were trying not to copy all the default values to each customer on create.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.