Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Return Default value if no row found

Tags:

mysql

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?

like image 306
Jadeja RJ Avatar asked May 09 '14 06:05

Jadeja RJ


People also ask

How do you return null if there is no records found SQL?

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.

How do I assign a default value if no rows returned from the select query mysql?

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.

What does a SQL query return if nothing is found?

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.


2 Answers

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:

  • The first is the value of the column searched with the default value set in case the row does not exist.
  • The second column returns the number of rows with the filter in the table
like image 105
Jose Romero Avatar answered Sep 24 '22 19:09

Jose Romero


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

like image 32
ashish Avatar answered Sep 24 '22 19:09

ashish