Subject: Queries over variable sized arrays

From: Aaron Roydhouse <[email-masked]>
Date: Thu, 12 May 1994 14:54:01 +1200

Variable sized arrays as implemented in Postgres 4.2 are good and
wonderful things for storage and retrieval, especially with the handy
sub-array query syntax.

However, I am finding it quite challenging to construct queries over
the contents of arrays. Consider the following simple example

----------------------------------------------------------------------
* create things (items = int4[])\g

Query sent to backend is "create things (items = int4[])"
CREATE
Go 
* append things (items = "{7,4,2}")\g

Query sent to backend is "append things (items = "{7,4,2}")"
APPEND 657000
Go 
* append things (items = "{3,9}")\g

Query sent to backend is "append things (items = "{3,9}")"
APPEND 657001
Go 
* append things (items = "{9,2,3,4}")\g

Query sent to backend is "append things (items = "{9,2,3,4}")"
APPEND 657002
Go 
* retrieve (things.all)\g

Query sent to backend is "retrieve (things.all)"
---------------
| items       |
---------------
| {7,4,2}     |
---------------
| {3,9}       |
---------------
| {9,2,3,4}   |
---------------
----------------------------------------------------------------------

Suppose I want to find instances with items greater than seven. I can
issue the following query.

----------------------------------------------------------------------
* retrieve (t.all) from t in things 
where t.items[1] > 7 
or t.items[2] > 7 
or t.items[3] > 7 
or t.items[4] > 7\g

Query sent to backend is "retrieve (t.all) from t in things where t.items[1] > 7 or t.items[2] > 7 or t.items[3] > 7 or t.items[4] > 7"
---------------
| items       |
---------------
| {3,9}       |
---------------
| {9,2,3,4}   |
---------------
----------------------------------------------------------------------

But this required as many conditions as the maximum number of items in
any array, and required me to know the maximum number of items in any
array (how can I find that out?).

I really want to map a test over the array, but I can't see how this
is possible. I guess I could write an operator in C that manually
conducts a test over the array. Sometimes, though, I'd want to issue
sub-queries for items in the array. Is there an (easy or documented or
example) method to issue internal sub-queries from inside postgres
functions defined in C? Has anyone done something similar?

Well, I'm just full of questions today. Thanks for your help Paul,
even if many of the answers have negative :-)

Aaron.

===============================================================================
    To add/remove yourself from the POSTGRES mailing list: send mail with 
    the subject line ADD or DEL to "[email-masked]"

    If this fails, send mail to "[email-masked]" and
    a human will deal with it.  DO NOT post to the "postgres" mailing list.
===============================================================================