Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PostgreSQL IS NULL and length

I am trying to get all records from a table where a specific column is NULL. But I am not getting any records. On the other hand, there are many records where the length(field) is indeed 0.

select count(*) from article a where length(for_interest) =0;
 count 
-------
     9
(1 row)

select count(*) from article a where for_interest is NULL ;
 count 
-------
     0
(1 row)

Something about NULLs I didn't get right? More info

select count(*) from article AS a where for_interest is NOT NULL ;
 count 
-------
    15
(1 row)

select count(*) from article ;
 count 
-------
    15
(1 row)

PostgreSQL version is 9.3.2.

Adding sample data, table description etc (new sample table created with just 2 records for this)

test=# \d sample_article 
           Table "public.sample_article"
    Column    |          Type          | Modifiers 
--------------+------------------------+-----------
 id           | integer                | 
 title        | character varying(150) | 
 for_interest | character varying(512) | 

test=# select * from sample_article where length(for_interest)=0;
 id |                              title                              | for_interest 
----+-----------------------------------------------------------------+--------------
  8 | What is the Logic Behind the Most Popular Interview Questions?  | 
(1 row)

test=# select * from sample_article where for_interest IS NOT NULL;
 id |                              title                              | for_interest 
----+-----------------------------------------------------------------+--------------
  7 | Auto Expo 2014: Bike Gallery                                    | Wheels
  8 | What is the Logic Behind the Most Popular Interview Questions?  | 
(2 rows)

test=# select * from sample_article where for_interest IS NULL;
 id | title | for_interest 
----+-------+--------------
(0 rows)
like image 775
Jayadevan Avatar asked Dec 15 '22 00:12

Jayadevan


1 Answers

Character types can hold the empty string '', which is not a NULL value.
The length of an empty string is 0. The length of a NULL value is NULL.
Most functions return NULL for NULL input.

SELECT length('');   --> 0
SELECT length(NULL); --> NULL

SELECT NULL IS NULL; --> TRUE
SELECT '' IS NULL;   --> FALSE
like image 200
Erwin Brandstetter Avatar answered Jan 04 '23 19:01

Erwin Brandstetter