# How to use a CTE instead of complicated CASE expressions
In the past I’ve had to write queries to convert data in a table into user-friendly display text. One way to do this is with CASE expressions. For example, let’s say you have a table with a column being a country code, and you want to add the country name in the final result.
1 | sqlite> SELECT code FROM data; |
One approach is to use a CASE expression in your query like this:
1 | sqlite> SELECT code, |
The downside is that it’s harder to read, and if you need to do something similar elsewhere in the query, you’ll have to repeat the expression.
An alternative is to use a CTE like this:
1 | sqlite> WITH countries (code, name) AS ( |
Now the countries
CTE becomes a lookup table that you can reference several times in your queries.
This approach works with SQLite and PostgreSQL.
Comments
In Oracle can use as below.
1 | WITH countries(code, name) AS ( |