]> granicus.if.org Git - postgresql/blob - doc/src/sgml/array.sgml
Random copy-editing.
[postgresql] / doc / src / sgml / array.sgml
1 <!-- $Header: /cvsroot/pgsql/doc/src/sgml/array.sgml,v 1.33 2003/11/04 09:55:38 petere Exp $ -->
2
3 <sect1 id="arrays">
4  <title>Arrays</title>
5
6  <indexterm>
7   <primary>array</primary>
8  </indexterm>
9
10  <para>
11   <productname>PostgreSQL</productname> allows columns of a table to be
12   defined as variable-length multidimensional arrays. Arrays of any
13   built-in type or user-defined type can be created.
14  </para>
15
16  <sect2>
17   <title>Declaration of Array Types</title>
18
19  <para>
20   To illustrate the use of array types, we create this table:
21 <programlisting>
22 CREATE TABLE sal_emp (
23     name            text,
24     pay_by_quarter  integer[],
25     schedule        text[][]
26 );
27 </programlisting>
28   As shown, an array data type is named by appending square brackets
29   (<literal>[]</>) to the data type name of the array elements.  The
30   above command will create a table named
31   <structname>sal_emp</structname> with a column of type
32   <type>text</type> (<structfield>name</structfield>), a
33   one-dimensional array of type <type>integer</type>
34   (<structfield>pay_by_quarter</structfield>), which represents the
35   employee's salary by quarter, and a two-dimensional array of
36   <type>text</type> (<structfield>schedule</structfield>), which
37   represents the employee's weekly schedule.
38  </para>
39
40  <para>
41   The syntax for <command>CREATE TABLE</command> allows the exact size of
42   arrays to be specified, for example:
43
44 <programlisting>
45 CREATE TABLE tictactoe (
46     squares   integer[3][3]
47 );
48 </programlisting>
49
50   However, the current implementation does not enforce the array size
51   limits --- the behavior is the same as for arrays of unspecified
52   length.
53  </para>
54
55  <para>
56   Actually, the current implementation does not enforce the declared
57   number of dimensions either.  Arrays of a particular element type are
58   all considered to be of the same type, regardless of size or number
59   of dimensions.  So, declaring number of dimensions or sizes in
60   <command>CREATE TABLE</command> is simply documentation, it does not
61   affect runtime behavior.
62  </para>
63
64  <para>
65   An alternative, SQL99-standard syntax may be used for one-dimensional arrays.
66   <structfield>pay_by_quarter</structfield> could have been defined as:
67 <programlisting>
68     pay_by_quarter  integer ARRAY[4],
69 </programlisting>
70   This syntax requires an integer constant to denote the array size.
71   As before, however, <productname>PostgreSQL</> does not enforce the
72   size restriction.
73  </para>
74  </sect2>
75
76  <sect2>
77   <title>Array Value Input</title>
78
79   <indexterm>
80    <primary>array</primary>
81    <secondary>constant</secondary>
82   </indexterm>
83
84   <para>
85    To write an array value as a literal constant, enclose the element
86    values within curly braces and separate them by commas.  (If you
87    know C, this is not unlike the C syntax for initializing
88    structures.)  You may put double quotes around any element value,
89    and must do so if it contains commas or curly braces.  (More
90    details appear below.)  Thus, the general format of an array
91    constant is the following:
92 <synopsis>
93 '{ <replaceable>val1</replaceable> <replaceable>delim</replaceable> <replaceable>val2</replaceable> <replaceable>delim</replaceable> ... }'
94 </synopsis>
95    where <replaceable>delim</replaceable> is the delimiter character
96    for the type, as recorded in its <literal>pg_type</literal> entry.
97    (For all built-in types, this is the comma character
98    <quote><literal>,</literal></>.)  Each
99    <replaceable>val</replaceable> is either a constant of the array
100    element type, or a subarray.  An example of an array constant is
101 <programlisting>
102 '{{1,2,3},{4,5,6},{7,8,9}}'
103 </programlisting>
104    This constant is a two-dimensional, 3-by-3 array consisting of
105    three subarrays of integers.
106   </para>
107
108   <para>
109    (These kinds of array constants are actually only a special case of
110    the generic type constants discussed in <xref
111    linkend="sql-syntax-constants-generic">.  The constant is initially
112    treated as a string and passed to the array input conversion
113    routine.  An explicit type specification might be necessary.)
114   </para>
115
116   <para>
117    Now we can show some <command>INSERT</command> statements.
118
119 <programlisting>
120 INSERT INTO sal_emp
121     VALUES ('Bill',
122     '{10000, 10000, 10000, 10000}',
123     '{{"meeting", "lunch"}, {}}');
124
125 INSERT INTO sal_emp
126     VALUES ('Carol',
127     '{20000, 25000, 25000, 25000}',
128     '{{"talk", "consult"}, {"meeting"}}');
129 </programlisting>
130   </para>
131
132   <para>
133    A limitation of the present array implementation is that individual
134    elements of an array cannot be SQL null values.  The entire array
135    can be set to null, but you can't have an array with some elements
136    null and some not.
137   </para>
138
139  <para>
140   This can lead to surprising results. For example, the result of the
141   previous two inserts looks like this:
142 <programlisting>
143 SELECT * FROM sal_emp;
144  name  |      pay_by_quarter       |      schedule
145 -------+---------------------------+--------------------
146  Bill  | {10000,10000,10000,10000} | {{meeting},{""}}
147  Carol | {20000,25000,25000,25000} | {{talk},{meeting}}
148 (2 rows)
149 </programlisting>
150   Because the <literal>[2][2]</literal> element of
151   <structfield>schedule</structfield> is missing in each of the
152   <command>INSERT</command> statements, the <literal>[1][2]</literal>
153   element is discarded.
154  </para>
155
156  <note>
157   <para>
158    Fixing this is on the to-do list.
159   </para>
160  </note>
161
162  <para>
163   The <literal>ARRAY</literal> expression syntax may also be used:
164 <programlisting>
165 INSERT INTO sal_emp
166     VALUES ('Bill',
167     ARRAY[10000, 10000, 10000, 10000],
168     ARRAY[['meeting', 'lunch'], ['','']]);
169
170 INSERT INTO sal_emp
171     VALUES ('Carol',
172     ARRAY[20000, 25000, 25000, 25000],
173     ARRAY[['talk', 'consult'], ['meeting', '']]);
174 SELECT * FROM sal_emp;
175  name  |      pay_by_quarter       |           schedule
176 -------+---------------------------+-------------------------------
177  Bill  | {10000,10000,10000,10000} | {{meeting,lunch},{"",""}}
178  Carol | {20000,25000,25000,25000} | {{talk,consult},{meeting,""}}
179 (2 rows)
180 </programlisting>
181   Note that with this syntax, multidimensional arrays must have matching
182   extents for each dimension. A mismatch causes an error report, rather than
183   silently discarding values as in the previous case.
184   For example:
185 <programlisting>
186 INSERT INTO sal_emp
187     VALUES ('Carol',
188     ARRAY[20000, 25000, 25000, 25000],
189     ARRAY[['talk', 'consult'], ['meeting']]);
190 ERROR:  multidimensional arrays must have array expressions with matching dimensions
191 </programlisting>
192   Also notice that the array elements are ordinary SQL constants or
193   expressions; for instance, string literals are single quoted, instead of
194   double quoted as they would be in an array literal.  The <literal>ARRAY</>
195   expression syntax is discussed in more detail in <xref
196   linkend="sql-syntax-array-constructors">.
197  </para>
198  </sect2>
199
200  <sect2>
201   <title>Accessing Arrays</title>
202
203  <para>
204   Now, we can run some queries on the table.
205   First, we show how to access a single element of an array at a time.
206   This query retrieves the names of the employees whose pay changed in
207   the second quarter:
208      
209 <programlisting>
210 SELECT name FROM sal_emp WHERE pay_by_quarter[1] &lt;&gt; pay_by_quarter[2];
211
212  name
213 -------
214  Carol
215 (1 row)
216 </programlisting>
217
218   The array subscript numbers are written within square brackets.
219   By default <productname>PostgreSQL</productname> uses the
220   one-based numbering convention for arrays, that is,
221   an array of <replaceable>n</> elements starts with <literal>array[1]</literal> and
222   ends with <literal>array[<replaceable>n</>]</literal>.
223  </para>
224
225  <para>
226   This query retrieves the third quarter pay of all employees:
227      
228 <programlisting>
229 SELECT pay_by_quarter[3] FROM sal_emp;
230
231  pay_by_quarter
232 ----------------
233           10000
234           25000
235 (2 rows)
236 </programlisting>
237  </para>
238
239  <para>
240   We can also access arbitrary rectangular slices of an array, or
241   subarrays.  An array slice is denoted by writing
242   <literal><replaceable>lower-bound</replaceable>:<replaceable>upper-bound</replaceable></literal>
243   for one or more array dimensions.  For example, this query retrieves the first
244   item on Bill's schedule for the first two days of the week:
245      
246 <programlisting>
247 SELECT schedule[1:2][1:1] FROM sal_emp WHERE name = 'Bill';
248
249       schedule
250 --------------------
251  {{meeting},{""}}
252 (1 row)
253 </programlisting>
254
255   We could also have written
256
257 <programlisting>
258 SELECT schedule[1:2][1] FROM sal_emp WHERE name = 'Bill';
259 </programlisting>
260
261   with the same result.  An array subscripting operation is always taken to
262   represent an array slice if any of the subscripts are written in the form
263   <literal><replaceable>lower</replaceable>:<replaceable>upper</replaceable></literal>.
264   A lower bound of 1 is assumed for any subscript where only one value
265   is specified, as in this example:
266 <programlisting>
267 SELECT schedule[1:2][2] FROM sal_emp WHERE name = 'Bill';
268          schedule
269 ---------------------------
270  {{meeting,lunch},{"",""}}
271 (1 row)
272 </programlisting>
273  </para>
274
275  <para>
276   The current dimensions of any array value can be retrieved with the
277   <function>array_dims</function> function:
278
279 <programlisting>
280 SELECT array_dims(schedule) FROM sal_emp WHERE name = 'Carol';
281
282  array_dims
283 ------------
284  [1:2][1:1]
285 (1 row)
286 </programlisting>
287
288   <function>array_dims</function> produces a <type>text</type> result,
289   which is convenient for people to read but perhaps not so convenient
290   for programs.  Dimensions can also be retrieved with
291   <function>array_upper</function> and <function>array_lower</function>,
292   which return the upper and lower bound of a
293   specified array dimension, respectively.
294
295 <programlisting>
296 SELECT array_upper(schedule, 1) FROM sal_emp WHERE name = 'Carol';
297
298  array_upper
299 -------------
300            2
301 (1 row)
302 </programlisting>
303  </para>
304  </sect2>
305
306  <sect2>
307   <title>Modifying Arrays</title>
308
309  <para>
310   An array value can be replaced completely:
311
312 <programlisting>
313 UPDATE sal_emp SET pay_by_quarter = '{25000,25000,27000,27000}'
314     WHERE name = 'Carol';
315 </programlisting>
316
317   or using the <literal>ARRAY</literal> expression syntax:
318
319 <programlisting>
320 UPDATE sal_emp SET pay_by_quarter = ARRAY[25000,25000,27000,27000]
321     WHERE name = 'Carol';
322 </programlisting>
323
324   An array may also be updated at a single element:
325
326 <programlisting>
327 UPDATE sal_emp SET pay_by_quarter[4] = 15000
328     WHERE name = 'Bill';
329 </programListing>
330
331   or updated in a slice:
332
333 <programlisting>
334 UPDATE sal_emp SET pay_by_quarter[1:2] = '{27000,27000}'
335     WHERE name = 'Carol';
336 </programlisting>
337
338  </para>
339
340  <para>
341   A stored array value can be enlarged by assigning to an element adjacent to
342   those already present, or by assigning to a slice that is adjacent
343   to or overlaps the data already present.  For example, if array
344   <literal>myarray</> currently has 4 elements, it will have five
345   elements after an update that assigns to <literal>myarray[5]</>.
346   Currently, enlargement in this fashion is only allowed for one-dimensional
347   arrays, not multidimensional arrays.
348  </para>
349
350  <para>
351   Array slice assignment allows creation of arrays that do not use one-based
352   subscripts.  For example one might assign to <literal>myarray[-2:7]</> to
353   create an array with subscript values running from -2 to 7.
354  </para>
355
356  <para>
357   New array values can also be constructed by using the concatenation operator,
358   <literal>||</literal>.
359 <programlisting>
360 SELECT ARRAY[1,2] || ARRAY[3,4];
361  ?column?
362 -----------
363  {1,2,3,4}
364 (1 row)
365
366 SELECT ARRAY[5,6] || ARRAY[[1,2],[3,4]];
367       ?column?
368 ---------------------
369  {{5,6},{1,2},{3,4}}
370 (1 row)
371 </programlisting>
372  </para>
373
374  <para>
375   The concatenation operator allows a single element to be pushed on to the
376   beginning or end of a one-dimensional array. It also accepts two
377   <replaceable>N</>-dimensional arrays, or an <replaceable>N</>-dimensional
378   and an <replaceable>N+1</>-dimensional array.
379  </para>
380
381  <para>
382   When a single element is pushed on to the beginning of a one-dimensional
383   array, the result is an array with a lower bound subscript equal to
384   the right-hand operand's lower bound subscript, minus one. When a single
385   element is pushed on to the end of a one-dimensional array, the result is
386   an array retaining the lower bound of the left-hand operand. For example:
387 <programlisting>
388 SELECT array_dims(1 || ARRAY[2,3]);
389  array_dims
390 ------------
391  [0:2]
392 (1 row)
393
394 SELECT array_dims(ARRAY[1,2] || 3);
395  array_dims
396 ------------
397  [1:3]
398 (1 row)
399 </programlisting>
400  </para>
401
402  <para>
403   When two arrays with an equal number of dimensions are concatenated, the
404   result retains the lower bound subscript of the left-hand operand's outer
405   dimension. The result is an array comprising every element of the left-hand
406   operand followed by every element of the right-hand operand. For example:
407 <programlisting>
408 SELECT array_dims(ARRAY[1,2] || ARRAY[3,4,5]);
409  array_dims
410 ------------
411  [1:5]
412 (1 row)
413
414 SELECT array_dims(ARRAY[[1,2],[3,4]] || ARRAY[[5,6],[7,8],[9,0]]);
415  array_dims
416 ------------
417  [1:5][1:2]
418 (1 row)
419 </programlisting>
420  </para>
421
422  <para>
423   When an <replaceable>N</>-dimensional array is pushed on to the beginning
424   or end of an <replaceable>N+1</>-dimensional array, the result is
425   analogous to the element-array case above. Each <replaceable>N</>-dimensional
426   sub-array is essentially an element of the <replaceable>N+1</>-dimensional
427   array's outer dimension. For example:
428 <programlisting>
429 SELECT array_dims(ARRAY[1,2] || ARRAY[[3,4],[5,6]]);
430  array_dims
431 ------------
432  [0:2][1:2]
433 (1 row)
434 </programlisting>
435  </para>
436
437  <para>
438   An array can also be constructed by using the functions
439   <function>array_prepend</function>, <function>array_append</function>,
440   or <function>array_cat</function>. The first two only support one-dimensional
441   arrays, but <function>array_cat</function> supports multidimensional arrays.
442
443   Note that the concatenation operator discussed above is preferred over
444   direct use of these functions. In fact, the functions are primarily for use
445   in implementing the concatenation operator. However, they may be directly
446   useful in the creation of user-defined aggregates. Some examples:
447
448 <programlisting>
449 SELECT array_prepend(1, ARRAY[2,3]);
450  array_prepend
451 ---------------
452  {1,2,3}
453 (1 row)
454
455 SELECT array_append(ARRAY[1,2], 3);
456  array_append
457 --------------
458  {1,2,3}
459 (1 row)
460
461 SELECT array_cat(ARRAY[1,2], ARRAY[3,4]);
462  array_cat
463 -----------
464  {1,2,3,4}
465 (1 row)
466
467 SELECT array_cat(ARRAY[[1,2],[3,4]], ARRAY[5,6]);
468       array_cat
469 ---------------------
470  {{1,2},{3,4},{5,6}}
471 (1 row)
472
473 SELECT array_cat(ARRAY[5,6], ARRAY[[1,2],[3,4]]);
474       array_cat
475 ---------------------
476  {{5,6},{1,2},{3,4}}
477 </programlisting>
478  </para>
479  </sect2>
480
481  <sect2>
482   <title>Searching in Arrays</title>
483
484  <para>
485   To search for a value in an array, you must check each value of the
486   array. This can be done by hand, if you know the size of the array.
487   For example:
488
489 <programlisting>
490 SELECT * FROM sal_emp WHERE pay_by_quarter[1] = 10000 OR
491                             pay_by_quarter[2] = 10000 OR
492                             pay_by_quarter[3] = 10000 OR
493                             pay_by_quarter[4] = 10000;
494 </programlisting>
495
496   However, this quickly becomes tedious for large arrays, and is not
497   helpful if the size of the array is uncertain. An alternative method is
498   described in <xref linkend="functions-comparisons">. The above
499   query could be replaced by:
500
501 <programlisting>
502 SELECT * FROM sal_emp WHERE 10000 = ANY (pay_by_quarter);
503 </programlisting>
504
505   In addition, you could find rows where the array had all values
506   equal to 10000 with:
507
508 <programlisting>
509 SELECT * FROM sal_emp WHERE 10000 = ALL (pay_by_quarter);
510 </programlisting>
511
512  </para>
513
514  <tip>
515   <para>
516    Arrays are not sets; searching for specific array elements
517    may be a sign of database misdesign.  Consider
518    using a separate table with a row for each item that would be an
519    array element.  This will be easier to search, and is likely to
520    scale up better to large numbers of elements.
521   </para>
522  </tip>
523  </sect2>
524
525  <sect2>
526   <title>Array Input and Output Syntax</title>
527
528   <para>
529    The external text representation of an array value consists of items that
530    are interpreted according to the I/O conversion rules for the array's
531    element type, plus decoration that indicates the array structure.
532    The decoration consists of curly braces (<literal>{</> and <literal>}</>)
533    around the array value plus delimiter characters between adjacent items.
534    The delimiter character is usually a comma (<literal>,</>) but can be
535    something else: it is determined by the <literal>typdelim</> setting
536    for the array's element type.  (Among the standard data types provided
537    in the <productname>PostgreSQL</productname> distribution, type
538    <literal>box</> uses a semicolon (<literal>;</>) but all the others
539    use comma.)  In a multidimensional array, each dimension (row, plane,
540    cube, etc.) gets its own level of curly braces, and delimiters
541    must be written between adjacent curly-braced entities of the same level.
542    You may write whitespace before a left brace, after a right
543    brace, or before any individual item string.  Whitespace after an item
544    is not ignored, however: after skipping leading whitespace, everything
545    up to the next right brace or delimiter is taken as the item value.
546   </para>
547
548   <para>
549    As shown previously, when writing an array value you may write double
550    quotes around any individual array
551    element.  You <emphasis>must</> do so if the element value would otherwise
552    confuse the array-value parser.  For example, elements containing curly
553    braces, commas (or whatever the delimiter character is), double quotes,
554    backslashes, or leading white space must be double-quoted.  To put a double
555    quote or backslash in a quoted array element value, precede it with a
556    backslash.
557    Alternatively, you can use backslash-escaping to protect all data characters
558    that would otherwise be taken as array syntax or ignorable white space.
559   </para>
560
561   <para>
562    The array output routine will put double quotes around element values
563    if they are empty strings or contain curly braces, delimiter characters,
564    double quotes, backslashes, or white space.  Double quotes and backslashes
565    embedded in element values will be backslash-escaped.  For numeric
566    data types it is safe to assume that double quotes will never appear, but
567    for textual data types one should be prepared to cope with either presence
568    or absence of quotes.  (This is a change in behavior from pre-7.2
569    <productname>PostgreSQL</productname> releases.)
570   </para>
571
572  <note>
573   <para>
574    Remember that what you write in an SQL command will first be interpreted
575    as a string literal, and then as an array.  This doubles the number of
576    backslashes you need.  For example, to insert a <type>text</> array
577    value containing a backslash and a double quote, you'd need to write
578 <programlisting>
579 INSERT ... VALUES ('{"\\\\","\\""}');
580 </programlisting>
581    The string-literal processor removes one level of backslashes, so that
582    what arrives at the array-value parser looks like <literal>{"\\","\""}</>.
583    In turn, the strings fed to the <type>text</> data type's input routine
584    become <literal>\</> and <literal>"</> respectively.  (If we were working
585    with a data type whose input routine also treated backslashes specially,
586    <type>bytea</> for example, we might need as many as eight backslashes
587    in the command to get one backslash into the stored array element.)
588   </para>
589  </note>
590
591  <tip>
592   <para>
593    The <literal>ARRAY</> constructor syntax is often easier to work with
594    than the array-literal syntax when writing array values in SQL commands.
595    In <literal>ARRAY</>, individual element values are written the same way
596    they would be written when not members of an array.
597   </para>
598  </tip>
599  </sect2>
600
601 </sect1>