Search code examples
sqlpostgresqlmaterialized-views

How can I add a sequence to the left of a materialized view in SQL?


I have a materialized view as follows:

|product_type|
--------------
shoes
clothing
electronics
..100's more

I'd like to create the view instead in a way that each product type has a corresponding ID. So the view should look as follows:

| ID | product_type|
--------------------
1   | shoes
2   | clothing
3   | electronics
100 | ..100's more

SQL used to create the view was:

select distinct(product_type) from items

Solution

  • You could use row_number():

    select row_number() over (order by product_type) as my_id
    

    However, if you need a unique number per product_type -- and one that is stable over time -- I would suggest using an identity column in a "product types" table.

    For your particular example, I would suggest:

    select row_number() over (order by product_type), product_type
    from items
    group by product_type;