4 CREATE TABLE — define a new table
8 CREATE [ [ GLOBAL | LOCAL ] { TEMPORARY | TEMP } | UNLOGGED ] TABLE [ IF NOT EXI
10 { column_name data_type [ STORAGE { PLAIN | EXTERNAL | EXTENDED | MAIN | DEFAU
11 LT } ] [ COMPRESSION compression_method ] [ COLLATE collation ] [ column_constra
14 | LIKE source_table [ like_option ... ] }
17 [ INHERITS ( parent_table [, ... ] ) ]
18 [ PARTITION BY { RANGE | LIST | HASH } ( { column_name | ( expression ) } [ COLL
19 ATE collation ] [ opclass ] [, ... ] ) ]
21 [ WITH ( storage_parameter [= value] [, ... ] ) | WITHOUT OIDS ]
22 [ ON COMMIT { PRESERVE ROWS | DELETE ROWS | DROP } ]
23 [ TABLESPACE tablespace_name ]
25 CREATE [ [ GLOBAL | LOCAL ] { TEMPORARY | TEMP } | UNLOGGED ] TABLE [ IF NOT EXI
28 { column_name [ WITH OPTIONS ] [ column_constraint [ ... ] ]
32 [ PARTITION BY { RANGE | LIST | HASH } ( { column_name | ( expression ) } [ COLL
33 ATE collation ] [ opclass ] [, ... ] ) ]
35 [ WITH ( storage_parameter [= value] [, ... ] ) | WITHOUT OIDS ]
36 [ ON COMMIT { PRESERVE ROWS | DELETE ROWS | DROP } ]
37 [ TABLESPACE tablespace_name ]
39 CREATE [ [ GLOBAL | LOCAL ] { TEMPORARY | TEMP } | UNLOGGED ] TABLE [ IF NOT EXI
41 PARTITION OF parent_table [ (
42 { column_name [ WITH OPTIONS ] [ column_constraint [ ... ] ]
45 ) ] { FOR VALUES partition_bound_spec | DEFAULT }
46 [ PARTITION BY { RANGE | LIST | HASH } ( { column_name | ( expression ) } [ COLL
47 ATE collation ] [ opclass ] [, ... ] ) ]
49 [ WITH ( storage_parameter [= value] [, ... ] ) | WITHOUT OIDS ]
50 [ ON COMMIT { PRESERVE ROWS | DELETE ROWS | DROP } ]
51 [ TABLESPACE tablespace_name ]
53 where column_constraint is:
55 [ CONSTRAINT constraint_name ]
56 { NOT NULL [ NO INHERIT ] |
58 CHECK ( expression ) [ NO INHERIT ] |
59 DEFAULT default_expr |
60 GENERATED ALWAYS AS ( generation_expr ) [ STORED | VIRTUAL ] |
61 GENERATED { ALWAYS | BY DEFAULT } AS IDENTITY [ ( sequence_options ) ] |
62 UNIQUE [ NULLS [ NOT ] DISTINCT ] index_parameters |
63 PRIMARY KEY index_parameters |
64 REFERENCES reftable [ ( refcolumn ) ] [ MATCH FULL | MATCH PARTIAL | MATCH SIM
66 [ ON DELETE referential_action ] [ ON UPDATE referential_action ] }
67 [ DEFERRABLE | NOT DEFERRABLE ] [ INITIALLY DEFERRED | INITIALLY IMMEDIATE ] [ E
68 NFORCED | NOT ENFORCED ]
70 and table_constraint is:
72 [ CONSTRAINT constraint_name ]
73 { CHECK ( expression ) [ NO INHERIT ] |
74 NOT NULL column_name [ NO INHERIT ] |
75 UNIQUE [ NULLS [ NOT ] DISTINCT ] ( column_name [, ... ] [, column_name WITHOU
76 T OVERLAPS ] ) index_parameters |
77 PRIMARY KEY ( column_name [, ... ] [, column_name WITHOUT OVERLAPS ] ) index_p
79 EXCLUDE [ USING index_method ] ( exclude_element WITH operator [, ... ] ) inde
80 x_parameters [ WHERE ( predicate ) ] |
81 FOREIGN KEY ( column_name [, ... ] [, PERIOD column_name ] ) REFERENCES reftab
82 le [ ( refcolumn [, ... ] [, PERIOD refcolumn ] ) ]
83 [ MATCH FULL | MATCH PARTIAL | MATCH SIMPLE ] [ ON DELETE referential_action
84 ] [ ON UPDATE referential_action ] }
85 [ DEFERRABLE | NOT DEFERRABLE ] [ INITIALLY DEFERRED | INITIALLY IMMEDIATE ] [ E
86 NFORCED | NOT ENFORCED ]
90 { INCLUDING | EXCLUDING } { COMMENTS | COMPRESSION | CONSTRAINTS | DEFAULTS | GE
91 NERATED | IDENTITY | INDEXES | STATISTICS | STORAGE | ALL }
93 and partition_bound_spec is:
95 IN ( partition_bound_expr [, ...] ) |
96 FROM ( { partition_bound_expr | MINVALUE | MAXVALUE } [, ...] )
97 TO ( { partition_bound_expr | MINVALUE | MAXVALUE } [, ...] ) |
98 WITH ( MODULUS numeric_literal, REMAINDER numeric_literal )
100 index_parameters in UNIQUE, PRIMARY KEY, and EXCLUDE constraints are:
102 [ INCLUDE ( column_name [, ... ] ) ]
103 [ WITH ( storage_parameter [= value] [, ... ] ) ]
104 [ USING INDEX TABLESPACE tablespace_name ]
106 exclude_element in an EXCLUDE constraint is:
108 { column_name | ( expression ) } [ COLLATE collation ] [ opclass [ ( opclass_par
109 ameter = value [, ... ] ) ] ] [ ASC | DESC ] [ NULLS { FIRST | LAST } ]
111 referential_action in a FOREIGN KEY/REFERENCES constraint is:
113 { NO ACTION | RESTRICT | CASCADE | SET NULL [ ( column_name [, ... ] ) ] | SET D
114 EFAULT [ ( column_name [, ... ] ) ] }
118 CREATE TABLE will create a new, initially empty table in the current
119 database. The table will be owned by the user issuing the command.
121 If a schema name is given (for example, CREATE TABLE myschema.mytable
122 ...) then the table is created in the specified schema. Otherwise it is
123 created in the current schema. Temporary tables exist in a special
124 schema, so a schema name cannot be given when creating a temporary
125 table. The name of the table must be distinct from the name of any
126 other relation (table, sequence, index, view, materialized view, or
127 foreign table) in the same schema.
129 CREATE TABLE also automatically creates a data type that represents the
130 composite type corresponding to one row of the table. Therefore, tables
131 cannot have the same name as any existing data type in the same schema.
133 The optional constraint clauses specify constraints (tests) that new or
134 updated rows must satisfy for an insert or update operation to succeed.
135 A constraint is an SQL object that helps define the set of valid values
136 in the table in various ways.
138 There are two ways to define constraints: table constraints and column
139 constraints. A column constraint is defined as part of a column
140 definition. A table constraint definition is not tied to a particular
141 column, and it can encompass more than one column. Every column
142 constraint can also be written as a table constraint; a column
143 constraint is only a notational convenience for use when the constraint
144 only affects one column.
146 To be able to create a table, you must have USAGE privilege on all
147 column types or the type in the OF clause, respectively.
152 If specified, the table is created as a temporary table.
153 Temporary tables are automatically dropped at the end of a
154 session, or optionally at the end of the current transaction
155 (see ON COMMIT below). The default search_path includes the
156 temporary schema first and so identically named existing
157 permanent tables are not chosen for new plans while the
158 temporary table exists, unless they are referenced with
159 schema-qualified names. Any indexes created on a temporary table
160 are automatically temporary as well.
162 The autovacuum daemon cannot access and therefore cannot vacuum
163 or analyze temporary tables. For this reason, appropriate vacuum
164 and analyze operations should be performed via session SQL
165 commands. For example, if a temporary table is going to be used
166 in complex queries, it is wise to run ANALYZE on the temporary
167 table after it is populated.
169 Optionally, GLOBAL or LOCAL can be written before TEMPORARY or
170 TEMP. This presently makes no difference in PostgreSQL and is
171 deprecated; see Compatibility below.
174 If specified, the table is created as an unlogged table. Data
175 written to unlogged tables is not written to the write-ahead log
176 (see Chapter 28), which makes them considerably faster than
177 ordinary tables. However, they are not crash-safe: an unlogged
178 table is automatically truncated after a crash or unclean
179 shutdown. The contents of an unlogged table are also not
180 replicated to standby servers. Any indexes created on an
181 unlogged table are automatically unlogged as well.
183 If this is specified, any sequences created together with the
184 unlogged table (for identity or serial columns) are also created
187 This form is not supported for partitioned tables.
190 Do not throw an error if a relation with the same name already
191 exists. A notice is issued in this case. Note that there is no
192 guarantee that the existing relation is anything like the one
193 that would have been created.
196 The name (optionally schema-qualified) of the table to be
200 Creates a typed table, which takes its structure from the
201 specified stand-alone composite type (that is, one created using
202 CREATE TYPE) though it still produces a new composite type as
203 well. The table will have a dependency on the referenced type,
204 meaning that cascaded alter and drop actions on that type will
205 propagate to the table.
207 A typed table always has the same column names and data types as
208 the type it is derived from, so you cannot specify additional
209 columns. But the CREATE TABLE command can add defaults and
210 constraints to the table, as well as specify storage parameters.
213 The name of a column to be created in the new table.
216 The data type of the column. This can include array specifiers.
217 For more information on the data types supported by PostgreSQL,
221 The COLLATE clause assigns a collation to the column (which must
222 be of a collatable data type). If not specified, the column data
223 type's default collation is used.
225 STORAGE { PLAIN | EXTERNAL | EXTENDED | MAIN | DEFAULT } #
226 This form sets the storage mode for the column. This controls
227 whether this column is held inline or in a secondary TOAST
228 table, and whether the data should be compressed or not. PLAIN
229 must be used for fixed-length values such as integer and is
230 inline, uncompressed. MAIN is for inline, compressible data.
231 EXTERNAL is for external, uncompressed data, and EXTENDED is for
232 external, compressed data. Writing DEFAULT sets the storage mode
233 to the default mode for the column's data type. EXTENDED is the
234 default for most data types that support non-PLAIN storage. Use
235 of EXTERNAL will make substring operations on very large text
236 and bytea values run faster, at the penalty of increased storage
237 space. See Section 66.2 for more information.
239 COMPRESSION compression_method #
240 The COMPRESSION clause sets the compression method for the
241 column. Compression is supported only for variable-width data
242 types, and is used only when the column's storage mode is main
243 or extended. (See ALTER TABLE for information on column storage
244 modes.) Setting this property for a partitioned table has no
245 direct effect, because such tables have no storage of their own,
246 but the configured value will be inherited by newly-created
247 partitions. The supported compression methods are pglz and lz4.
248 (lz4 is available only if --with-lz4 was used when building
249 PostgreSQL.) In addition, compression_method can be default to
250 explicitly specify the default behavior, which is to consult the
251 default_toast_compression setting at the time of data insertion
252 to determine the method to use.
254 INHERITS ( parent_table [, ... ] ) #
255 The optional INHERITS clause specifies a list of tables from
256 which the new table automatically inherits all columns. Parent
257 tables can be plain tables or foreign tables.
259 Use of INHERITS creates a persistent relationship between the
260 new child table and its parent table(s). Schema modifications to
261 the parent(s) normally propagate to children as well, and by
262 default the data of the child table is included in scans of the
265 If the same column name exists in more than one parent table, an
266 error is reported unless the data types of the columns match in
267 each of the parent tables. If there is no conflict, then the
268 duplicate columns are merged to form a single column in the new
269 table. If the column name list of the new table contains a
270 column name that is also inherited, the data type must likewise
271 match the inherited column(s), and the column definitions are
272 merged into one. If the new table explicitly specifies a default
273 value for the column, this default overrides any defaults from
274 inherited declarations of the column. Otherwise, any parents
275 that specify default values for the column must all specify the
276 same default, or an error will be reported.
278 CHECK constraints are merged in essentially the same way as
279 columns: if multiple parent tables and/or the new table
280 definition contain identically-named CHECK constraints, these
281 constraints must all have the same check expression, or an error
282 will be reported. Constraints having the same name and
283 expression will be merged into one copy. A constraint marked NO
284 INHERIT in a parent will not be considered. Notice that an
285 unnamed CHECK constraint in the new table will never be merged,
286 since a unique name will always be chosen for it.
288 Column STORAGE settings are also copied from parent tables.
290 If a column in the parent table is an identity column, that
291 property is not inherited. A column in the child table can be
292 declared identity column if desired.
294 PARTITION BY { RANGE | LIST | HASH } ( { column_name | ( expression ) }
295 [ opclass ] [, ...] ) #
296 The optional PARTITION BY clause specifies a strategy of
297 partitioning the table. The table thus created is called a
298 partitioned table. The parenthesized list of columns or
299 expressions forms the partition key for the table. When using
300 range or hash partitioning, the partition key can include
301 multiple columns or expressions (up to 32, but this limit can be
302 altered when building PostgreSQL), but for list partitioning,
303 the partition key must consist of a single column or expression.
305 Range and list partitioning require a btree operator class,
306 while hash partitioning requires a hash operator class. If no
307 operator class is specified explicitly, the default operator
308 class of the appropriate type will be used; if no default
309 operator class exists, an error will be raised. When hash
310 partitioning is used, the operator class used must implement
311 support function 2 (see Section 36.16.3 for details).
313 A partitioned table is divided into sub-tables (called
314 partitions), which are created using separate CREATE TABLE
315 commands. The partitioned table is itself empty. A data row
316 inserted into the table is routed to a partition based on the
317 value of columns or expressions in the partition key. If no
318 existing partition matches the values in the new row, an error
321 See Section 5.12 for more discussion on table partitioning.
323 PARTITION OF parent_table { FOR VALUES partition_bound_spec | DEFAULT }
325 Creates the table as a partition of the specified parent table.
326 The table can be created either as a partition for specific
327 values using FOR VALUES or as a default partition using DEFAULT.
328 Any indexes, constraints and user-defined row-level triggers
329 that exist in the parent table are cloned on the new partition.
331 The partition_bound_spec must correspond to the partitioning
332 method and partition key of the parent table, and must not
333 overlap with any existing partition of that parent. The form
334 with IN is used for list partitioning, the form with FROM and TO
335 is used for range partitioning, and the form with WITH is used
336 for hash partitioning.
338 partition_bound_expr is any variable-free expression
339 (subqueries, window functions, aggregate functions, and
340 set-returning functions are not allowed). Its data type must
341 match the data type of the corresponding partition key column.
342 The expression is evaluated once at table creation time, so it
343 can even contain volatile expressions such as CURRENT_TIMESTAMP.
345 When creating a list partition, NULL can be specified to signify
346 that the partition allows the partition key column to be null.
347 However, there cannot be more than one such list partition for a
348 given parent table. NULL cannot be specified for range
351 When creating a range partition, the lower bound specified with
352 FROM is an inclusive bound, whereas the upper bound specified
353 with TO is an exclusive bound. That is, the values specified in
354 the FROM list are valid values of the corresponding partition
355 key columns for this partition, whereas those in the TO list are
356 not. Note that this statement must be understood according to
357 the rules of row-wise comparison (Section 9.25.5). For example,
358 given PARTITION BY RANGE (x,y), a partition bound FROM (1, 2) TO
359 (3, 4) allows x=1 with any y>=2, x=2 with any non-null y, and
362 The special values MINVALUE and MAXVALUE may be used when
363 creating a range partition to indicate that there is no lower or
364 upper bound on the column's value. For example, a partition
365 defined using FROM (MINVALUE) TO (10) allows any values less
366 than 10, and a partition defined using FROM (10) TO (MAXVALUE)
367 allows any values greater than or equal to 10.
369 When creating a range partition involving more than one column,
370 it can also make sense to use MAXVALUE as part of the lower
371 bound, and MINVALUE as part of the upper bound. For example, a
372 partition defined using FROM (0, MAXVALUE) TO (10, MAXVALUE)
373 allows any rows where the first partition key column is greater
374 than 0 and less than or equal to 10. Similarly, a partition
375 defined using FROM ('a', MINVALUE) TO ('b', MINVALUE) allows any
376 rows where the first partition key column starts with "a".
378 Note that if MINVALUE or MAXVALUE is used for one column of a
379 partitioning bound, the same value must be used for all
380 subsequent columns. For example, (10, MINVALUE, 0) is not a
381 valid bound; you should write (10, MINVALUE, MINVALUE).
383 Also note that some element types, such as timestamp, have a
384 notion of "infinity", which is just another value that can be
385 stored. This is different from MINVALUE and MAXVALUE, which are
386 not real values that can be stored, but rather they are ways of
387 saying that the value is unbounded. MAXVALUE can be thought of
388 as being greater than any other value, including "infinity" and
389 MINVALUE as being less than any other value, including "minus
390 infinity". Thus the range FROM ('infinity') TO (MAXVALUE) is not
391 an empty range; it allows precisely one value to be stored —
394 If DEFAULT is specified, the table will be created as the
395 default partition of the parent table. This option is not
396 available for hash-partitioned tables. A partition key value not
397 fitting into any other partition of the given parent will be
398 routed to the default partition.
400 When a table has an existing DEFAULT partition and a new
401 partition is added to it, the default partition must be scanned
402 to verify that it does not contain any rows which properly
403 belong in the new partition. If the default partition contains a
404 large number of rows, this may be slow. The scan will be skipped
405 if the default partition is a foreign table or if it has a
406 constraint which proves that it cannot contain rows which should
407 be placed in the new partition.
409 When creating a hash partition, a modulus and remainder must be
410 specified. The modulus must be a positive integer, and the
411 remainder must be a non-negative integer less than the modulus.
412 Typically, when initially setting up a hash-partitioned table,
413 you should choose a modulus equal to the number of partitions
414 and assign every table the same modulus and a different
415 remainder (see examples, below). However, it is not required
416 that every partition have the same modulus, only that every
417 modulus which occurs among the partitions of a hash-partitioned
418 table is a factor of the next larger modulus. This allows the
419 number of partitions to be increased incrementally without
420 needing to move all the data at once. For example, suppose you
421 have a hash-partitioned table with 8 partitions, each of which
422 has modulus 8, but find it necessary to increase the number of
423 partitions to 16. You can detach one of the modulus-8
424 partitions, create two new modulus-16 partitions covering the
425 same portion of the key space (one with a remainder equal to the
426 remainder of the detached partition, and the other with a
427 remainder equal to that value plus 8), and repopulate them with
428 data. You can then repeat this -- perhaps at a later time -- for
429 each modulus-8 partition until none remain. While this may still
430 involve a large amount of data movement at each step, it is
431 still better than having to create a whole new table and move
432 all the data at once.
434 A partition must have the same column names and types as the
435 partitioned table to which it belongs. Modifications to the
436 column names or types of a partitioned table will automatically
437 propagate to all partitions. CHECK constraints will be inherited
438 automatically by every partition, but an individual partition
439 may specify additional CHECK constraints; additional constraints
440 with the same name and condition as in the parent will be merged
441 with the parent constraint. Defaults may be specified separately
442 for each partition. But note that a partition's default value is
443 not applied when inserting a tuple through a partitioned table.
445 Rows inserted into a partitioned table will be automatically
446 routed to the correct partition. If no suitable partition
447 exists, an error will occur.
449 Operations such as TRUNCATE which normally affect a table and
450 all of its inheritance children will cascade to all partitions,
451 but may also be performed on an individual partition.
453 Note that creating a partition using PARTITION OF requires
454 taking an ACCESS EXCLUSIVE lock on the parent partitioned table.
455 Likewise, dropping a partition with DROP TABLE requires taking
456 an ACCESS EXCLUSIVE lock on the parent table. It is possible to
457 use ALTER TABLE ATTACH/DETACH PARTITION to perform these
458 operations with a weaker lock, thus reducing interference with
459 concurrent operations on the partitioned table.
461 LIKE source_table [ like_option ... ] #
462 The LIKE clause specifies a table from which the new table
463 automatically copies all column names, their data types, and
464 their not-null constraints.
466 Unlike INHERITS, the new table and original table are completely
467 decoupled after creation is complete. Changes to the original
468 table will not be applied to the new table, and it is not
469 possible to include data of the new table in scans of the
472 Also unlike INHERITS, columns and constraints copied by LIKE are
473 not merged with similarly named columns and constraints. If the
474 same name is specified explicitly or in another LIKE clause, an
477 The optional like_option clauses specify which additional
478 properties of the original table to copy. Specifying INCLUDING
479 copies the property, specifying EXCLUDING omits the property.
480 EXCLUDING is the default. If multiple specifications are made
481 for the same kind of object, the last one is used. The available
485 Comments for the copied columns, constraints, and indexes
486 will be copied. The default behavior is to exclude
487 comments, resulting in the copied columns and constraints
488 in the new table having no comments.
490 INCLUDING COMPRESSION #
491 Compression method of the columns will be copied. The
492 default behavior is to exclude compression methods,
493 resulting in columns having the default compression
496 INCLUDING CONSTRAINTS #
497 CHECK constraints will be copied. No distinction is made
498 between column constraints and table constraints. Not-null
499 constraints are always copied to the new table.
502 Default expressions for the copied column definitions will
503 be copied. Otherwise, default expressions are not copied,
504 resulting in the copied columns in the new table having
505 null defaults. Note that copying defaults that call
506 database-modification functions, such as nextval, may
507 create a functional linkage between the original and new
510 INCLUDING GENERATED #
511 Any generation expressions as well as the stored/virtual
512 choice of copied column definitions will be copied. By
513 default, new columns will be regular base columns.
516 Any identity specifications of copied column definitions
517 will be copied. A new sequence is created for each
518 identity column of the new table, separate from the
519 sequences associated with the old table.
522 Indexes, PRIMARY KEY, UNIQUE, and EXCLUDE constraints on
523 the original table will be created on the new table. Names
524 for the new indexes and constraints are chosen according
525 to the default rules, regardless of how the originals were
526 named. (This behavior avoids possible duplicate-name
527 failures for the new indexes.)
529 INCLUDING STATISTICS #
530 Extended statistics are copied to the new table.
533 STORAGE settings for the copied column definitions will be
534 copied. The default behavior is to exclude STORAGE
535 settings, resulting in the copied columns in the new table
536 having type-specific default settings. For more on STORAGE
537 settings, see Section 66.2.
540 INCLUDING ALL is an abbreviated form selecting all the
541 available individual options. (It could be useful to write
542 individual EXCLUDING clauses after INCLUDING ALL to select
543 all but some specific options.)
545 The LIKE clause can also be used to copy column definitions from
546 views, foreign tables, or composite types. Inapplicable options
547 (e.g., INCLUDING INDEXES from a view) are ignored.
549 CONSTRAINT constraint_name #
550 An optional name for a column or table constraint. If the
551 constraint is violated, the constraint name is present in error
552 messages, so constraint names like col must be positive can be
553 used to communicate helpful constraint information to client
554 applications. (Double-quotes are needed to specify constraint
555 names that contain spaces.) If a constraint name is not
556 specified, the system generates a name.
558 NOT NULL [ NO INHERIT ] #
559 The column is not allowed to contain null values.
561 A constraint marked with NO INHERIT will not propagate to child
565 The column is allowed to contain null values. This is the
568 This clause is only provided for compatibility with non-standard
569 SQL databases. Its use is discouraged in new applications.
571 CHECK ( expression ) [ NO INHERIT ] #
572 The CHECK clause specifies an expression producing a Boolean
573 result which new or updated rows must satisfy for an insert or
574 update operation to succeed. Expressions evaluating to TRUE or
575 UNKNOWN succeed. Should any row of an insert or update operation
576 produce a FALSE result, an error exception is raised and the
577 insert or update does not alter the database. A check constraint
578 specified as a column constraint should reference that column's
579 value only, while an expression appearing in a table constraint
580 can reference multiple columns.
582 Currently, CHECK expressions cannot contain subqueries nor refer
583 to variables other than columns of the current row (see
584 Section 5.5.1). The system column tableoid may be referenced,
585 but not any other system column.
587 A constraint marked with NO INHERIT will not propagate to child
590 When a table has multiple CHECK constraints, they will be tested
591 for each row in alphabetical order by name, after checking NOT
592 NULL constraints. (PostgreSQL versions before 9.5 did not honor
593 any particular firing order for CHECK constraints.)
595 DEFAULT default_expr #
596 The DEFAULT clause assigns a default data value for the column
597 whose column definition it appears within. The value is any
598 variable-free expression (in particular, cross-references to
599 other columns in the current table are not allowed). Subqueries
600 are not allowed either. The data type of the default expression
601 must match the data type of the column.
603 The default expression will be used in any insert operation that
604 does not specify a value for the column. If there is no default
605 for a column, then the default is null.
607 GENERATED ALWAYS AS ( generation_expr ) [ STORED | VIRTUAL ] #
608 This clause creates the column as a generated column. The column
609 cannot be written to, and when read the result of the specified
610 expression will be returned.
612 When VIRTUAL is specified, the column will be computed when it
613 is read, and it will not occupy any storage. When STORED is
614 specified, the column will be computed on write and will be
615 stored on disk. VIRTUAL is the default.
617 The generation expression can refer to other columns in the
618 table, but not other generated columns. Any functions and
619 operators used must be immutable. References to other tables are
622 A virtual generated column cannot have a user-defined type, and
623 the generation expression of a virtual generated column must not
624 reference user-defined functions or types, that is, it can only
625 use built-in functions or types. This applies also indirectly,
626 such as for functions or types that underlie operators or casts.
627 (This restriction does not exist for stored generated columns.)
629 GENERATED { ALWAYS | BY DEFAULT } AS IDENTITY [ ( sequence_options ) ]
631 This clause creates the column as an identity column. It will
632 have an implicit sequence attached to it and in newly-inserted
633 rows the column will automatically have values from the sequence
634 assigned to it. Such a column is implicitly NOT NULL.
636 The clauses ALWAYS and BY DEFAULT determine how explicitly
637 user-specified values are handled in INSERT and UPDATE commands.
639 In an INSERT command, if ALWAYS is selected, a user-specified
640 value is only accepted if the INSERT statement specifies
641 OVERRIDING SYSTEM VALUE. If BY DEFAULT is selected, then the
642 user-specified value takes precedence. See INSERT for details.
643 (In the COPY command, user-specified values are always used
644 regardless of this setting.)
646 In an UPDATE command, if ALWAYS is selected, any update of the
647 column to any value other than DEFAULT will be rejected. If BY
648 DEFAULT is selected, the column can be updated normally. (There
649 is no OVERRIDING clause for the UPDATE command.)
651 The optional sequence_options clause can be used to override the
652 parameters of the sequence. The available options include those
653 shown for CREATE SEQUENCE, plus SEQUENCE NAME name, LOGGED, and
654 UNLOGGED, which allow selection of the name and persistence
655 level of the sequence. Without SEQUENCE NAME, the system chooses
656 an unused name for the sequence. Without LOGGED or UNLOGGED, the
657 sequence will have the same persistence level as the table.
659 UNIQUE [ NULLS [ NOT ] DISTINCT ] (column constraint)
660 UNIQUE [ NULLS [ NOT ] DISTINCT ] ( column_name [, ... ] [,
661 column_name WITHOUT OVERLAPS ] ) [ INCLUDE ( column_name [,
662 ...]) ] (table constraint) #
663 The UNIQUE constraint specifies that a group of one or more
664 columns of a table can contain only unique values. The behavior
665 of a unique table constraint is the same as that of a unique
666 column constraint, with the additional capability to span
667 multiple columns. The constraint therefore enforces that any two
668 rows must differ in at least one of these columns.
670 If the WITHOUT OVERLAPS option is specified for the last column,
671 then that column is checked for overlaps instead of equality. In
672 that case, the other columns of the constraint will allow
673 duplicates so long as the duplicates don't overlap in the
674 WITHOUT OVERLAPS column. (This is sometimes called a temporal
675 key, if the column is a range of dates or timestamps, but
676 PostgreSQL allows ranges over any base type.) In effect, such a
677 constraint is enforced with an EXCLUDE constraint rather than a
678 UNIQUE constraint. So for example UNIQUE (id, valid_at WITHOUT
679 OVERLAPS) behaves like EXCLUDE USING GIST (id WITH =, valid_at
680 WITH &&). The WITHOUT OVERLAPS column must have a range or
681 multirange type. Empty ranges/multiranges are not permitted. The
682 non-WITHOUT OVERLAPS columns of the constraint can be any type
683 that can be compared for equality in a GiST index. By default,
684 only range types are supported, but you can use other types by
685 adding the btree_gist extension (which is the expected way to
688 For the purpose of a unique constraint, null values are not
689 considered equal, unless NULLS NOT DISTINCT is specified.
691 Each unique constraint should name a set of columns that is
692 different from the set of columns named by any other unique or
693 primary key constraint defined for the table. (Otherwise,
694 redundant unique constraints will be discarded.)
696 When establishing a unique constraint for a multi-level
697 partition hierarchy, all the columns in the partition key of the
698 target partitioned table, as well as those of all its descendant
699 partitioned tables, must be included in the constraint
702 Adding a unique constraint will automatically create a unique
703 btree index on the column or group of columns used in the
704 constraint. But if the constraint includes a WITHOUT OVERLAPS
705 clause, it will use a GiST index. The created index has the same
706 name as the unique constraint.
708 The optional INCLUDE clause adds to that index one or more
709 columns that are simply “payload”: uniqueness is not enforced on
710 them, and the index cannot be searched on the basis of those
711 columns. However they can be retrieved by an index-only scan.
712 Note that although the constraint is not enforced on included
713 columns, it still depends on them. Consequently, some operations
714 on such columns (e.g., DROP COLUMN) can cause cascaded
715 constraint and index deletion.
717 PRIMARY KEY (column constraint)
718 PRIMARY KEY ( column_name [, ... ] [, column_name WITHOUT
719 OVERLAPS ] ) [ INCLUDE ( column_name [, ...]) ] (table
721 The PRIMARY KEY constraint specifies that a column or columns of
722 a table can contain only unique (non-duplicate), nonnull values.
723 Only one primary key can be specified for a table, whether as a
724 column constraint or a table constraint.
726 The primary key constraint should name a set of columns that is
727 different from the set of columns named by any unique constraint
728 defined for the same table. (Otherwise, the unique constraint is
729 redundant and will be discarded.)
731 PRIMARY KEY enforces the same data constraints as a combination
732 of UNIQUE and NOT NULL. However, identifying a set of columns as
733 the primary key also provides metadata about the design of the
734 schema, since a primary key implies that other tables can rely
735 on this set of columns as a unique identifier for rows.
737 When placed on a partitioned table, PRIMARY KEY constraints
738 share the restrictions previously described for UNIQUE
741 Adding a PRIMARY KEY constraint will automatically create a
742 unique btree index on the column or group of columns used in the
743 constraint, or GiST if WITHOUT OVERLAPS was specified.
745 The optional INCLUDE clause adds to that index one or more
746 columns that are simply “payload”: uniqueness is not enforced on
747 them, and the index cannot be searched on the basis of those
748 columns. However they can be retrieved by an index-only scan.
749 Note that although the constraint is not enforced on included
750 columns, it still depends on them. Consequently, some operations
751 on such columns (e.g., DROP COLUMN) can cause cascaded
752 constraint and index deletion.
754 EXCLUDE [ USING index_method ] ( exclude_element WITH operator [, ... ]
755 ) index_parameters [ WHERE ( predicate ) ] #
756 The EXCLUDE clause defines an exclusion constraint, which
757 guarantees that if any two rows are compared on the specified
758 column(s) or expression(s) using the specified operator(s), not
759 all of these comparisons will return TRUE. If all of the
760 specified operators test for equality, this is equivalent to a
761 UNIQUE constraint, although an ordinary unique constraint will
762 be faster. However, exclusion constraints can specify
763 constraints that are more general than simple equality. For
764 example, you can specify a constraint that no two rows in the
765 table contain overlapping circles (see Section 8.8) by using the
766 && operator. The operator(s) are required to be commutative.
768 Exclusion constraints are implemented using an index that has
769 the same name as the constraint, so each specified operator must
770 be associated with an appropriate operator class (see
771 Section 11.10) for the index access method index_method. Each
772 exclude_element defines a column of the index, so it can
773 optionally specify a collation, an operator class, operator
774 class parameters, and/or ordering options; these are described
775 fully under CREATE INDEX.
777 The access method must support amgettuple (see Chapter 63); at
778 present this means GIN cannot be used. Although it's allowed,
779 there is little point in using B-tree or hash indexes with an
780 exclusion constraint, because this does nothing that an ordinary
781 unique constraint doesn't do better. So in practice the access
782 method will always be GiST or SP-GiST.
784 The predicate allows you to specify an exclusion constraint on a
785 subset of the table; internally this creates a partial index.
786 Note that parentheses are required around the predicate.
788 When establishing an exclusion constraint for a multi-level
789 partition hierarchy, all the columns in the partition key of the
790 target partitioned table, as well as those of all its descendant
791 partitioned tables, must be included in the constraint
792 definition. Additionally, those columns must be compared using
793 the equality operator. These restrictions ensure that
794 potentially-conflicting rows will exist in the same partition.
795 The constraint may also refer to other columns which are not a
796 part of any partition key, which can be compared using any
797 appropriate operator.
799 REFERENCES reftable [ ( refcolumn ) ] [ MATCH matchtype ] [ ON DELETE
800 referential_action ] [ ON UPDATE referential_action ] (column
802 FOREIGN KEY ( column_name [, ... ] [, PERIOD column_name ] )
803 REFERENCES reftable [ ( refcolumn [, ... ] [, PERIOD refcolumn ]
804 ) ] [ MATCH matchtype ] [ ON DELETE referential_action ] [ ON
805 UPDATE referential_action ] (table constraint) #
806 These clauses specify a foreign key constraint, which requires
807 that a group of one or more columns of the new table must only
808 contain values that match values in the referenced column(s) of
809 some row of the referenced table. If the refcolumn list is
810 omitted, the primary key of the reftable is used. Otherwise, the
811 refcolumn list must refer to the columns of a non-deferrable
812 unique or primary key constraint or be the columns of a
813 non-partial unique index.
815 If the last column is marked with PERIOD, it is treated in a
816 special way. While the non-PERIOD columns are compared for
817 equality (and there must be at least one of them), the PERIOD
818 column is not. Instead, the constraint is considered satisfied
819 if the referenced table has matching records (based on the
820 non-PERIOD parts of the key) whose combined PERIOD values
821 completely cover the referencing record's. In other words, the
822 reference must have a referent for its entire duration. This
823 column must be a range or multirange type. In addition, the
824 referenced table must have a primary key or unique constraint
825 declared with WITHOUT OVERLAPS. Finally, if the foreign key has
826 a PERIOD column_name specification the corresponding refcolumn,
827 if present, must also be marked PERIOD. If the refcolumn clause
828 is omitted, and thus the reftable's primary key constraint
829 chosen, the primary key must have its final column marked
832 For each pair of referencing and referenced column, if they are
833 of a collatable data type, then the collations must either be
834 both deterministic or else both the same. This ensures that both
835 columns have a consistent notion of equality.
837 The user must have REFERENCES permission on the referenced table
838 (either the whole table, or the specific referenced columns).
839 The addition of a foreign key constraint requires a SHARE ROW
840 EXCLUSIVE lock on the referenced table. Note that foreign key
841 constraints cannot be defined between temporary tables and
844 A value inserted into the referencing column(s) is matched
845 against the values of the referenced table and referenced
846 columns using the given match type. There are three match types:
847 MATCH FULL, MATCH PARTIAL, and MATCH SIMPLE (which is the
848 default). MATCH FULL will not allow one column of a multicolumn
849 foreign key to be null unless all foreign key columns are null;
850 if they are all null, the row is not required to have a match in
851 the referenced table. MATCH SIMPLE allows any of the foreign key
852 columns to be null; if any of them are null, the row is not
853 required to have a match in the referenced table. MATCH PARTIAL
854 is not yet implemented. (Of course, NOT NULL constraints can be
855 applied to the referencing column(s) to prevent these cases from
858 In addition, when the data in the referenced columns is changed,
859 certain actions are performed on the data in this table's
860 columns. The ON DELETE clause specifies the action to perform
861 when a referenced row in the referenced table is being deleted.
862 Likewise, the ON UPDATE clause specifies the action to perform
863 when a referenced column in the referenced table is being
864 updated to a new value. If the row is updated, but the
865 referenced column is not actually changed, no action is done.
866 Referential actions are executed as part of the data changing
867 command, even if the constraint is deferred. There are the
868 following possible actions for each clause:
871 Produce an error if the deletion or update would create a
872 foreign key constraint violation. If the constraint is
873 deferred, this error will be produced at constraint check
874 time if there still exist any referencing rows. This is
878 Produce an error if a row to be deleted or updated matches
879 a row in the referencing table. This prevents the action
880 even if the state after the action would not violate the
881 foreign key constraint. In particular, it prevents updates
882 of referenced rows to values that are distinct but compare
883 as equal. (But it does not prevent “no-op” updates that
884 update a column to the same value.)
886 In a temporal foreign key, this option is not supported.
889 Delete any rows referencing the deleted row, or update the
890 values of the referencing column(s) to the new values of
891 the referenced columns, respectively.
893 In a temporal foreign key, this option is not supported.
895 SET NULL [ ( column_name [, ... ] ) ] #
896 Set all of the referencing columns, or a specified subset
897 of the referencing columns, to null. A subset of columns
898 can only be specified for ON DELETE actions.
900 In a temporal foreign key, this option is not supported.
902 SET DEFAULT [ ( column_name [, ... ] ) ] #
903 Set all of the referencing columns, or a specified subset
904 of the referencing columns, to their default values. A
905 subset of columns can only be specified for ON DELETE
906 actions. (There must be a row in the referenced table
907 matching the default values, if they are not null, or the
908 operation will fail.)
910 In a temporal foreign key, this option is not supported.
912 If the referenced column(s) are changed frequently, it might be
913 wise to add an index to the referencing column(s) so that
914 referential actions associated with the foreign key constraint
915 can be performed more efficiently.
919 This controls whether the constraint can be deferred. A
920 constraint that is not deferrable will be checked immediately
921 after every command. Checking of constraints that are deferrable
922 can be postponed until the end of the transaction (using the SET
923 CONSTRAINTS command). NOT DEFERRABLE is the default. Currently,
924 only UNIQUE, PRIMARY KEY, EXCLUDE, and REFERENCES (foreign key)
925 constraints accept this clause. NOT NULL and CHECK constraints
926 are not deferrable. Note that deferrable constraints cannot be
927 used as conflict arbitrators in an INSERT statement that
928 includes an ON CONFLICT DO UPDATE clause.
932 If a constraint is deferrable, this clause specifies the default
933 time to check the constraint. If the constraint is INITIALLY
934 IMMEDIATE, it is checked after each statement. This is the
935 default. If the constraint is INITIALLY DEFERRED, it is checked
936 only at the end of the transaction. The constraint check time
937 can be altered with the SET CONSTRAINTS command.
941 When the constraint is ENFORCED, then the database system will
942 ensure that the constraint is satisfied, by checking the
943 constraint at appropriate times (after each statement or at the
944 end of the transaction, as appropriate). That is the default. If
945 the constraint is NOT ENFORCED, the database system will not
946 check the constraint. It is then up to the application code to
947 ensure that the constraints are satisfied. The database system
948 might still assume that the data actually satisfies the
949 constraint for optimization decisions where this does not affect
950 the correctness of the result.
952 NOT ENFORCED constraints can be useful as documentation if the
953 actual checking of the constraint at run time is too expensive.
955 This is currently only supported for foreign key and CHECK
959 This optional clause specifies the table access method to use to
960 store the contents for the new table; the method needs be an
961 access method of type TABLE. See Chapter 62 for more
962 information. If this option is not specified, the default table
963 access method is chosen for the new table. See
964 default_table_access_method for more information.
966 When creating a partition, the table access method is the access
967 method of its partitioned table, if set.
969 WITH ( storage_parameter [= value] [, ... ] ) #
970 This clause specifies optional storage parameters for a table or
971 index; see Storage Parameters below for more information. For
972 backward-compatibility the WITH clause for a table can also
973 include OIDS=FALSE to specify that rows of the new table should
974 not contain OIDs (object identifiers), OIDS=TRUE is not
978 This is backward-compatible syntax for declaring a table WITHOUT
979 OIDS, creating a table WITH OIDS is not supported anymore.
982 The behavior of temporary tables at the end of a transaction
983 block can be controlled using ON COMMIT. The three options are:
986 No special action is taken at the ends of transactions.
987 This is the default behavior.
990 All rows in the temporary table will be deleted at the end
991 of each transaction block. Essentially, an automatic
992 TRUNCATE is done at each commit. When used on a
993 partitioned table, this is not cascaded to its partitions.
996 The temporary table will be dropped at the end of the
997 current transaction block. When used on a partitioned
998 table, this action drops its partitions and when used on
999 tables with inheritance children, it drops the dependent
1002 TABLESPACE tablespace_name #
1003 The tablespace_name is the name of the tablespace in which the
1004 new table is to be created. If not specified, default_tablespace
1005 is consulted, or temp_tablespaces if the table is temporary. For
1006 partitioned tables, since no storage is required for the table
1007 itself, the tablespace specified overrides default_tablespace as
1008 the default tablespace to use for any newly created partitions
1009 when no other tablespace is explicitly specified.
1011 USING INDEX TABLESPACE tablespace_name #
1012 This clause allows selection of the tablespace in which the
1013 index associated with a UNIQUE, PRIMARY KEY, or EXCLUDE
1014 constraint will be created. If not specified, default_tablespace
1015 is consulted, or temp_tablespaces if the table is temporary.
1019 The WITH clause can specify storage parameters for tables, and for
1020 indexes associated with a UNIQUE, PRIMARY KEY, or EXCLUDE constraint.
1021 Storage parameters for indexes are documented in CREATE INDEX. The
1022 storage parameters currently available for tables are listed below. For
1023 many of these parameters, as shown, there is an additional parameter
1024 with the same name prefixed with toast., which controls the behavior of
1025 the table's secondary TOAST table, if any (see Section 66.2 for more
1026 information about TOAST). If a table parameter value is set and the
1027 equivalent toast. parameter is not, the TOAST table will use the
1028 table's parameter value. Specifying these parameters for partitioned
1029 tables is not supported, but you may specify them for individual leaf
1032 fillfactor (integer) #
1033 The fillfactor for a table is a percentage between 10 and 100.
1034 100 (complete packing) is the default. When a smaller fillfactor
1035 is specified, INSERT operations pack table pages only to the
1036 indicated percentage; the remaining space on each page is
1037 reserved for updating rows on that page. This gives UPDATE a
1038 chance to place the updated copy of a row on the same page as
1039 the original, which is more efficient than placing it on a
1040 different page, and makes heap-only tuple updates more likely.
1041 For a table whose entries are never updated, complete packing is
1042 the best choice, but in heavily updated tables smaller
1043 fillfactors are appropriate. This parameter cannot be set for
1046 toast_tuple_target (integer) #
1047 The toast_tuple_target specifies the minimum tuple length
1048 required before we try to compress and/or move long column
1049 values into TOAST tables, and is also the target length we try
1050 to reduce the length below once toasting begins. This affects
1051 columns marked as External (for move), Main (for compression),
1052 or Extended (for both) and applies only to new tuples. There is
1053 no effect on existing rows. By default this parameter is set to
1054 allow at least 4 tuples per block, which with the default block
1055 size will be 2040 bytes. Valid values are between 128 bytes and
1056 the (block size - header), by default 8160 bytes. Changing this
1057 value may not be useful for very short or very long rows. Note
1058 that the default setting is often close to optimal, and it is
1059 possible that setting this parameter could have negative effects
1060 in some cases. This parameter cannot be set for TOAST tables.
1062 parallel_workers (integer) #
1063 This sets the number of workers that should be used to assist a
1064 parallel scan of this table. If not set, the system will
1065 determine a value based on the relation size. The actual number
1066 of workers chosen by the planner or by utility statements that
1067 use parallel scans may be less, for example due to the setting
1068 of max_worker_processes.
1070 autovacuum_enabled, toast.autovacuum_enabled (boolean) #
1071 Enables or disables the autovacuum daemon for a particular
1072 table. If true, the autovacuum daemon will perform automatic
1073 VACUUM and/or ANALYZE operations on this table following the
1074 rules discussed in Section 24.1.6. If false, this table will not
1075 be autovacuumed, except to prevent transaction ID wraparound.
1076 See Section 24.1.5 for more about wraparound prevention. Note
1077 that the autovacuum daemon does not run at all (except to
1078 prevent transaction ID wraparound) if the autovacuum parameter
1079 is false; setting individual tables' storage parameters does not
1080 override that. Therefore there is seldom much point in
1081 explicitly setting this storage parameter to true, only to
1084 vacuum_index_cleanup, toast.vacuum_index_cleanup (enum) #
1085 Forces or disables index cleanup when VACUUM is run on this
1086 table. The default value is AUTO. With OFF, index cleanup is
1087 disabled, with ON it is enabled, and with AUTO a decision is
1088 made dynamically, each time VACUUM runs. The dynamic behavior
1089 allows VACUUM to avoid needlessly scanning indexes to remove
1090 very few dead tuples. Forcibly disabling all index cleanup can
1091 speed up VACUUM very significantly, but may also lead to
1092 severely bloated indexes if table modifications are frequent.
1093 The INDEX_CLEANUP parameter of VACUUM, if specified, overrides
1094 the value of this option.
1096 vacuum_truncate, toast.vacuum_truncate (boolean) #
1097 Per-table value for vacuum_truncate parameter. The TRUNCATE
1098 parameter of VACUUM, if specified, overrides the value of this
1101 autovacuum_vacuum_threshold, toast.autovacuum_vacuum_threshold
1103 Per-table value for autovacuum_vacuum_threshold parameter.
1105 autovacuum_vacuum_max_threshold, toast.autovacuum_vacuum_max_threshold
1107 Per-table value for autovacuum_vacuum_max_threshold parameter.
1109 autovacuum_vacuum_scale_factor, toast.autovacuum_vacuum_scale_factor
1111 Per-table value for autovacuum_vacuum_scale_factor parameter.
1113 autovacuum_vacuum_insert_threshold,
1114 toast.autovacuum_vacuum_insert_threshold (integer) #
1115 Per-table value for autovacuum_vacuum_insert_threshold
1116 parameter. The special value of -1 may be used to disable insert
1117 vacuums on the table.
1119 autovacuum_vacuum_insert_scale_factor,
1120 toast.autovacuum_vacuum_insert_scale_factor (floating point) #
1121 Per-table value for autovacuum_vacuum_insert_scale_factor
1124 autovacuum_analyze_threshold (integer) #
1125 Per-table value for autovacuum_analyze_threshold parameter.
1127 autovacuum_analyze_scale_factor (floating point) #
1128 Per-table value for autovacuum_analyze_scale_factor parameter.
1130 autovacuum_vacuum_cost_delay, toast.autovacuum_vacuum_cost_delay
1132 Per-table value for autovacuum_vacuum_cost_delay parameter.
1134 autovacuum_vacuum_cost_limit, toast.autovacuum_vacuum_cost_limit
1136 Per-table value for autovacuum_vacuum_cost_limit parameter.
1138 autovacuum_freeze_min_age, toast.autovacuum_freeze_min_age (integer) #
1139 Per-table value for vacuum_freeze_min_age parameter. Note that
1140 autovacuum will ignore per-table autovacuum_freeze_min_age
1141 parameters that are larger than half the system-wide
1142 autovacuum_freeze_max_age setting.
1144 autovacuum_freeze_max_age, toast.autovacuum_freeze_max_age (integer) #
1145 Per-table value for autovacuum_freeze_max_age parameter. Note
1146 that autovacuum will ignore per-table autovacuum_freeze_max_age
1147 parameters that are larger than the system-wide setting (it can
1148 only be set smaller).
1150 autovacuum_freeze_table_age, toast.autovacuum_freeze_table_age
1152 Per-table value for vacuum_freeze_table_age parameter.
1154 autovacuum_multixact_freeze_min_age,
1155 toast.autovacuum_multixact_freeze_min_age (integer) #
1156 Per-table value for vacuum_multixact_freeze_min_age parameter.
1157 Note that autovacuum will ignore per-table
1158 autovacuum_multixact_freeze_min_age parameters that are larger
1159 than half the system-wide autovacuum_multixact_freeze_max_age
1162 autovacuum_multixact_freeze_max_age,
1163 toast.autovacuum_multixact_freeze_max_age (integer) #
1164 Per-table value for autovacuum_multixact_freeze_max_age
1165 parameter. Note that autovacuum will ignore per-table
1166 autovacuum_multixact_freeze_max_age parameters that are larger
1167 than the system-wide setting (it can only be set smaller).
1169 autovacuum_multixact_freeze_table_age,
1170 toast.autovacuum_multixact_freeze_table_age (integer) #
1171 Per-table value for vacuum_multixact_freeze_table_age parameter.
1173 log_autovacuum_min_duration, toast.log_autovacuum_min_duration
1175 Per-table value for log_autovacuum_min_duration parameter.
1177 vacuum_max_eager_freeze_failure_rate,
1178 toast.vacuum_max_eager_freeze_failure_rate (floating point) #
1179 Per-table value for vacuum_max_eager_freeze_failure_rate
1182 user_catalog_table (boolean) #
1183 Declare the table as an additional catalog table for purposes of
1184 logical replication. See Section 47.6.2 for details. This
1185 parameter cannot be set for TOAST tables.
1189 PostgreSQL automatically creates an index for each unique constraint
1190 and primary key constraint to enforce uniqueness. Thus, it is not
1191 necessary to create an index explicitly for primary key columns. (See
1192 CREATE INDEX for more information.)
1194 Unique constraints and primary keys are not inherited in the current
1195 implementation. This makes the combination of inheritance and unique
1196 constraints rather dysfunctional.
1198 A table cannot have more than 1600 columns. (In practice, the effective
1199 limit is usually lower because of tuple-length constraints.)
1203 Create table films and table distributors:
1204 CREATE TABLE films (
1205 code char(5) CONSTRAINT firstkey PRIMARY KEY,
1206 title varchar(40) NOT NULL,
1207 did integer NOT NULL,
1210 len interval hour to minute
1213 CREATE TABLE distributors (
1214 did integer PRIMARY KEY GENERATED BY DEFAULT AS IDENTITY,
1215 name varchar(40) NOT NULL CHECK (name <> '')
1218 Create a table with a 2-dimensional array:
1219 CREATE TABLE array_int (
1223 Define a unique table constraint for the table films. Unique table
1224 constraints can be defined on one or more columns of the table:
1225 CREATE TABLE films (
1231 len interval hour to minute,
1232 CONSTRAINT production UNIQUE(date_prod)
1235 Define a check column constraint:
1236 CREATE TABLE distributors (
1237 did integer CHECK (did > 100),
1241 Define a check table constraint:
1242 CREATE TABLE distributors (
1245 CONSTRAINT con1 CHECK (did > 100 AND name <> '')
1248 Define a primary key table constraint for the table films:
1249 CREATE TABLE films (
1255 len interval hour to minute,
1256 CONSTRAINT code_title PRIMARY KEY(code,title)
1259 Define a primary key constraint for table distributors. The following
1260 two examples are equivalent, the first using the table constraint
1261 syntax, the second the column constraint syntax:
1262 CREATE TABLE distributors (
1268 CREATE TABLE distributors (
1269 did integer PRIMARY KEY,
1273 Assign a literal constant default value for the column name, arrange
1274 for the default value of column did to be generated by selecting the
1275 next value of a sequence object, and make the default value of modtime
1276 be the time at which the row is inserted:
1277 CREATE TABLE distributors (
1278 name varchar(40) DEFAULT 'Luso Films',
1279 did integer DEFAULT nextval('distributors_serial'),
1280 modtime timestamp DEFAULT current_timestamp
1283 Define two NOT NULL column constraints on the table distributors, one
1284 of which is explicitly given a name:
1285 CREATE TABLE distributors (
1286 did integer CONSTRAINT no_null NOT NULL,
1287 name varchar(40) NOT NULL
1290 Define a unique constraint for the name column:
1291 CREATE TABLE distributors (
1293 name varchar(40) UNIQUE
1296 The same, specified as a table constraint:
1297 CREATE TABLE distributors (
1303 Create the same table, specifying 70% fill factor for both the table
1304 and its unique index:
1305 CREATE TABLE distributors (
1308 UNIQUE(name) WITH (fillfactor=70)
1310 WITH (fillfactor=70);
1312 Create table circles with an exclusion constraint that prevents any two
1313 circles from overlapping:
1314 CREATE TABLE circles (
1316 EXCLUDE USING gist (c WITH &&)
1319 Create table cinemas in tablespace diskvol1:
1320 CREATE TABLE cinemas (
1324 ) TABLESPACE diskvol1;
1326 Create a composite type and a typed table:
1327 CREATE TYPE employee_type AS (name text, salary numeric);
1329 CREATE TABLE employees OF employee_type (
1331 salary WITH OPTIONS DEFAULT 1000
1334 Create a range partitioned table:
1335 CREATE TABLE measurement (
1336 logdate date not null,
1339 ) PARTITION BY RANGE (logdate);
1341 Create a range partitioned table with multiple columns in the partition
1343 CREATE TABLE measurement_year_month (
1344 logdate date not null,
1347 ) PARTITION BY RANGE (EXTRACT(YEAR FROM logdate), EXTRACT(MONTH FROM logdate));
1349 Create a list partitioned table:
1350 CREATE TABLE cities (
1351 city_id bigserial not null,
1354 ) PARTITION BY LIST (left(lower(name), 1));
1356 Create a hash partitioned table:
1357 CREATE TABLE orders (
1358 order_id bigint not null,
1359 cust_id bigint not null,
1361 ) PARTITION BY HASH (order_id);
1363 Create partition of a range partitioned table:
1364 CREATE TABLE measurement_y2016m07
1365 PARTITION OF measurement (
1367 ) FOR VALUES FROM ('2016-07-01') TO ('2016-08-01');
1369 Create a few partitions of a range partitioned table with multiple
1370 columns in the partition key:
1371 CREATE TABLE measurement_ym_older
1372 PARTITION OF measurement_year_month
1373 FOR VALUES FROM (MINVALUE, MINVALUE) TO (2016, 11);
1375 CREATE TABLE measurement_ym_y2016m11
1376 PARTITION OF measurement_year_month
1377 FOR VALUES FROM (2016, 11) TO (2016, 12);
1379 CREATE TABLE measurement_ym_y2016m12
1380 PARTITION OF measurement_year_month
1381 FOR VALUES FROM (2016, 12) TO (2017, 01);
1383 CREATE TABLE measurement_ym_y2017m01
1384 PARTITION OF measurement_year_month
1385 FOR VALUES FROM (2017, 01) TO (2017, 02);
1387 Create partition of a list partitioned table:
1388 CREATE TABLE cities_ab
1389 PARTITION OF cities (
1390 CONSTRAINT city_id_nonzero CHECK (city_id != 0)
1391 ) FOR VALUES IN ('a', 'b');
1393 Create partition of a list partitioned table that is itself further
1394 partitioned and then add a partition to it:
1395 CREATE TABLE cities_ab
1396 PARTITION OF cities (
1397 CONSTRAINT city_id_nonzero CHECK (city_id != 0)
1398 ) FOR VALUES IN ('a', 'b') PARTITION BY RANGE (population);
1400 CREATE TABLE cities_ab_10000_to_100000
1401 PARTITION OF cities_ab FOR VALUES FROM (10000) TO (100000);
1403 Create partitions of a hash partitioned table:
1404 CREATE TABLE orders_p1 PARTITION OF orders
1405 FOR VALUES WITH (MODULUS 4, REMAINDER 0);
1406 CREATE TABLE orders_p2 PARTITION OF orders
1407 FOR VALUES WITH (MODULUS 4, REMAINDER 1);
1408 CREATE TABLE orders_p3 PARTITION OF orders
1409 FOR VALUES WITH (MODULUS 4, REMAINDER 2);
1410 CREATE TABLE orders_p4 PARTITION OF orders
1411 FOR VALUES WITH (MODULUS 4, REMAINDER 3);
1413 Create a default partition:
1414 CREATE TABLE cities_partdef
1415 PARTITION OF cities DEFAULT;
1419 The CREATE TABLE command conforms to the SQL standard, with exceptions
1424 Although the syntax of CREATE TEMPORARY TABLE resembles that of the SQL
1425 standard, the effect is not the same. In the standard, temporary tables
1426 are defined just once and automatically exist (starting with empty
1427 contents) in every session that needs them. PostgreSQL instead requires
1428 each session to issue its own CREATE TEMPORARY TABLE command for each
1429 temporary table to be used. This allows different sessions to use the
1430 same temporary table name for different purposes, whereas the
1431 standard's approach constrains all instances of a given temporary table
1432 name to have the same table structure.
1434 The standard's definition of the behavior of temporary tables is widely
1435 ignored. PostgreSQL's behavior on this point is similar to that of
1436 several other SQL databases.
1438 The SQL standard also distinguishes between global and local temporary
1439 tables, where a local temporary table has a separate set of contents
1440 for each SQL module within each session, though its definition is still
1441 shared across sessions. Since PostgreSQL does not support SQL modules,
1442 this distinction is not relevant in PostgreSQL.
1444 For compatibility's sake, PostgreSQL will accept the GLOBAL and LOCAL
1445 keywords in a temporary table declaration, but they currently have no
1446 effect. Use of these keywords is discouraged, since future versions of
1447 PostgreSQL might adopt a more standard-compliant interpretation of
1450 The ON COMMIT clause for temporary tables also resembles the SQL
1451 standard, but has some differences. If the ON COMMIT clause is omitted,
1452 SQL specifies that the default behavior is ON COMMIT DELETE ROWS.
1453 However, the default behavior in PostgreSQL is ON COMMIT PRESERVE ROWS.
1454 The ON COMMIT DROP option does not exist in SQL.
1456 Non-Deferred Uniqueness Constraints
1458 When a UNIQUE or PRIMARY KEY constraint is not deferrable, PostgreSQL
1459 checks for uniqueness immediately whenever a row is inserted or
1460 modified. The SQL standard says that uniqueness should be enforced only
1461 at the end of the statement; this makes a difference when, for example,
1462 a single command updates multiple key values. To obtain
1463 standard-compliant behavior, declare the constraint as DEFERRABLE but
1464 not deferred (i.e., INITIALLY IMMEDIATE). Be aware that this can be
1465 significantly slower than immediate uniqueness checking.
1467 Column Check Constraints
1469 The SQL standard says that CHECK column constraints can only refer to
1470 the column they apply to; only CHECK table constraints can refer to
1471 multiple columns. PostgreSQL does not enforce this restriction; it
1472 treats column and table check constraints alike.
1476 The EXCLUDE constraint type is a PostgreSQL extension.
1478 Foreign Key Constraints
1480 The ability to specify column lists in the foreign key actions SET
1481 DEFAULT and SET NULL is a PostgreSQL extension.
1483 It is a PostgreSQL extension that a foreign key constraint may
1484 reference columns of a unique index instead of columns of a primary key
1485 or unique constraint.
1489 The NULL “constraint” (actually a non-constraint) is a PostgreSQL
1490 extension to the SQL standard that is included for compatibility with
1491 some other database systems (and for symmetry with the NOT NULL
1492 constraint). Since it is the default for any column, its presence is
1497 The SQL standard says that table and domain constraints must have names
1498 that are unique across the schema containing the table or domain.
1499 PostgreSQL is laxer: it only requires constraint names to be unique
1500 across the constraints attached to a particular table or domain.
1501 However, this extra freedom does not exist for index-based constraints
1502 (UNIQUE, PRIMARY KEY, and EXCLUDE constraints), because the associated
1503 index is named the same as the constraint, and index names must be
1504 unique across all relations within the same schema.
1508 Multiple inheritance via the INHERITS clause is a PostgreSQL language
1509 extension. SQL:1999 and later define single inheritance using a
1510 different syntax and different semantics. SQL:1999-style inheritance is
1511 not yet supported by PostgreSQL.
1515 PostgreSQL allows a table of no columns to be created (for example,
1516 CREATE TABLE foo();). This is an extension from the SQL standard, which
1517 does not allow zero-column tables. Zero-column tables are not in
1518 themselves very useful, but disallowing them creates odd special cases
1519 for ALTER TABLE DROP COLUMN, so it seems cleaner to ignore this spec
1522 Multiple Identity Columns
1524 PostgreSQL allows a table to have more than one identity column. The
1525 standard specifies that a table can have at most one identity column.
1526 This is relaxed mainly to give more flexibility for doing schema
1527 changes or migrations. Note that the INSERT command supports only one
1528 override clause that applies to the entire statement, so having
1529 multiple identity columns with different behaviors is not well
1534 The options STORED and VIRTUAL are not standard but are also used by
1535 other SQL implementations. The SQL standard does not specify the
1536 storage of generated columns.
1540 While a LIKE clause exists in the SQL standard, many of the options
1541 that PostgreSQL accepts for it are not in the standard, and some of the
1542 standard's options are not implemented by PostgreSQL.
1546 The WITH clause is a PostgreSQL extension; storage parameters are not
1551 The PostgreSQL concept of tablespaces is not part of the standard.
1552 Hence, the clauses TABLESPACE and USING INDEX TABLESPACE are
1557 Typed tables implement a subset of the SQL standard. According to the
1558 standard, a typed table has columns corresponding to the underlying
1559 composite type as well as one other column that is the
1560 “self-referencing column”. PostgreSQL does not support self-referencing
1565 The PARTITION BY clause is a PostgreSQL extension.
1569 The PARTITION OF clause is a PostgreSQL extension.
1573 ALTER TABLE, DROP TABLE, CREATE TABLE AS, CREATE TABLESPACE, CREATE