I'm building query to search multiple rows from database like
SELECT
*
FROM
table1
WHERE col1 = '012311'
OR col1 = '0123631'
OR col1 = '091233'
OR col1 = '092111'
Here it returns first 3 values because they are present in the table but it returns nothing for last one because it's not in table. So how can I set my default value in the query if no row is found for that value?
Well by definition you can't return anything if there are no records. You would have to force the query to always return a resultset. So you can force the issue but it seems this type of thing is more suited to the front end instead of trying to make sql return data when there is no data to return.
Here's one way: SELECT *, IFNULL( ( SELECT col1 FROM table1 WHERE col1 IN ('012311','0123631','091233','092111') ), 'some_value' ) AS my_col1 FROM table1; Not neccessarily copy+paste, you will have to adjust for your specific case.
If the inner query has no matching row, then it doesn't return anything. The outer query treats this like a NULL, and so the ISNULL ends up returning 0.
The best way I've founded is this:
SELECT COALESCE(col1, 'defaultValue') col1, COUNT(*) cRows
FROM table1
WHERE colx = 'filter';
This query returns 2 columns:
In MySQL you can use IFNULL to return a specified value if no row found i.e. when it returns NULL ex-
SELECT IFNULL( (SELECT col1 FROM table1 WHERE col1 in (your_list)) ,'default_value_you_want_to_return');
you can see examples of IFNULL here - IFNULL Example
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