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.
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.
The IN operator allows you to specify multiple values in a WHERE clause. The IN operator is a shorthand for multiple OR conditions.
It is possible to replace HAVING with WHERE, but there is no benefit in doing so.
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.
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'))
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With