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