Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

COALESCE vs IS NOT NULL performance on checking empty string

Tags:

sql

teradata

Some articles I found on the internet compared ISNULL with COALESCE, so I think my question is a little different.

I'm wondering which is better in terms of performance?

SELECT * FROM mytable WHERE mycolumn IS NOT NULL AND mycolumn <> '';

Or

SELECT * FROM mytable WHERE COALESCE(mycolumn,'') <> '';

Other than performance, are there any other concerns I should consider when deciding?

EDIT:

I'm using Teradata.

like image 427
Russell Avatar asked Oct 14 '10 16:10

Russell


People also ask

Does coalesce work on empty string?

The Coalesce function evaluates its arguments in order and returns the first value that isn't blank or an empty string. Use this function to replace a blank value or empty string with a different value but leave non-blank and non-empty string values unchanged.

Does coalesce affect performance?

COALESCE could hurt your performance, but not compared to CASE , because it's actually just a CASE by another name. ISNULL could lead to better perf in some cases. But be aware of other differences between them, mainly the return type.

What is faster coalesce or Isnull?

Mladen aka spirit1 posted a speed test of COALESCE vs. ISNULL. Reported result: COALESCE is faster.

Which is better coalesce or Isnull?

advantage that COALESCE has over ISNULL is that it supports more than two inputs, whereas ISNULL supports only two. Another advantage of COALESCE is that it's a standard function (namely, defined by the ISO/ANSI SQL standards), whereas ISNULL is T-SQL–specific.


2 Answers

This version is slightly more sargable and allows an index to be (potentially) used

SELECT * FROM mytable WHERE mycolumn IS NOT NULL AND mycolumn <> '';

It can be simplified to

SELECT * FROM mytable WHERE mycolumn <> '';

The reason why I say "slightly" and "potentially" is that the non equality predicate may well mean you end up with a full scan anyway.

like image 168
Martin Smith Avatar answered Sep 28 '22 04:09

Martin Smith


You might also consider using the ANSI_NULL ON setting. This will implicitly filter out null values on a column where you issue a search argument. Doing this simplifies your query, i'm not sure if it makes it faster. Logically in theory it should though, since less filter arguments need to be evaluated and no functions are being used in where clause which should enable full index selectivity. As an example you could re-factor your query like this:

SET ANSI_NULLS ON;
SELECT * FROM mytable WHERE NOT mycolumn = '';

I hope this helps.

like image 43
James Avatar answered Sep 28 '22 05:09

James