patternsqlMinor
Attributes from an hstore-column as separate columns in a view?
Viewed 0 times
columnscolumnhstoreviewseparateattributesfrom
Problem
Let's assume we have a table where it has two columns, one an ID and one an hstore column, which stores key/value pairs.
You could query that column as such:
Can you create a view for this table where the keys/values appear as columns in the view instead of all in the
Example: I have an hstore key where it might have the key of amenity. I want to create a view showing the the ID and the amenity values in a new view.
You could query that column as such:
SELECT name, attributes->'device' as device
FROM products
WHERE attributes->'edition'= 'ebook'Can you create a view for this table where the keys/values appear as columns in the view instead of all in the
hstore column?Example: I have an hstore key where it might have the key of amenity. I want to create a view showing the the ID and the amenity values in a new view.
Solution
Sure you can.
SQL Fiddle demo.
But only for a static set of columns. Dynamic output of all possible attributes in an
This later answer provides a completely dynamic solution (in two steps):
CREATE VIEW v_ebooks AS
SELECT products_id, attributes->'device' AS device
FROM products
WHERE attributes->'edition'= 'ebook';SQL Fiddle demo.
But only for a static set of columns. Dynamic output of all possible attributes in an
hstore column conflicts with the requirement that the return type has to be declared at creation time.This later answer provides a completely dynamic solution (in two steps):
- Dynamically convert hstore keys into columns for an unknown set of keys
Code Snippets
CREATE VIEW v_ebooks AS
SELECT products_id, attributes->'device' AS device
FROM products
WHERE attributes->'edition'= 'ebook';Context
StackExchange Database Administrators Q#58279, answer score: 3
Revisions (0)
No revisions yet.