简体   繁体   中英

Returning results that are not null in MySQL

I have a MySQL query like so:

SELECT `contact_last_name` FROM `customer` WHERE `contact_last_name` IS NOT NULL

Basically I want to return any rows where the column contact_last_name has something entered in it. If it makes any difference, this column is a VARCHAR column.

But instead, it is returning every row in the database, regardless of whether that column is empty or not!

I'm not sure why this query is not working?

NULL requires the column to actually be NULL . Not an empty string. Are you trying to check if it's empty?

SELECT 
    `contact_last_name` 
FROM 
    `customer` 
WHERE 
    `contact_last_name` != ''

Do you have white space issues?

SELECT 
    `contact_last_name` 
FROM 
    `customer` 
WHERE 
    TRIM(`contact_last_name`) != ''

Can it both be NULL and empty?

SELECT 
    `contact_last_name` 
FROM 
    `customer` 
WHERE 
    `contact_last_name` != '' 
AND 
    `contact_last_name` IS NOT NULL

There's a difference between a varchar being an empty string and it being explicitly NULL. You could try this where clause:

LENGTH(contact_last_name) > 0;

NULL (unknown value) is different to "blank" (known, but zero-length string), so you must check for both:

SELECT contact_last_name
FROM customer
WHERE contact_last_name IS NOT NULL
AND contact_last_name != ''

With mysql, this can be shortened to:

SELECT contact_last_name
FROM customer
WHERE ifnull(contact_last_name, '') != ''

Note also the removal of the unnecessary backticks from your query - none of the column/table names you have are reserved words.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM