0

I really want to know about there would be any performance impact while comparing table column with the same table column like

select id, name from person
where name = coalesce(NULLIF(:application_parameter,''),name)

So in above example if I don't recieve parameter from my application(if it's null or blank) then query will be

select id, name from person
where name = name

This is just a sample, but in my application it's really a complex query. I know there are some alternates to this like create dynamic query(append where condition only if you want it).

But I am only interested to know what will be the performance impact if I compare column with the same column.

4
  • In SQL, there is no "performance" impact when you compare a column to a column. Performance penalty comes when the database has to obtain the data that it has to compare with. If you compare a number 1 to a million records, it's really trivial to perform that comparison. What's not trivial is to find that data and retrieve it. Everyone who answered so far seem to be answering about the performance impact of obtaining data.
    – N.B.
    Aug 18, 2015 at 14:48
  • 2
    In the latest version of mysql, the optimizer rewrites "where col1=col1" as "where 1" (at least in the one case i tried), so it looks like no additional cost
    – AdrianBR
    Aug 18, 2015 at 14:48
  • Just for interest (and not having a mysql handy) what happens if that col was a virtual column? Does the optimizer still remove the clause?
    – Andrew
    Aug 18, 2015 at 14:56
  • in my test it, on a simple select on 1 table(where date+0=date+0), it did. I would bet it will not be so smart in most other situations though.
    – AdrianBR
    Aug 18, 2015 at 15:31

2 Answers 2

1

Yes. This version:

where name = coalesce(NULLIF(:application_parameter,''),name)

will not take advantage of an index on name. The use of the function impedes index optimization.

It is hard to get queries to both take parameters and to use indexes. You can try:

where name = :application_parameter or :application_parameter is NULL

MySQL might optimize this correctly. Otherwise this might do the trick:

select id, name
from person
where :application_parameter is NULL
union all
select id, name
from person
where name = :application_parameter;
1

To see the performance impact in mysql you can look at the query after the optimizer had it. Do a

EXPLAIN EXTENDED SELECT aCol FROM aTable WHERE aCol = aCol;

This will generate a WARNING with the result of the optimizer. You can get it by

SHOW WARNINGS;

Here you will find:

SELECT aCol FROM aTable WHERE 1;

So the condition gets optimized away :-)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.