How do I check if a column is empty or null in MySQL?
This will select all rows where some_col
is NULL
or ''
(empty string)
SELECT * FROM table WHERE some_col IS NULL OR some_col = '';
How to check if field is null or empty in MySQL?
Either use
SELECT IF(field1 IS NULL or field1 = '', 'empty', field1) as field1
from tablename
or
SELECT case when field1 IS NULL or field1 = ''
then 'empty'
else field1
end as field1
from tablename
If you only want to check for null
and not for empty strings then you can also use ifnull()
or coalesce(field1, 'empty')
. But that is not suitable for empty strings.
MySQL - Which way is better to check if a column is null or empty
Evaluating the two expressions on a single row should not take such a big difference. The reason people use the second version is the use of indexes. Mysql has a special optimization for this and can use it even with the or
.
See IS NULL Optimization
IS NULL Optimization
MySQL can perform the same optimization on col_name IS NULL that it can use for col_name = constant_value. For example, MySQL can use indexes and ranges to search for NULL with IS NULL.
If a WHERE clause includes a col_name IS NULL condition for a column that is declared as NOT NULL, that expression is optimized away. This optimization does not occur in cases when the column might produce NULL anyway; for example, if it comes from a table on the right side of a LEFT JOIN.
MySQL can also optimize the combination col_name = expr OR col_name IS NULL, a form that is common in resolved subqueries. EXPLAIN shows ref_or_null when this optimization is used.
Check if MySQL Column is empty
If it's empty, it should output all the bets from a user. The code posted is in a for loop.
Since you are checking if it's empty, your if
statement should be the other way round:
if ($row['status'] == '') {
Alternatively, you can use mysqli_num_rows()
get the number of rows:
Returns the number of rows in the result set.
$result = queryMysql("SELECT * FROM bets WHERE user='$user'");
if (mysqli_num_rows($result) > 0) {
$row = mysqli_fetch_array($result);
echo "Status: " . $status . "