0

PostgreSQL Version 11.6. The requirement is select/return the rows if column value present in the table or else return the default value. The column value is passed as the input to the query. Here is the test data

create table test (id int,c1 varchar(10));

insert into test values (1,'A');
insert into test values (1,'B');
insert into test values (1,'C');
insert into test values (1,'D');
insert into test values (1,'E');
insert into test values (2,'F');
insert into test values (2,'G');
insert into test values (2,'H');
insert into test values (0,'Default');

What I tried?

select * from test where id = coalesce((select distinct id from test where id = 1),0);

It will return the all the id = 1 rows in the table.

select * from test where id = coalesce((select distinct id from test where id = 11),0);

It will return the id = 0 Default row in the table since id = 11 is not there in the table.

Is there better way to do this? Because I query the table twice to get the result and it may degrade the performance. is there any efficient way to do this?

1 Answer 1

0

Hmm, I don't think your approach is half bad... It depends on how well the optimizer shrinks down the subquery to a mere existence check. So maybe explicitly using EXISTS can improve performance?

SELECT t1.*
       FROM test t1
       WHERE EXISTS (SELECT *
                            FROM test t2
                            WHERE t2.id = ?)
             AND t1.id = ?
              OR NOT EXISTS (SELECT *
                                    FROM test t2
                                    WHERE t2.id = ?)
                 AND t1.id = 0;
                 

Either way you want an index on (id).

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.