Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to fallback to a different value in 'WHERE' clause sql?

I have a case where i have to fetch records for column field1='value1' if there are no values for 'value1' then i should fetch the record for 'default'.

For the above scenario I have used two queries:

Select * from table_name where field1="value1"

If the above query does not give back any record I fire the following query:

Select * from table_name where field1="default"

Now I want to do the above stated in one query. Can someone please help me with the same. I believe the answer lies somewhere in using CASE WHEN clause.

Also the above queries should work for oracle, postgres as well as mysql.

like image 448
Manas Saxena Avatar asked Aug 02 '16 08:08

Manas Saxena


People also ask

How do I convert one value to another in SQL?

The CONVERT() function in SQL server is used to convert a value of one type to another type. It is the target data type to which the to expression will be converted, e.g: INT, BIT, SQL_VARIANT, etc. It provides the length of the target_type. Length is not mandatory.

WHERE clause pass multiple values?

The IN operator allows you to specify multiple values in a WHERE clause. The IN operator is a shorthand for multiple OR conditions.

Can we replace WHERE with HAVING in SQL?

It is possible to replace HAVING with WHERE, but there is no benefit in doing so.

Can you do two WHERE clauses in SQL?

You can specify multiple conditions in a single WHERE clause to, say, retrieve rows based on the values in multiple columns. You can use the AND and OR operators to combine two or more conditions into a compound condition. AND, OR, and a third operator, NOT, are logical operators.


2 Answers

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'))
like image 125
jarlh Avatar answered Oct 04 '22 02:10

jarlh


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
like image 23
TheGameiswar Avatar answered Oct 04 '22 01:10

TheGameiswar