1 <?xml version="1.0" encoding="UTF-8" standalone="no"?>
2 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"><html xmlns="http://www.w3.org/1999/xhtml"><head><meta http-equiv="Content-Type" content="text/html; charset=UTF-8" /><title>8.16. Composite Types</title><link rel="stylesheet" type="text/css" href="stylesheet.css" /><link rev="made" href="pgsql-docs@lists.postgresql.org" /><meta name="generator" content="DocBook XSL Stylesheets Vsnapshot" /><link rel="prev" href="arrays.html" title="8.15. Arrays" /><link rel="next" href="rangetypes.html" title="8.17. Range Types" /></head><body id="docContent" class="container-fluid col-10"><div class="navheader"><table width="100%" summary="Navigation header"><tr><th colspan="5" align="center">8.16. Composite Types</th></tr><tr><td width="10%" align="left"><a accesskey="p" href="arrays.html" title="8.15. Arrays">Prev</a> </td><td width="10%" align="left"><a accesskey="u" href="datatype.html" title="Chapter 8. Data Types">Up</a></td><th width="60%" align="center">Chapter 8. Data Types</th><td width="10%" align="right"><a accesskey="h" href="index.html" title="PostgreSQL 18.0 Documentation">Home</a></td><td width="10%" align="right"> <a accesskey="n" href="rangetypes.html" title="8.17. Range Types">Next</a></td></tr></table><hr /></div><div class="sect1" id="ROWTYPES"><div class="titlepage"><div><div><h2 class="title" style="clear: both">8.16. Composite Types <a href="#ROWTYPES" class="id_link">#</a></h2></div></div></div><div class="toc"><dl class="toc"><dt><span class="sect2"><a href="rowtypes.html#ROWTYPES-DECLARING">8.16.1. Declaration of Composite Types</a></span></dt><dt><span class="sect2"><a href="rowtypes.html#ROWTYPES-CONSTRUCTING">8.16.2. Constructing Composite Values</a></span></dt><dt><span class="sect2"><a href="rowtypes.html#ROWTYPES-ACCESSING">8.16.3. Accessing Composite Types</a></span></dt><dt><span class="sect2"><a href="rowtypes.html#ROWTYPES-MODIFYING">8.16.4. Modifying Composite Types</a></span></dt><dt><span class="sect2"><a href="rowtypes.html#ROWTYPES-USAGE">8.16.5. Using Composite Types in Queries</a></span></dt><dt><span class="sect2"><a href="rowtypes.html#ROWTYPES-IO-SYNTAX">8.16.6. Composite Type Input and Output Syntax</a></span></dt></dl></div><a id="id-1.5.7.24.2" class="indexterm"></a><a id="id-1.5.7.24.3" class="indexterm"></a><p>
3 A <em class="firstterm">composite type</em> represents the structure of a row or record;
4 it is essentially just a list of field names and their data types.
5 <span class="productname">PostgreSQL</span> allows composite types to be
6 used in many of the same ways that simple types can be used. For example, a
7 column of a table can be declared to be of a composite type.
8 </p><div class="sect2" id="ROWTYPES-DECLARING"><div class="titlepage"><div><div><h3 class="title">8.16.1. Declaration of Composite Types <a href="#ROWTYPES-DECLARING" class="id_link">#</a></h3></div></div></div><p>
9 Here are two simple examples of defining composite types:
10 </p><pre class="programlisting">
11 CREATE TYPE complex AS (
16 CREATE TYPE inventory_item AS (
22 The syntax is comparable to <code class="command">CREATE TABLE</code>, except that only
23 field names and types can be specified; no constraints (such as <code class="literal">NOT
24 NULL</code>) can presently be included. Note that the <code class="literal">AS</code> keyword
25 is essential; without it, the system will think a different kind
26 of <code class="command">CREATE TYPE</code> command is meant, and you will get odd syntax
29 Having defined the types, we can use them to create tables:
31 </p><pre class="programlisting">
32 CREATE TABLE on_hand (
37 INSERT INTO on_hand VALUES (ROW('fuzzy dice', 42, 1.99), 1000);
42 </p><pre class="programlisting">
43 CREATE FUNCTION price_extension(inventory_item, integer) RETURNS numeric
44 AS 'SELECT $1.price * $2' LANGUAGE SQL;
46 SELECT price_extension(item, 10) FROM on_hand;
50 Whenever you create a table, a composite type is also automatically
51 created, with the same name as the table, to represent the table's
52 row type. For example, had we said:
53 </p><pre class="programlisting">
54 CREATE TABLE inventory_item (
56 supplier_id integer REFERENCES suppliers,
57 price numeric CHECK (price > 0)
60 then the same <code class="literal">inventory_item</code> composite type shown above would
62 byproduct, and could be used just as above. Note however an important
63 restriction of the current implementation: since no constraints are
64 associated with a composite type, the constraints shown in the table
65 definition <span class="emphasis"><em>do not apply</em></span> to values of the composite type
66 outside the table. (To work around this, create a
67 <a class="glossterm" href="glossary.html#GLOSSARY-DOMAIN"><em class="glossterm"><a class="glossterm" href="glossary.html#GLOSSARY-DOMAIN" title="Domain">domain</a></em></a> over the composite
68 type, and apply the desired constraints as <code class="literal">CHECK</code>
69 constraints of the domain.)
70 </p></div><div class="sect2" id="ROWTYPES-CONSTRUCTING"><div class="titlepage"><div><div><h3 class="title">8.16.2. Constructing Composite Values <a href="#ROWTYPES-CONSTRUCTING" class="id_link">#</a></h3></div></div></div><a id="id-1.5.7.24.6.2" class="indexterm"></a><p>
71 To write a composite value as a literal constant, enclose the field
72 values within parentheses and separate them by commas. You can put double
73 quotes around any field value, and must do so if it contains commas or
74 parentheses. (More details appear <a class="link" href="rowtypes.html#ROWTYPES-IO-SYNTAX" title="8.16.6. Composite Type Input and Output Syntax">below</a>.) Thus, the general format of
75 a composite constant is the following:
76 </p><pre class="synopsis">
77 '( <em class="replaceable"><code>val1</code></em> , <em class="replaceable"><code>val2</code></em> , ... )'
80 </p><pre class="programlisting">
81 '("fuzzy dice",42,1.99)'
83 which would be a valid value of the <code class="literal">inventory_item</code> type
84 defined above. To make a field be NULL, write no characters at all
85 in its position in the list. For example, this constant specifies
87 </p><pre class="programlisting">
90 If you want an empty string rather than NULL, write double quotes:
91 </p><pre class="programlisting">
94 Here the first field is a non-NULL empty string, the third is NULL.
96 (These constants are actually only a special case of
97 the generic type constants discussed in <a class="xref" href="sql-syntax-lexical.html#SQL-SYNTAX-CONSTANTS-GENERIC" title="4.1.2.7. Constants of Other Types">Section 4.1.2.7</a>. The constant is initially
98 treated as a string and passed to the composite-type input conversion
99 routine. An explicit type specification might be necessary to tell
100 which type to convert the constant to.)
102 The <code class="literal">ROW</code> expression syntax can also be used to
103 construct composite values. In most cases this is considerably
104 simpler to use than the string-literal syntax since you don't have
105 to worry about multiple layers of quoting. We already used this
107 </p><pre class="programlisting">
108 ROW('fuzzy dice', 42, 1.99)
111 The ROW keyword is actually optional as long as you have more than one
112 field in the expression, so these can be simplified to:
113 </p><pre class="programlisting">
114 ('fuzzy dice', 42, 1.99)
117 The <code class="literal">ROW</code> expression syntax is discussed in more detail in <a class="xref" href="sql-expressions.html#SQL-SYNTAX-ROW-CONSTRUCTORS" title="4.2.13. Row Constructors">Section 4.2.13</a>.
118 </p></div><div class="sect2" id="ROWTYPES-ACCESSING"><div class="titlepage"><div><div><h3 class="title">8.16.3. Accessing Composite Types <a href="#ROWTYPES-ACCESSING" class="id_link">#</a></h3></div></div></div><p>
119 To access a field of a composite column, one writes a dot and the field
120 name, much like selecting a field from a table name. In fact, it's so
121 much like selecting from a table name that you often have to use parentheses
122 to keep from confusing the parser. For example, you might try to select
123 some subfields from our <code class="literal">on_hand</code> example table with something
126 </p><pre class="programlisting">
127 SELECT item.name FROM on_hand WHERE item.price > 9.99;
130 This will not work since the name <code class="literal">item</code> is taken to be a table
131 name, not a column name of <code class="literal">on_hand</code>, per SQL syntax rules.
132 You must write it like this:
134 </p><pre class="programlisting">
135 SELECT (item).name FROM on_hand WHERE (item).price > 9.99;
138 or if you need to use the table name as well (for instance in a multitable
141 </p><pre class="programlisting">
142 SELECT (on_hand.item).name FROM on_hand WHERE (on_hand.item).price > 9.99;
145 Now the parenthesized object is correctly interpreted as a reference to
146 the <code class="literal">item</code> column, and then the subfield can be selected from it.
148 Similar syntactic issues apply whenever you select a field from a composite
149 value. For instance, to select just one field from the result of a function
150 that returns a composite value, you'd need to write something like:
152 </p><pre class="programlisting">
153 SELECT (my_func(...)).field FROM ...
156 Without the extra parentheses, this will generate a syntax error.
158 The special field name <code class="literal">*</code> means <span class="quote">“<span class="quote">all fields</span>”</span>, as
159 further explained in <a class="xref" href="rowtypes.html#ROWTYPES-USAGE" title="8.16.5. Using Composite Types in Queries">Section 8.16.5</a>.
160 </p></div><div class="sect2" id="ROWTYPES-MODIFYING"><div class="titlepage"><div><div><h3 class="title">8.16.4. Modifying Composite Types <a href="#ROWTYPES-MODIFYING" class="id_link">#</a></h3></div></div></div><p>
161 Here are some examples of the proper syntax for inserting and updating
163 First, inserting or updating a whole column:
165 </p><pre class="programlisting">
166 INSERT INTO mytab (complex_col) VALUES((1.1,2.2));
168 UPDATE mytab SET complex_col = ROW(1.1,2.2) WHERE ...;
171 The first example omits <code class="literal">ROW</code>, the second uses it; we
172 could have done it either way.
174 We can update an individual subfield of a composite column:
176 </p><pre class="programlisting">
177 UPDATE mytab SET complex_col.r = (complex_col).r + 1 WHERE ...;
180 Notice here that we don't need to (and indeed cannot)
181 put parentheses around the column name appearing just after
182 <code class="literal">SET</code>, but we do need parentheses when referencing the same
183 column in the expression to the right of the equal sign.
185 And we can specify subfields as targets for <code class="command">INSERT</code>, too:
187 </p><pre class="programlisting">
188 INSERT INTO mytab (complex_col.r, complex_col.i) VALUES(1.1, 2.2);
191 Had we not supplied values for all the subfields of the column, the
192 remaining subfields would have been filled with null values.
193 </p></div><div class="sect2" id="ROWTYPES-USAGE"><div class="titlepage"><div><div><h3 class="title">8.16.5. Using Composite Types in Queries <a href="#ROWTYPES-USAGE" class="id_link">#</a></h3></div></div></div><p>
194 There are various special syntax rules and behaviors associated with
195 composite types in queries. These rules provide useful shortcuts,
196 but can be confusing if you don't know the logic behind them.
198 In <span class="productname">PostgreSQL</span>, a reference to a table name (or alias)
199 in a query is effectively a reference to the composite value of the
200 table's current row. For example, if we had a table
201 <code class="structname">inventory_item</code> as shown
202 <a class="link" href="rowtypes.html#ROWTYPES-DECLARING" title="8.16.1. Declaration of Composite Types">above</a>, we could write:
203 </p><pre class="programlisting">
204 SELECT c FROM inventory_item c;
206 This query produces a single composite-valued column, so we might get
208 </p><pre class="programlisting">
210 ------------------------
211 ("fuzzy dice",42,1.99)
214 Note however that simple names are matched to column names before table
215 names, so this example works only because there is no column
216 named <code class="structfield">c</code> in the query's tables.
218 The ordinary qualified-column-name
219 syntax <em class="replaceable"><code>table_name</code></em><code class="literal">.</code><em class="replaceable"><code>column_name</code></em>
220 can be understood as applying <a class="link" href="sql-expressions.html#FIELD-SELECTION" title="4.2.4. Field Selection">field
221 selection</a> to the composite value of the table's current row.
222 (For efficiency reasons, it's not actually implemented that way.)
225 </p><pre class="programlisting">
226 SELECT c.* FROM inventory_item c;
228 then, according to the SQL standard, we should get the contents of the
229 table expanded into separate columns:
230 </p><pre class="programlisting">
231 name | supplier_id | price
232 ------------+-------------+-------
233 fuzzy dice | 42 | 1.99
237 </p><pre class="programlisting">
238 SELECT c.name, c.supplier_id, c.price FROM inventory_item c;
240 <span class="productname">PostgreSQL</span> will apply this expansion behavior to
241 any composite-valued expression, although as shown <a class="link" href="rowtypes.html#ROWTYPES-ACCESSING" title="8.16.3. Accessing Composite Types">above</a>, you need to write parentheses
242 around the value that <code class="literal">.*</code> is applied to whenever it's not a
243 simple table name. For example, if <code class="function">myfunc()</code> is a function
244 returning a composite type with columns <code class="structfield">a</code>,
245 <code class="structfield">b</code>, and <code class="structfield">c</code>, then these two queries have the
247 </p><pre class="programlisting">
248 SELECT (myfunc(x)).* FROM some_table;
249 SELECT (myfunc(x)).a, (myfunc(x)).b, (myfunc(x)).c FROM some_table;
251 </p><div class="tip"><h3 class="title">Tip</h3><p>
252 <span class="productname">PostgreSQL</span> handles column expansion by
253 actually transforming the first form into the second. So, in this
254 example, <code class="function">myfunc()</code> would get invoked three times per row
255 with either syntax. If it's an expensive function you may wish to
256 avoid that, which you can do with a query like:
257 </p><pre class="programlisting">
258 SELECT m.* FROM some_table, LATERAL myfunc(x) AS m;
260 Placing the function in
261 a <code class="literal">LATERAL</code> <code class="literal">FROM</code> item keeps it from
262 being invoked more than once per row. <code class="literal">m.*</code> is still
263 expanded into <code class="literal">m.a, m.b, m.c</code>, but now those variables
264 are just references to the output of the <code class="literal">FROM</code> item.
265 (The <code class="literal">LATERAL</code> keyword is optional here, but we show it
266 to clarify that the function is getting <code class="structfield">x</code>
267 from <code class="structname">some_table</code>.)
269 The <em class="replaceable"><code>composite_value</code></em><code class="literal">.*</code> syntax results in
270 column expansion of this kind when it appears at the top level of
271 a <a class="link" href="queries-select-lists.html" title="7.3. Select Lists"><code class="command">SELECT</code> output
272 list</a>, a <a class="link" href="dml-returning.html" title="6.4. Returning Data from Modified Rows"><code class="literal">RETURNING</code>
273 list</a> in <code class="command">INSERT</code>/<code class="command">UPDATE</code>/<code class="command">DELETE</code>/<code class="command">MERGE</code>,
274 a <a class="link" href="queries-values.html" title="7.7. VALUES Lists"><code class="literal">VALUES</code> clause</a>, or
275 a <a class="link" href="sql-expressions.html#SQL-SYNTAX-ROW-CONSTRUCTORS" title="4.2.13. Row Constructors">row constructor</a>.
276 In all other contexts (including when nested inside one of those
277 constructs), attaching <code class="literal">.*</code> to a composite value does not
278 change the value, since it means <span class="quote">“<span class="quote">all columns</span>”</span> and so the
279 same composite value is produced again. For example,
280 if <code class="function">somefunc()</code> accepts a composite-valued argument,
281 these queries are the same:
283 </p><pre class="programlisting">
284 SELECT somefunc(c.*) FROM inventory_item c;
285 SELECT somefunc(c) FROM inventory_item c;
288 In both cases, the current row of <code class="structname">inventory_item</code> is
289 passed to the function as a single composite-valued argument.
290 Even though <code class="literal">.*</code> does nothing in such cases, using it is good
291 style, since it makes clear that a composite value is intended. In
292 particular, the parser will consider <code class="literal">c</code> in <code class="literal">c.*</code> to
293 refer to a table name or alias, not to a column name, so that there is
294 no ambiguity; whereas without <code class="literal">.*</code>, it is not clear
295 whether <code class="literal">c</code> means a table name or a column name, and in fact
296 the column-name interpretation will be preferred if there is a column
297 named <code class="literal">c</code>.
299 Another example demonstrating these concepts is that all these queries
301 </p><pre class="programlisting">
302 SELECT * FROM inventory_item c ORDER BY c;
303 SELECT * FROM inventory_item c ORDER BY c.*;
304 SELECT * FROM inventory_item c ORDER BY ROW(c.*);
306 All of these <code class="literal">ORDER BY</code> clauses specify the row's composite
307 value, resulting in sorting the rows according to the rules described
308 in <a class="xref" href="functions-comparisons.html#COMPOSITE-TYPE-COMPARISON" title="9.25.6. Composite Type Comparison">Section 9.25.6</a>. However,
309 if <code class="structname">inventory_item</code> contained a column
310 named <code class="structfield">c</code>, the first case would be different from the
311 others, as it would mean to sort by that column only. Given the column
312 names previously shown, these queries are also equivalent to those above:
313 </p><pre class="programlisting">
314 SELECT * FROM inventory_item c ORDER BY ROW(c.name, c.supplier_id, c.price);
315 SELECT * FROM inventory_item c ORDER BY (c.name, c.supplier_id, c.price);
317 (The last case uses a row constructor with the key word <code class="literal">ROW</code>
320 Another special syntactical behavior associated with composite values is
321 that we can use <em class="firstterm">functional notation</em> for extracting a field
322 of a composite value. The simple way to explain this is that
323 the notations <code class="literal"><em class="replaceable"><code>field</code></em>(<em class="replaceable"><code>table</code></em>)</code>
324 and <code class="literal"><em class="replaceable"><code>table</code></em>.<em class="replaceable"><code>field</code></em></code>
325 are interchangeable. For example, these queries are equivalent:
327 </p><pre class="programlisting">
328 SELECT c.name FROM inventory_item c WHERE c.price > 1000;
329 SELECT name(c) FROM inventory_item c WHERE price(c) > 1000;
332 Moreover, if we have a function that accepts a single argument of a
333 composite type, we can call it with either notation. These queries are
336 </p><pre class="programlisting">
337 SELECT somefunc(c) FROM inventory_item c;
338 SELECT somefunc(c.*) FROM inventory_item c;
339 SELECT c.somefunc FROM inventory_item c;
342 This equivalence between functional notation and field notation
343 makes it possible to use functions on composite types to implement
344 <span class="quote">“<span class="quote">computed fields</span>”</span>.
345 <a id="id-1.5.7.24.9.10.2" class="indexterm"></a>
346 <a id="id-1.5.7.24.9.10.3" class="indexterm"></a>
347 An application using the last query above wouldn't need to be directly
348 aware that <code class="literal">somefunc</code> isn't a real column of the table.
349 </p><div class="tip"><h3 class="title">Tip</h3><p>
350 Because of this behavior, it's unwise to give a function that takes a
351 single composite-type argument the same name as any of the fields of
352 that composite type. If there is ambiguity, the field-name
353 interpretation will be chosen if field-name syntax is used, while the
354 function will be chosen if function-call syntax is used. However,
355 <span class="productname">PostgreSQL</span> versions before 11 always chose the
356 field-name interpretation, unless the syntax of the call required it to
357 be a function call. One way to force the function interpretation in
358 older versions is to schema-qualify the function name, that is, write
359 <code class="literal"><em class="replaceable"><code>schema</code></em>.<em class="replaceable"><code>func</code></em>(<em class="replaceable"><code>compositevalue</code></em>)</code>.
360 </p></div></div><div class="sect2" id="ROWTYPES-IO-SYNTAX"><div class="titlepage"><div><div><h3 class="title">8.16.6. Composite Type Input and Output Syntax <a href="#ROWTYPES-IO-SYNTAX" class="id_link">#</a></h3></div></div></div><p>
361 The external text representation of a composite value consists of items that
362 are interpreted according to the I/O conversion rules for the individual
363 field types, plus decoration that indicates the composite structure.
364 The decoration consists of parentheses (<code class="literal">(</code> and <code class="literal">)</code>)
365 around the whole value, plus commas (<code class="literal">,</code>) between adjacent
366 items. Whitespace outside the parentheses is ignored, but within the
367 parentheses it is considered part of the field value, and might or might not be
368 significant depending on the input conversion rules for the field data type.
370 </p><pre class="programlisting">
373 the whitespace will be ignored if the field type is integer, but not if
376 As shown previously, when writing a composite value you can write double
377 quotes around any individual field value.
378 You <span class="emphasis"><em>must</em></span> do so if the field value would otherwise
379 confuse the composite-value parser. In particular, fields containing
380 parentheses, commas, double quotes, or backslashes must be double-quoted.
381 To put a double quote or backslash in a quoted composite field value,
382 precede it with a backslash. (Also, a pair of double quotes within a
383 double-quoted field value is taken to represent a double quote character,
384 analogously to the rules for single quotes in SQL literal strings.)
385 Alternatively, you can avoid quoting and use backslash-escaping to
386 protect all data characters
387 that would otherwise be taken as composite syntax.
389 A completely empty field value (no characters at all between the commas
390 or parentheses) represents a NULL. To write a value that is an empty
391 string rather than NULL, write <code class="literal">""</code>.
393 The composite output routine will put double quotes around field values
394 if they are empty strings or contain parentheses, commas,
395 double quotes, backslashes, or white space. (Doing so for white space
396 is not essential, but aids legibility.) Double quotes and backslashes
397 embedded in field values will be doubled.
398 </p><div class="note"><h3 class="title">Note</h3><p>
399 Remember that what you write in an SQL command will first be interpreted
400 as a string literal, and then as a composite. This doubles the number of
401 backslashes you need (assuming escape string syntax is used).
402 For example, to insert a <code class="type">text</code> field
403 containing a double quote and a backslash in a composite
404 value, you'd need to write:
405 </p><pre class="programlisting">
406 INSERT ... VALUES ('("\"\\")');
408 The string-literal processor removes one level of backslashes, so that
409 what arrives at the composite-value parser looks like
410 <code class="literal">("\"\\")</code>. In turn, the string
411 fed to the <code class="type">text</code> data type's input routine
412 becomes <code class="literal">"\</code>. (If we were working
413 with a data type whose input routine also treated backslashes specially,
414 <code class="type">bytea</code> for example, we might need as many as eight backslashes
415 in the command to get one backslash into the stored composite field.)
416 Dollar quoting (see <a class="xref" href="sql-syntax-lexical.html#SQL-SYNTAX-DOLLAR-QUOTING" title="4.1.2.4. Dollar-Quoted String Constants">Section 4.1.2.4</a>) can be
417 used to avoid the need to double backslashes.
418 </p></div><div class="tip"><h3 class="title">Tip</h3><p>
419 The <code class="literal">ROW</code> constructor syntax is usually easier to work with
420 than the composite-literal syntax when writing composite values in SQL
422 In <code class="literal">ROW</code>, individual field values are written the same way
423 they would be written when not members of a composite.
424 </p></div></div></div><div class="navfooter"><hr /><table width="100%" summary="Navigation footer"><tr><td width="40%" align="left"><a accesskey="p" href="arrays.html" title="8.15. Arrays">Prev</a> </td><td width="20%" align="center"><a accesskey="u" href="datatype.html" title="Chapter 8. Data Types">Up</a></td><td width="40%" align="right"> <a accesskey="n" href="rangetypes.html" title="8.17. Range Types">Next</a></td></tr><tr><td width="40%" align="left" valign="top">8.15. Arrays </td><td width="20%" align="center"><a accesskey="h" href="index.html" title="PostgreSQL 18.0 Documentation">Home</a></td><td width="40%" align="right" valign="top"> 8.17. Range Types</td></tr></table></div></body></html>