Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL CASE vs multiplication

Tags:

sql

sql-server

I have a query like this:

SELECT
  CASE WHEN IsAdd = 1
  THEN
    Base + Extra
  ELSE
    Base
  END
FROM MyTable

Would using multiplication to eliminate the CASE statement have better performance?

SELECT
    Base + Extra * ISNULL(IsAdd, 0)
FROM MyTable
like image 778
user868538 Avatar asked Jun 16 '26 21:06

user868538


1 Answers

You don't need to worry about such optimizations.

The expense of a SQL query is usually around reading the data, extracting the records, and returning the results. Simple operations such as multiplication or comparisons are minor. Some operations can get expensive (such as working with user-defined functions, long strings, and so on). But multiplication would not generally be one of them.

So, focus on what best represents the work you want to accomplish. Your two queries do not express exactly the same logic. They may happen to be the same if IsAdd only takes on the values of 0, 1, and NULL. But you should use the version that best expresses your intent.

By the way, I prefer COALESCE() to ISNULL() because it is standard.

like image 131
Gordon Linoff Avatar answered Jun 19 '26 12:06

Gordon Linoff