Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

create a cte of manually entered values

I’d like to create a lookup table within my query using a cte e.g.

food, category
apple, fruit
carrot, vegetable
grape, fruit

How can I just type values directly in this way? Tried:

with
    
lookup_table as (
  select 
    'apple', 'carrot', 'grape' as fruits,
    'fruit', 'vegetable', 'fruit' as category
)

select * from lookup_table;

Gives:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

"?column?"  "?column?"  fruits  "?column?"  "?column?"  category
apple   carrot  grape   fruit   vegetable   fruit

How can I create a manual lookup directly in this way with 2 fields, fruit and category, as well as the 3 corresponding values for each?

>Solution :

One elegant way in Postgres is to use a VALUES clause.

WITH
lookup
AS
(
SELECT *
       FROM (VALUES ('apple',
                     'fruit'),
                    ...
                    ('grape',
                     'fruit')) AS v
                                  (fruit,
                                   category)
)
SELECT *
       FROM lookup;
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading