Retrieving Non-Empty Column Values in MySQL
In MySQL, selecting records where specific columns contain non-empty values can be achieved through comparison with an empty string.
Query Optimization:
Consider the following query:
select phone, phone2 from jewishyellow.users where phone like '813%' and phone2
This query aims to retrieve rows where the phone number begins with '813' and phone2 is not empty. However, it suffers from optimization issues.
Optimized Solution:
To optimize the query, compare the phone2 column directly with an empty string:
select phone, phone2 from jewishyellow.users where phone like '813%' and phone2<>''
By using the <> (not equal to) operator, the query excludes rows where phone2 is empty, including those with NULL values. This approach improves query performance by avoiding the evaluation of NULLs.
Note:
It's essential to remember that NULL values are interpreted as false in MySQL. Therefore, the query will not retrieve rows where phone2 has a NULL value, even though they technically contain data.
The above is the detailed content of How to Efficiently Retrieve Rows with Non-Empty Column Values in MySQL?. For more information, please follow other related articles on the PHP Chinese website!