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

天大地大妈咪最大 提交于 2019-12-04 03:36:31

问题


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?


回答1:


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)


来源:https://stackoverflow.com/questions/22640981/sql-case-does-the-order-of-the-when-statements-matter

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!