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