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