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