2

Suppose I have the following events table:

 Column |   Type  |
--------+---------+
 id     | integer |
 type   | integer |

The event type can be any user provided number and there is no relation on any other table in the system associated with this type.

The request came in that I generate a report and I need to match the type to a user provided string.

The user may provide the following:

1 = "Created event" 
2 = "Deleted event" 
3 = "Updated event"

This is overly simplified, but you get the idea.

Now I need to generate the report that includes the event table but instead of the type the matching string should be used.

I read the manual on the string functions and found the replace function which only solves the problem partially - I can only replace on type:

select replace(type::text, '3', 'Updated event') from events;

This will return all the events rows and only the rows that have the type 3 will have the correct string, the others will have the integer.

How can I leverage that to be able to match the type to a user string in one select?

2 Answers 2

10

You need a case expression:

select case type
          when 1 then 'Created event'
          when 2 then 'Deleted event'
          when 3 then 'Updated even'
          else 'Unknown Type'
       end as type_name
from events;

Another option (maybe a bit more flexible) is to create the lookup table "on-the-fly":

with type_names (id, type_name) as (
   values 
      (1, 'Created event'),
      (2, 'Deleted event'),
      (3, 'Updated event')
)
select e.id, coalesce(tn.type_name, 'Unknown type') as type_name
from events e 
  left join type_names tn on t.id = e.type;

The outer join is necessary in case there are events that have a different type number then expected.

Sign up to request clarification or add additional context in comments.

2 Comments

The "on-the-fly" table is exactly what I was looking for, I just didn't know it was possible and didn't know how to put my google query together to find such options. Thanks!
You can also put that "on-the-fly" table into a view to simplify the queries using it
2

The case conditional will do what you want:

SELECT CASE 
       WHEN type=1 THEN 'Created event'
       WHEN type=2 THEN 'Deleted event'
       ELSE 'Updated event'
       END
FROM events;

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.