dpesios
dpesios

Reputation: 47

Create database View in PostgreSQL and change record values simultaneously

To cut a long story short, is it possible to create a database view in postgres and at the same time change the record values for a specific column ?

CREATE VIEW ViewOfCoupons AS
SELECT *
FROM Coupons
WHERE title = 'Category_1' OR title = 'Category_2';

I want to rename the records contained in the view to have different title other than 'Category_1' or 'Category_2', lets say 'Category_3'. In fact, as I mention in the commect, 'Category_3' is a supercategory involving the other two. So I only want the rows having these values. Is this possible with CASE statement ?

Upvotes: 0

Views: 79

Answers (1)

user330315
user330315

Reputation:

CREATE VIEW ViewOfCoupons AS
SELECT case title
         when 'Category_1' then 'Brand new category' 
         when 'Category_2' then 'The other category'
         else title
       end as title, 
       ... other columns ...
FROM Coupons
WHERE title in ('Category_1', 'Category_2');

Strictly speaking the else title is not necessary because the WHERE clause makes sure that no other values will appear in that column, but I add this nevertheless to be prepared for future changes, e.g. if someone changes the where clause but forgets to change the case as well.

Upvotes: 1

Related Questions