How to fallback to a different value in 'WHERE' clause sql?
Use CASE and Exists like below
Select * from table_name where field1=
case when exists(select 1 from table_name where field1='value1')
then 'value1' else 'default 'end
Optimal solution using coalesce()
:
Select * from table_name where field1 = coalesce (
(select field1 from table_name where field1='value1' limit 1)
, 'default'
);
Notice the limit 1
in the subquery: In this case it is mandatory to ensure that subselect doesn't return more than one row. But even using the case when exists (...)
approach it is a good practice to add it because, otherwise, database engine would be forced to scan all rows matching the subquery.
Of course, most modern databases are smart enough to silently optimize it. But some old ones could not. And anyway, it can be cases where they cant.
That is, for example, in PostgreSQL, if subquery uses non (or non properly declared as) stable functions, the planner would be forced to perform a full scan to produce consistent results if that function has any side effect.
Core ANSI SQL answer, expected to run on all different platforms:
select * from table_name
where field1 = 'value1'
or (field1 = 'default'
and NOT EXISTS (select 1 from table_name where field1 = 'value1'))