sehcheese
sehcheese

Reputation: 175

SQL CASE: Does the order of the WHEN statements matter?

I am using PHP to generate a SQL query that needs to be ordered in a custom way. I am generating a CASE block with a number of WHEN statements that assign a number ranking. The WHEN statements that are included are contingent on how much information I have available for querying. For example, if I have a phone available, I will generate three WHEN statements:

WHEN phone = '(202) 555-5555' AND last_name = 'Smith' and first_name = 'John' THEN 1

WHEN phone = '(202) 555-5555' AND last_name = 'Smith' THEN 2

WHEN phone = '(202) 555-5555' THEN 3

So I am ranking based on how close the match is, and I am valuing the parameters the same (a match on phone, first name, and last name should be ranked on the same tier as a match on address, first name and last name). However, after generating these statements for multiple pieces of information (phone, address, etc), my WHEN statements will be all out of order; the THEN 1 terminated clauses will be separated from each other, same for THEN 2 and so on. I could put them in order, but that would make my PHP more verbose and ugly.

TL;DR?

So the short question is: Does the order of the WHEN statements in a CASE statement matter? Does SQL (I'm using Oracle) go with the first match or does it evaluate all of the possibilities and assign the highest ranking?

Upvotes: 8

Views: 10533

Answers (1)

Gordon Linoff
Gordon Linoff

Reputation: 1270463

Yes, the order of the case statements does matter. The first matching row will be the one returned.

So, this statement:

(CASE WHEN phone = '(202) 555-5555' AND last_name = 'Smith' and first_name = 'John' THEN 1
      WHEN phone = '(202) 555-5555' AND last_name = 'Smith' THEN 2
      WHEN phone = '(202) 555-5555' THEN 3
 END)

Could return 1, 2, or 3 (or NULL). The following will always return 3 (or NULL) because the last two conditions will never be processed:

(CASE WHEN phone = '(202) 555-5555' THEN 3
      WHEN phone = '(202) 555-5555' AND last_name = 'Smith' THEN 2
      WHEN phone = '(202) 555-5555' AND last_name = 'Smith' and first_name = 'John' THEN 1
 END)

Upvotes: 14

Related Questions