How to add a custom column with a default value in an sql query?

Yes, that's quite easy:

select first_name, 
       last_name,
       'test' as default_value, --<< a "virtual" column containing a character value
       42 as the_answer         --<< another column containing a numeric value
from table1 
  join table2 on table1.id = table2.customer_id;

You should also stop using those outdated implicit joins in the WHERE clause. Use an explicit JOIN operator instead. It makes the queries more robust against accidentally forgotten join conditions.


"Is there any option to put a condition on the virtual column's value?"

select first_name, 
   last_name,
   CASE WHEN first_name = 'Mary' THEN 'test' WHEN first_name = 'John' THEN 'test2' 
        ELSE 'Not known' END as default_value,
   42 as the_answer
from table1 
join table2 on table1.id = table2.customer_id;

Tags:

Sql

Postgresql