views:

198

answers:

3

I'm wondering if using a CASE statement in SQLite (or other SQL engines) to replace data is not advised. For example lets say I have a query.

SELECT Users, 
                CASE WHEN Active = 0 THEN 'Inactive'
                        WHEN Active = 1 THEN 'Active'
                        WHEN Active = 2 THEN 'Processing'
                        ELSE 'ERROR' AS Active
FROM UsersTable;

When is it better to create a reference table and perform a JOIN. In this case I would create a Table 'ActiveStatesTable' with ActiveID, ActiveDescription and perform the JOIN.

+2  A: 

The CASE statement is preferred syntax:

  • It's ANSI (92?), so it's supported on MySQL, Oracle, SQL Server, Postgres... unlike database vendor specific IF syntax
  • It supports short ciruiting - the rest of the evaluation is not performed once criteria matches
OMG Ponies
Should the Size of the CASE statement be considered? What if a column 'Description ID' was in the table, and there are 100's of descriptions to map?
galford13x
+2  A: 

Doing the separate table and JOIN is definitely the cleaner way to write this code. What happens, for example, if you want to write another query with the same mappings? You'd have to copy the CASE statement into the new query, and copy duplication is bad. What happens if you need to add a new Active state?

Performance-wise, both the JOIN and the CASE should be fairly cheap. CASE might be slightly more performant because of short-circuiting of evaluation and the few cases, but JOIN is, in my opinion, the cleaner and more flexible and more SQL-ey solution.

RarrRarrRarr
This is true, but maintaining the CASE wont be too difficult as I could just create a VIEW with that has the CASE and then maintain the VIEW.
galford13x
+1  A: 

CASE should be much cheaper as it should not involve any I/O, but for small tables JOINs are not that expensive either (but do test it).

The question is if you will need to maintain this CASE in several queries and will you need to establish any referential integrity on it.

Unreason
This is true, but maintaining the CASE wont be too difficult as I could just create a VIEW with that has the CASE and then maintain the VIEW.
galford13x
It could be easy for small number of cases and as an exception, but it still should be considered. Disregarding the integrity, maintaining it in a view is not the same as maintaining it in a table (you can't update translation based on a query).
Unreason
That makes sense. I'll add a table and perform some benchmarks. I'll post results when I'm finished.
galford13x