Question

Many times I have to run this query:

select * from users where name is not null and name != ''

Is there any better way to do this. I need more performance, any suggestion. I guess this is very common, so there may be some compiled function which will be something like

select * from users where name is present()

Using PostgreSQL 9 version.

Was it helpful?

Solution

For any x, null != x will be null and null is not true. That means that you can simply ignore NULLs in your case and say:

select * from users where name != ''

You could also convert NULLs to empty strings using COALESCE if that's clearer to you:

select * from users where coalesce(name, '') != ''

Of course that coalesce call isn't free.

Demo: http://sqlfiddle.com/#!2/e810c/2

OTHER TIPS

You can use NULLIF:

SELECT  * 
FROM    USERS 
WHERE   NULLIF(NAME,'') IS NOT NULL
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top