Home >Database >Mysql Tutorial >How to Return a Default Value When a SQL Query Returns No Rows?
Return a Default Value When Query Returns No Rows
When using a SQL query to retrieve data and no matching rows are found, it can be useful to return a default value instead of an empty result. This is especially useful when you want to ensure that something is always displayed, even if there is no data to show.
Consider the following SQL statement:
<code class="sql">SELECT `file` FROM `show`, `schedule` WHERE `channel` = 1 AND `start_time` <= UNIX_TIMESTAMP() AND `start_time` > UNIX_TIMESTAMP()-1800 AND `show`.`id` = `schedule`.`file` ORDER BY `start_time` DESC LIMIT 1</code>
This query attempts to retrieve the next scheduled item for a specific channel, but if no matching row is found, it will return an empty result. To return a default value instead, you can use the COALESCE or IFNULL functions:
<code class="sql">SELECT COALESCE(`file`, 'default.webm') `file` ... SELECT IFNULL(`file`, 'default.webm') `file` ...</code>
However, these solutions may return an empty result if no rows are found. To ensure that a default value is always returned, you can use an aggregate function, such as MIN(), to provide a NULL value when no records are selected. The following statement uses this technique:
<code class="sql">SELECT IFNULL(MIN(`file`), 'default.webm') `file` ...</code>
By using the MIN() function, you can guarantee that NULL will be returned if no rows are selected. Then, the IFNULL() function will replace the NULL value with the default value, ensuring that something is always displayed.
The above is the detailed content of How to Return a Default Value When a SQL Query Returns No Rows?. For more information, please follow other related articles on the PHP Chinese website!