![]() ![]()
Thursday, October 27. 2011PostgreSQL Array: The ANY and Contains trickPrinter FriendlyRecommended Books: PostgreSQL 9.0 SQL Reference 1A PostgreSQL 9.0 SQL Reference 1B
Trackbacks
Trackback specific URI for this entry
No Trackbacks
Recommended Books: PostgreSQL 9.0 SQL Reference 1A PostgreSQL 9.0 SQL Reference 1B
Comments
Display comments as
(Linear | Threaded)
Y one cannot select/copy the SQL snippets on your site?
You made a copy/paste mistake withh the string_agg ORDER BY sample in the WHERE clause.
Is ANY over an array a better (in terms of performance, memory use, etc) option than using IN (1,2,3,...) or IN ('str1','str2','str3',...)?
You forgot to put the WHERE in the select, and maybe exists an error in the statment
SELECT string_agg(product_name, ',' ORDER BY product_name) As prod_list FROM products product_id = ANY('{1,4,5}'::int[]) ), ',') As prod_list; and so you see there is an error in the select, because correcting the WHERE and then running it returns the following message ERROR: syntax error at or near ")" LINE 4: product_id = ANY('{1,4,5}'::int[]) ), ',') As prod_list;
string_agg(col, ', ', ORDER BY col) is just syntactic sugar for array_to_string(array_sort(array_agg(col), ',')) which has been available since PostgreSQL 8.4
Hugo,
I see a WHERE in my example, or maybe you were referring to the previous version that Vasco commented on as well.
Dane,
Not sure off-hand. I suspect they are equivalent, but that PostgreSQL internally prefers to work with arrays. Have you ever looked at a table constraint you have written with an IN clause. Every time I look at them, I see that Postgres has rewritten it to use an ARRAY instead of my IN list. Like for example I had a NOT IN('a', 'b','c') constraint I wrote and when I looked back it was rewritten to: use a not ALL (ARRAY[...])
string_agg is not syntactic sugar - you can check it, it's faster - because it has different implementation.
array_sort is not in build function - but you can find a few simple implementations on net. |
QuicksearchCalendarCategoriesArchivesBlog AdministrationEntry's LinksShow tagged entriesRemote RSS/OPML-Blogroll FeedNo RSS/OPML feed selected
|