0

I'm selecting rows from a table where the id is in an array. This works, but I also want to return default values for rows that do not exist in the table.

I currently have

  SELECT
    id,
    column1
  FROM
    table_name
  WHERE
    id = ANY(ids_array_variable)

but, if some of the ids in the array do not exist in the table, then my result is short a few rows. I need it to still return a default record of {id, default_value} so that the result always has the same number of entries as the ids_array_variable

2 Answers 2

5

Use a left join:

select a.id, 
       coalesce(t.column1, 'some default') as column1
from unnest(ids_array_variable) as a(id)
  left join table_name t on t.id = a.id;
Sign up to request clarification or add additional context in comments.

Comments

0

if table serviceconfig have n’t key - ‘my_key’ - use default value

thank @a-horse-with-no-name

SELECT COALESCE(KV.value, def.val) as value
FROM (
    select def.val from unnest(ARRAY ['default']) as def(val)) as def
LEFT JOIN
     (SELECT *
      FROM serviceconfig
      WHERE key = 'my_key') KV on true;

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.