+ sequence.
[ CONSTRAINT constraint_name ]
{ NOT NULL | NULL | UNIQUE | PRIMARY KEY |
CHECK (expression) |
- REFERENCES reftable [ ( refcolumn ) ] [ MATCH FULL | MATCH PARTIAL ]
+ REFERENCES reftable [ ( refcolumn ) ] [ MATCH FULL | MATCH PARTIAL | MATCH SIMPLE ]
[ ON DELETE action ] [ ON UPDATE action ] }
[ DEFERRABLE | NOT DEFERRABLE ] [ INITIALLY DEFERRED | INITIALLY IMMEDIATE ]
PRIMARY KEY ( column_name [, ... ] ) |
CHECK ( expression ) |
FOREIGN KEY ( column_name [, ... ] ) REFERENCES reftable [ ( refcolumn [, ... ] ) ]
- [ MATCH FULL | MATCH PARTIAL ] [ ON DELETE action ] [ ON UPDATE action ] }
+ [ MATCH FULL | MATCH PARTIAL | MATCH SIMPLE ] [ ON DELETE action ] [ ON UPDATE action ] }
[ DEFERRABLE | NOT DEFERRABLE ] [ INITIALLY DEFERRED | INITIALLY IMMEDIATE ]
If a schema name is given (for example, CREATE TABLE
myschema.mytable ...>) then the table is created in the
- specified schema. Otherwise it is created in the current schema (the one
- at the front of the search path; see CURRENT_SCHEMA()>).
- TEMP tables exist in a special schema, so a schema name may not be
- given when creating a TEMP table.
+ specified schema. Otherwise it is created in the current schema.
+ Temporary tables exist in a special schema, so a schema name may not be
+ given when creating a temporary table.
The table name must be distinct from the name of any other table,
sequence, index, or view in the same schema.
CREATE TABLE also automatically creates a data
- type that represents the tuple type (structure type) corresponding
+ type that represents the composite type corresponding
to one row of the table. Therefore, tables cannot have the same
name as any existing data type in the same schema.
The optional constraint clauses specify constraints (or tests) that
new or updated rows must satisfy for an insert or update operation
- to succeed. A constraint is a named rule: an SQL object which
- helps define valid sets of values by putting limits on the results
- of insert, update, or delete operations performed on a table.
+ to succeed. A constraint is an SQL object that helps define the
+ set of valid values in the table in various ways.
The DEFAULT> clause assigns a default data value for
the column whose column definition it appears within. The value
- is any variable-free expression (subselects and cross-references
+ is any variable-free expression (subqueries and cross-references
to other columns in the current table are not allowed). The
data type of the default expression must match the data type of the
column.
The default expression will be used in any insert operation that
does not specify a value for the column. If there is no default
- for a column, then the default is NULL.
+ for a column, then the default is null.
- WITH OIDS> or WITHOUT OIDS>
+ WITH OIDS>
+ WITHOUT OIDS>
This optional clause specifies whether rows of the new table
NOT NULL>
- The column is not allowed to contain NULL values.
+ The column is not allowed to contain null values.
NULL>
- The column is allowed to contain NULL values. This is the default.
+ The column is allowed to contain null values. This is the default.
- The UNIQUE constraint specifies a rule that a
+ The UNIQUE constraint specifies that a
group of one or more distinct columns of a table may contain
only unique values. The behavior of the unique table constraint
is the same as that for column constraints, with the additional
- For the purpose of a unique constraint, NULL values are not
+ For the purpose of a unique constraint, null values are not
considered equal.
The primary key constraint specifies that a column or columns of a table
- may contain only unique (non-duplicate), non-NULL values.
+ may contain only unique (non-duplicate), nonnull values.
Technically, PRIMARY KEY is merely a
combination of UNIQUE> and NOT NULL>, but
identifying a set of columns as primary key also provides
- meta-data about the design of the schema, as a primary key
+ metadata about the design of the schema, as a primary key
implies that other tables
may rely on this set of columns as a unique identifier for rows.
CHECK (expression)
- CHECK> clauses specify integrity constraints or tests
- which new or updated rows must satisfy for an insert or update
- operation to succeed. Each constraint must be an expression
- producing a Boolean result. A condition appearing within a
- column definition should reference that column's value only,
- while a condition appearing as a table constraint may reference
- multiple columns.
+ The CHECK> clause specifies an expression producing a
+ Boolean result which new or updated rows must satisfy for an
+ insert or update operation to succeed. A check constraint
+ specified as a column constraint should reference that column's
+ value only, while an expression appearing in a table constraint
+ may reference multiple columns.
Currently, CHECK expressions cannot contain
- subselects nor refer to variables other than columns of the
+ subqueries nor refer to variables other than columns of the
current row.
-
- The REFERENCES column constraint specifies
+ Theses clauses specify a foreign key constraint, which specifies
that a group of one or more columns of the new table must only
contain values which match against values in the referenced
column(s) refcolumn
- A value added to these columns is matched against the values of
- the referenced table and referenced columns using the given
- match type. There are three match types: MATCH
- FULL>, MATCH PARTIAL>, and a default match type if
- none is specified. MATCH FULL> will not allow one
- column of a multicolumn foreign key to be NULL unless all
- foreign key columns are NULL. The default match type allows some
- foreign key columns to be NULL while other parts of the foreign
- key are not NULL. MATCH PARTIAL> is not yet
- implemented.
+ A value inserted into these columns is matched against the
+ values of the referenced table and referenced columns using the
+ given match type. There are three match types: MATCH
+ FULL>, MATCH PARTIAL>, and MATCH
+ SIMPLE, which is also the default. MATCH
+ FULL> will not allow one column of a multicolumn foreign key
+ to be null unless all foreign key columns are null.
+ MATCH SIMPLE allows some foreign key columns
+ to be null while other parts of the foreign key are not
+ null. MATCH PARTIAL> is not yet implemented.
In addition, when the data in the referenced columns is changed,
certain actions are performed on the data in this table's
columns. The ON DELETE clause specifies the
- action to do when a referenced row in the referenced table is
+ action to perform when a referenced row in the referenced table is
being deleted. Likewise, the ON UPDATE
clause specifies the action to perform when a referenced column
in the referenced table is being updated to a new value. If the
SET NULL
- Set the referencing column values to NULL.
+ Set the referencing column values to null.
+
If primary key column is updated frequently, it may be wise to
- add an index to the REFERENCES column so that
- NO ACTION and CASCADE
- actions associated with the REFERENCES
- column can be more efficiently performed.
+ add an index to the foreign key column so that NO
+ ACTION and CASCADE actions
+ associated with the foreign key column can be more efficiently
+ performed.
-
- DEFERRABLE or NOT DEFERRABLE
+ DEFERRABLE
+ NOT DEFERRABLE
This controls whether the constraint can be deferred. A
- INITIALLY IMMEDIATE or INITIALLY DEFERRED
+ INITIALLY IMMEDIATE
+ INITIALLY DEFERRED
If a constraint is deferrable, this clause specifies the default
Diagnostics
-
-
-
-
-
- CREATE TABLE
-
-
-
-
-
- Message returned if table is successfully created.
-
-
-
-
-
-
-
-
-
- ERROR
-
-
-
-
-
- Message returned if table creation failed. This is usually
- accompanied by some descriptive text, such as:
-
ERROR: Relation '
- class="parameter">table' already
- exists, which occurs at run time if the table
- specified already exists in the database.
-
-
-
-
+
+
+ CREATE TABLE
+
+ Message returned if the table was successfully created.
+
+
+
+
-
- The SQL92 standard says that CHECK> column constraints
- may only refer to the column they apply to; only
- CHECK> table constraints may refer to multiple
- columns.
PostgreSQL does not enforce
- this restriction; it treats column and table check constraints
- alike.
-
-
-
Unique constraints and primary keys are not inherited in the
CREATE TABLE films (
- code CHARACTER(5) CONSTRAINT firstkey PRIMARY KEY,
- title CHARACTER VARYING(40) NOT NULL,
- did DECIMAL(3) NOT NULL,
- date_prod DATE,
- kind CHAR(10),
- len INTERVAL HOUR TO MINUTE
+ code char(5) CONSTRAINT firstkey PRIMARY KEY,
+ title varchar(40) NOT NULL,
+ did integer NOT NULL,
+ date_prod date,
+ kind varchar(10),
+ len interval hour to minute
);
CREATE TABLE distributors (
- did DECIMAL(3) PRIMARY KEY DEFAULT NEXTVAL('serial'),
- name VARCHAR(40) NOT NULL CHECK (name <> '')
+ did integer PRIMARY KEY DEFAULT nextval('serial'),
+ name varchar(40) NOT NULL CHECK (name <> '')
);
CREATE TABLE array (
- vector INT[][]
+ vector int[][]
);
- Define a unique table constraint for the table films. Unique table
- constraints can be defined on one or more columns of the table:
+ Define a unique table constraint for the table
+ films. Unique table constraints can be defined
+ on one or more columns of the table.
CREATE TABLE films (
- code CHAR(5),
- title VARCHAR(40),
- did DECIMAL(3),
- date_prod DATE,
- kind VARCHAR(10),
- len INTERVAL HOUR TO MINUTE,
+ code char(5),
+ title varchar(40),
+ did integer,
+ date_prod date,
+ kind varchar(10),
+ len interval hour to minute,
CONSTRAINT production UNIQUE(date_prod)
);
CREATE TABLE distributors (
- did DECIMAL(3) CHECK (did > 100),
- name VARCHAR(40)
+ did integer CHECK (did > 100),
+ name varchar(40)
);
CREATE TABLE distributors (
- did DECIMAL(3),
- name VARCHAR(40)
+ did integer,
+ name varchar(40)
CONSTRAINT con1 CHECK (did > 100 AND name <> '')
);
CREATE TABLE films (
- code CHAR(5),
- title VARCHAR(40),
- did DECIMAL(3),
- date_prod DATE,
- kind VARCHAR(10),
- len INTERVAL HOUR TO MINUTE,
+ code char(5),
+ title varchar(40),
+ did integer,
+ date_prod date,
+ kind varchar(10),
+ len interval hour to minute,
CONSTRAINT code_title PRIMARY KEY(code,title)
);
CREATE TABLE distributors (
- did DECIMAL(3),
- name CHAR VARYING(40),
+ did integer,
+ name varchar(40),
PRIMARY KEY(did)
);
CREATE TABLE distributors (
- did DECIMAL(3) PRIMARY KEY,
- name VARCHAR(40)
+ did integer PRIMARY KEY,
+ name varchar(40)
);
This assigns a literal constant default value for the column
- name, and arranges for the default value of
- column did to be generated by selecting the next
- value of a sequence object. The default value of
- modtime will be the time at which the row is
+ name, arranges for the default value of column
+ did to be generated by selecting the next value
+ of a sequence object, and makes the default value of
+ modtime be the time at which the row is
inserted.
CREATE TABLE distributors (
- name VARCHAR(40) DEFAULT 'luso films',
- did INTEGER DEFAULT NEXTVAL('distributors_serial'),
- modtime TIMESTAMP DEFAULT CURRENT_TIMESTAMP
+ name varchar(40) DEFAULT 'Luso Films',
+ did integer DEFAULT nextval('distributors_serial'),
+ modtime timestamp DEFAULT current_timestamp
);
CREATE TABLE distributors (
- did DECIMAL(3) CONSTRAINT no_null NOT NULL,
- name VARCHAR(40) NOT NULL
+ did integer CONSTRAINT no_null NOT NULL,
+ name varchar(40) NOT NULL
);
CREATE TABLE distributors (
- did DECIMAL(3),
- name VARCHAR(40) UNIQUE
+ did integer,
+ name varchar(40) UNIQUE
);
CREATE TABLE distributors (
- did DECIMAL(3),
- name VARCHAR(40),
+ did integer,
+ name varchar(40),
UNIQUE(name)
);
The CREATE TABLE command conforms to SQL92
- and to a subset of SQL99, with exceptions listed below and in the
- descriptions above.
+ and to a subset of SQL99, with exceptions listed below.
Although the syntax of CREATE TEMPORARY TABLE
- resembles that of SQL92, the effect is not the same. In the standard,
+ resembles that of SQL standard, the effect is not the same. In the standard,
temporary tables are defined just once and automatically exist (starting
with empty contents) in every session that needs them.
requires each session to issue its own CREATE TEMPORARY
TABLE command for each temporary table to be used. This allows
different sessions to use the same temporary table name for different
- purposes, whereas the spec's approach constrains all instances of a
+ purposes, whereas the standard's approach constrains all instances of a
given temporary table name to have the same table structure.
-
- The spec-mandated behavior of temporary tables is widely ignored.
-
PostgreSQL's behavior on this point is similar
- to that of several other RDBMSs.
-
-
+ The behavior of temporary tables mandated by the standard is
+ widely ignored.
PostgreSQL's behavior
+ on this point is similar to that of several other SQL databases.
+
- SQL92's distinction between global and local temporary tables
+ The standard's distinction between global and local temporary tables
is not in
PostgreSQL, since that distinction
depends on the concept of modules, which
PostgreSQL does not have.
The ON COMMIT clause for temporary tables
- also resembles SQL92, but has some differences.
- If the ON COMMIT> clause is omitted, SQL92 specifies that the
+ also resembles the SQL standard, but has some differences.
+ If the ON COMMIT> clause is omitted, SQL specifies that the
default behavior is ON COMMIT DELETE ROWS>. However, the
default behavior in
PostgreSQL is
ON COMMIT PRESERVE ROWS. The ON COMMIT
- DROP option does not exist in SQL92.
+ DROP option does not exist in SQL.
-
NULL Constraint
+
Column Check Constraints
- The NULL> constraint
(actually a
- non-constraint) is a
PostgreSQL
- extension to SQL92 that is included for compatibility with some
- other RDBMSs (and for symmetry with the NOT
- NULL constraint). Since it is the default for any
- column, its presence is simply noise.
+ The SQL standard says that CHECK> column constraints
+ may only refer to the column they apply to; only CHECK>
+ table constraints may refer to multiple columns.
+
PostgreSQL does not enforce this
+ restriction; it treats column and table check constraints alike.
-
-
-
Assertions
-
- An assertion is a special type of integrity constraint and shares
- the same namespace as other constraints. However, an assertion is
- not necessarily dependent on one particular table as constraints
- are, so SQL92 provides the CREATE ASSERTION
- statement as an alternate method for defining a constraint:
-
-CREATE ASSERTION name CHECK ( condition )
-
-
+
+
NULL Constraint
-
PostgreSQL> does not implement assertions at present.
+ The NULL> constraint
(actually a
+ non-constraint) is a
PostgreSQL
+ extension to the SQL standard that is included for compatibility with some
+ other database systems (and for symmetry with the NOT
+ NULL constraint). Since it is the default for any
+ column, its presence is simply noise.
-
-
Inheritance
CREATE [ [ LOCAL ] { TEMPORARY | TEMP } ] TABLE table_name [ (column_name [, ...] ) ]
AS query
-
+
-
- 2001-03-20
-
-
- Description
-
+
Description
+
CREATE TABLE AS creates a table and fills it
with data computed by a SELECT command. The
column_name
- The name of a column in the new table. Multiple column names can
- be specified using a comma-delimited list of column names. If
- column names are not provided, they are taken from the output
- column names of the query.
+ The name of a column in the new table. If column names are not
+ provided, they are taken from the output column names of the
+ query.
This command is modeled after an
Oracle
feature. There is no command with equivalent functionality in
- SQL92 or SQL99. However, a combination of CREATE
+ the SQL standard. However, a combination of CREATE
TABLE and INSERT ... SELECT can
accomplish the same thing with little more effort.
-
-
History
-
- The CREATE TABLE AS command has been available
-
-
-
See Also
CREATE TRIGGER
SQL - Language Statements
+
-
- CREATE TRIGGER
-
-
- define a new trigger
-
+ CREATE TRIGGER
+ define a new trigger
+
-
- 2000-03-25
-
-
+
CREATE TRIGGER name { BEFORE | AFTER } { event [ OR ... ] }
ON table [ FOR [ EACH ] { ROW | STATEMENT } ]
EXECUTE PROCEDURE func ( arguments )
-
-
-
-
- 1998-09-21
-
-
- Inputs
-
-
-
-
- name
-
- The name to give the new trigger. This must be distinct from the name
- of any other trigger for the same table.
-
-
-
-
-
- BEFORE
- AFTER
-
- Determines whether the function is called before or after the
- event.
-
-
-
-
-
- event
-
- One of INSERT, DELETE or
- UPDATE; this specifies the event that will
- fire the trigger. Multiple events can be specified using
- OR.
-
-
-
-
- table
-
- The name (optionally schema-qualified) of the table the
- trigger is for.
-
-
-
-
-
- FOR EACH ROW
- FOR EACH STATEMENT
-
-
- This specifies whether the trigger procedure should be fired
- once for every row affected by the trigger event, or just once
- per SQL statement. If neither is specified, FOR EACH
- STATEMENT is the default.
-
-
-
-
-
- func
-
- A user-supplied function that is declared as taking no arguments
- and returning type trigger>.
-
-
-
-
- arguments
-
- An optional comma-separated list of arguments to be provided to
- the function when the trigger is executed, along with the standard
- trigger data such as old and new tuple contents. The arguments
- are literal string constants. Simple names and numeric constants
- may be written here too, but they will all be converted to
- strings. Note that these arguments are not provided as normal
- function parameters (since a trigger procedure must be declared to
- take zero parameters), but are instead accessed through the
- TG_ARGV array.
-
-
-
-
-
-
-
-
-
- 1998-09-21
-
-
- Outputs
-
-
-
-
-
-CREATE TRIGGER
-
-
- This message is returned if the trigger is successfully created.
-
-
-
-
-
-
+
-
-
- 1998-09-21
-
-
- Description
-
+
+
Description
- CREATE TRIGGER will enter a new trigger into the current
- database. The trigger will be associated with the relation
- table and will execute
- the specified function func.
+ CREATE TRIGGER creates a new trigger. The
+ trigger will be associated with the specified table and will
+ execute the specified function e
+ class="parameter">func when certain events occur.
- The trigger can be specified to fire either before BEFORE the
- operation is attempted on a tuple (before constraints are checked and
- the INSERT, UPDATE or
- DELETE is attempted) or AFTER the operation has
- been attempted (e.g., after constraints are checked and the
- INSERT, UPDATE or
- DELETE has completed). If the trigger fires before
- the event, the trigger may skip the operation for the current tuple,
- or change the tuple being inserted (for INSERT and
- UPDATE operations only). If the trigger fires
- after the event, all changes, including the last insertion, update,
- or deletion, are visible
to the trigger.
+ The trigger can be specified to fire either before before the
+ operation is attempted on a row (before constraints are checked and
+ the INSERT, UPDATE, or
+ DELETE is attempted) or after the operation has
+ completed (after constraints are checked and the
+ INSERT, UPDATE, or
+ DELETE has completed). If the trigger fires
+ before the event, the trigger may skip the operation for the
+ current row, or change the row being inserted (for
+ INSERT and UPDATE operations
+ only). If the trigger fires after the event, all changes, including
+ the last insertion, update, or deletion, are visible
+ to the trigger.
- A trigger that executes FOR EACH ROW of the
- specified operation is called once for every row that the operation
- modifies. For example, a DELETE that affects 10
- rows will cause any ON DELETE triggers on the
- target relation to be called 10 separate times, once for each
- deleted tuple. In contrast, a trigger that executes FOR
- EACH STATEMENT of the specified operation only executes
- once for any given operation, regardless of how many rows it
- modifies (in particular, an operation that modifies zero rows will
- still result in the execution of any applicable FOR EACH
- STATEMENT triggers).
+ A trigger that is marked FOR EACH ROW is called
+ once for every row that the operation modifies. For example, a
+ DELETE that affects 10 rows will cause any
+ ON DELETE triggers on the target relation to be
+ called 10 separate times, once for each deleted row. In contrast, a
+ trigger that is marked FOR EACH STATEMENT only
+ executes once for any given operation, regardless of how many rows
+ it modifies (in particular, an operation that modifies zero rows
+ will still result in the execution of any applicable FOR
+ EACH STATEMENT triggers).
- Refer to server-programming"> for more information.
+ Refer to triggers"> for more information about triggers.
+
+
+
Parameters
+
+
+
+ name
+
+ The name to give the new trigger. This must be distinct from
+ the name of any other trigger for the same table.
+
+
+
+
+
+ BEFORE
+ AFTER
+
+ Determines whether the function is called before or after the
+ event.
+
+
+
+
+
+ event
+
+ One of INSERT, UPDATE, or
+ DELETE; this specifies the event that will
+ fire the trigger. Multiple events can be specified using
+ OR.
+
+
+
+
+
+ table
+
+ The name (optionally schema-qualified) of the table the trigger
+ is for.
+
+
+
+
+
+ FOR EACH ROW
+ FOR EACH STATEMENT
+
+
+ This specifies whether the trigger procedure should be fired
+ once for every row affected by the trigger event, or just once
+ per SQL statement. If neither is specified, FOR EACH
+ STATEMENT is the default.
+
+
+
+
+
+ func
+
+ A user-supplied function that is declared as taking no arguments
+ and returning type trigger>, which is executed when
+ the trigger fires.
+
+
+
+
+
+ arguments
+
+ An optional comma-separated list of arguments to be provided to
+ the function when the trigger is executed. The arguments are
+ literal string constants. Simple names and numeric constants
+ may be written here, too, but they will all be converted to
+ strings. Please check the description of the implementation
+ language of the trigger function about how the trigger arguments
+ are accessible within the function; it may be different from
+ normal function arguments.
+
+
+
+
+
+
+
+
Diagnostics
+
+
+
+ CREATE TRIGGER
+
+ Message returned if the trigger was successfully created.
+
+
+
+
+
Notes
necessary to declare trigger functions as returning the placeholder
type opaque>, rather than trigger>. To support loading
of old dump files, CREATE TRIGGER> will accept a function
- declared as returning opaque>, but it will issue a NOTICE and
+ declared as returning opaque>, but it will issue a notice and
change the function's declared return type to trigger>.
- Refer to the command for
- information on how to remove triggers.
+ Use
+ endterm="sql-droptrigger-title"> to remove a trigger.
Examples
- Check if the specified distributor code exists in the distributors
- table before appending or updating a row in the table films:
-
-CREATE TRIGGER if_dist_exists
- BEFORE INSERT OR UPDATE ON films FOR EACH ROW
- EXECUTE PROCEDURE check_primary_key ('did', 'distributors', 'did');
-
-
-
- Before cancelling a distributor or updating its code, remove every
- reference to the table films:
-CREATE TRIGGER if_film_exists
- BEFORE DELETE OR UPDATE ON distributors FOR EACH ROW
- EXECUTE PROCEDURE check_foreign_key (1, 'CASCADE', 'did', 'films', 'did');
-
-
-
- The second example can also be done by using a foreign key,
- constraint as in:
-
-CREATE TABLE distributors (
- did DECIMAL(3),
- name VARCHAR(40),
- CONSTRAINT if_film_exists
- FOREIGN KEY(did) REFERENCES films
- ON UPDATE CASCADE ON DELETE CASCADE
-);
-
+ contains a complete example.
Compatibility
-
-
- SQL92
+ The CREATE TRIGGER statement in
+
PostgreSQL implements a subset of the
+ SQL99 standard. (There are no provisions for triggers in SQL92.)
+ The following functionality is missing:
+
+
- There is no
CREATE TRIGGER statement in
SQL92.
+ SQL99 allows triggers to fire on updates to specific columns
+ (e.g., AFTER UPDATE OF col1, col2).
-
-
- SQL99
- The CREATE TRIGGER statement in
-
PostgreSQL implements a subset of the
- SQL99 standard. The following functionality is missing:
-
-
- SQL99 allows triggers to fire on updates to specific columns
- (e.g., AFTER UPDATE OF col1, col2).
-
-
-
-
- SQL99 allows you to define aliases for the old
- and new
rows or tables for use in the definition
- of the triggered action (e.g., CREATE TRIGGER ... ON
- tablename REFERENCING OLD ROW AS somename NEW ROW AS
- othername ...). Since
-
PostgreSQL allows trigger
- procedures to be written in any number of user-defined
- languages, access to the data is handled in a
- language-specific way.
-
-
-
-
-
PostgreSQL only allows the
- execution of a stored procedure for the triggered action.
- SQL99 allows the execution of a number of other SQL commands,
- such as CREATE TABLE as triggered action.
- This limitation is not hard to work around by creating a
- stored procedure that executes these commands.
-
-
-
-
-
- SQL99 specifies that multiple triggers should be fired in
- time-of-creation order.
PostgreSQL
- uses name order, which was judged more convenient to work with.
+ SQL99 allows you to define aliases for the old
+ and new
rows or tables for use in the definition
+ of the triggered action (e.g., CREATE TRIGGER ... ON
+ tablename REFERENCING OLD ROW AS somename NEW ROW AS othername
+ allows trigger procedures to be written in any number of
+ user-defined languages, access to the data is handled in a
+ language-specific way.
+
+
- The ability to specify multiple actions for a single trigger
- using
OR is a
PostgreSQL>
- extension of the SQL standard.
+
PostgreSQL only allows the execution
+ of a user-defined function for the triggered action. SQL99
+ allows the execution of a number of other SQL commands, such as
+ CREATE TABLE as triggered action. This
+ limitation is not hard to work around by creating a user-defined
+ function that executes the desired commands.
-
-
+
+
+
+ SQL99 specifies that multiple triggers should be fired in
+ time-of-creation order.
PostgreSQL uses
+ name order, which was judged more convenient to work with.
+
+
+ The ability to specify multiple actions for a single trigger using
+
OR is a
PostgreSQL> extension of
+ the SQL standard.
+
CREATE TYPE
SQL - Language Statements
+
-
- CREATE TYPE
-
-
- define a new data type
-
+ CREATE TYPE
+ define a new data type
+
-
- 1999-07-20
-
-
-CREATE TYPE typename ( INPUT = input_function, OUTPUT = output_function
- , INTERNALLENGTH = {
- class="parameter">internallength | VARIABLE }
+
+CREATE TYPE typename (
+ INPUT = input_function, OUTPUT = output_function
+ , INTERNALLENGTH = { internallength | VARIABLE }
[ , DEFAULT = default ]
[ , ELEMENT = element ] [ , DELIMITER = delimiter ]
[ , PASSEDBYVALUE ]
)
CREATE TYPE typename AS
- ( column_name data_type [, ... ] )
-
-
-
-
- 1998-09-21
-
-
- Inputs
-
-
-
-
- typename
-
- The name (optionally schema-qualified) of a type to be created.
-
-
-
-
-
- internallength
-
- A literal value, which specifies the internal length of
- the new type.
-
-
-
-
-
- input_function
-
- The name of a function, created by
- CREATE FUNCTION, which
- converts data from its external form to the type's
- internal form.
-
-
-
-
-
- output_function
-
- The name of a function, created by
- CREATE FUNCTION, which
- converts data from its internal form to a form suitable
- for display.
-
-
-
-
-
- element
-
- The type being created is an array; this specifies
- the type of the array elements.
-
-
-
-
-
- delimiter
-
- The delimiter character to be used between values in arrays made
- of this type.
-
-
-
-
-
- default
-
- The default value for the data type. Usually this is omitted,
- so that the default is NULL.
-
-
-
-
-
- alignment
-
- Storage alignment requirement of the data type. If specified, must
- be char, int2,
- int4, or double;
- the default is int4.
-
-
-
-
-
- storage
-
- Storage technique for the data type. If specified, must
- be plain, external,
- extended, or main;
- the default is plain.
-
-
-
-
-
- column_name
-
- The name of a column of the composite type.
-
-
-
-
-
- data_type
-
- The name of an existing data type.
-
-
-
-
-
-
-
-
-
-
- 1998-09-21
-
-
- Outputs
-
-
-
-
-
-CREATE TYPE
-
-
- Message returned if the type is successfully created.
-
-
-
-
-
-
+ ( attribute_name data_type [, ... ] )
+
-
-
- 1998-09-21
-
-
- Description
-
+
+
Description
- CREATE TYPE allows the user to register a new data
- t
ype with PostgreSQL> for use in the current data base.
- The user who defines a type becomes its owner.
+ CREATE TYPE registers a new data type for use in
+ the current data base. The user who defines a type becomes its
+ owner.
- If a schema name is given then the type is created in the
- specified schema. Otherwise it is created in the current schema (the one
- at the front of the search path; see CURRENT_SCHEMA()>).
- The type name must be distinct from the name of any existing type or
- domain in the same schema. (Because tables have associated data types,
- type names also must not conflict with table names in the same schema.)
+ If a schema name is given then the type is created in the specified
+ schema. Otherwise it is created in the current schema. The type
+ name must be distinct from the name of any existing type or domain
+ in the same schema. (Because tables have associated data types,
+ the type name must also be distinct from the name of any existing
+ table in the same schema.)
(scalar type). It requires the
registration of two functions (using CREATE
FUNCTION) before defining the
- type. The representation of a new base type is determined by
+ type. The internal representation of the new base type is determined by
input_function, which
- converts the type's external representation to an internal
+ converts the type's external representation to an internal
representation usable by the
- operators and functions defined for the type. Naturally,
+ operators and functions defined for the type.
output_function
performs the reverse transformation. The input function may be
declared as taking one argument of type cstring,
or as taking three arguments of types
- cstring, OID, int4.
- (The first argument is the input text as a C string, the second
+ cstring, oid, integer.
+ The first argument is the input text as a C string, the second
argument is the element type in case this is an array type,
- and the third is the typmod> of the destination column, if known.)
+ and the third is the typmod> of the destination column, if known.
It should return a value of the data type itself.
The output function may be
declared as taking one argument of the new data type, or as taking
- two arguments of which the second is type OID.
- (The second argument is again the array element type for array types.)
+ two arguments of which the second is type oid.
+ The second argument is again the array element type for array types.
The output function should return type cstring.
You should at this point be wondering how the input and output functions
- can be declared to have results or inputs of the new type, when they have
+ can be declared to have results or arguments of the new type, when they have
to be created before the new type can be created. The answer is that the
input function must be created first, then the output function, then the
data type.
PostgreSQL will first see the name of the new
data type as the return type of the input function. It will create a
shell> type, which is simply a placeholder entry in
- pg_type>, and link the input function definition to the shell
+ the system catalog, and link the input function definition to the shell
type. Similarly the output function will be linked to the (now already
existing) shell type. Finally, CREATE TYPE> replaces the
shell entry with a complete type definition, and the new type can be used.
-
- In
PostgreSQL versions before 7.3, it was
- customary to avoid creating a shell type by replacing the functions'
- forward references to the type name with the placeholder pseudo-type
- OPAQUE>. The cstring> inputs and
- results also had to be declared as OPAQUE> before 7.3.
- To support loading
- of old dump files, CREATE TYPE> will accept functions
- declared using opaque>, but it will issue a NOTICE and
- change the function's declaration to use the correct types.
-
-
-
- New base data types can be fixed length, in which case
+ Base data types can be fixed-length, in which case
internallength is a
positive integer, or variable length, indicated by setting
internallength
- to <option>VARIABLE>. (Internally, this is represented
+ to <literal>VARIABLE>. (Internally, this is represented
by setting typlen> to -1.) The internal representation of all
- variable-length types must start with an integer giving the total
+ variable-length types must start with a 4-byte integer giving the total
length of this value of the type.
- To indicate that a type is an array,
- specify the type of the array
- elements using the
- an array of 4-byte integers ("int4"), specify
- More details about array types appear below.
+ To indicate that a type is an array, specify the type of the array
+ elements using the ELEMENT> key word. For example, to
+ define an array of 4-byte integers (int4), specify
+ ELEMENT = int4 More details about array types
+ appear below.
representation of arrays of this type,
class="parameter">delimiter can be
set to a specific character. The default delimiter is the comma
- (','). Note that the delimiter is associated
+ (,). Note that the delimiter is associated
with the array element type, not the array type itself.
A default value may be specified, in case a user wants columns of the
- data type to default to something other than NULL.
- Specify the default with the <option>DEFAULT keyword.
- (Such a default may be overridden by an explicit <option>DEFAULT>
+ data type to default to something other than the null value.
+ Specify the default with the <literal>DEFAULT key word.
+ (Such a default may be overridden by an explicit <literal>DEFAULT>
clause attached to a particular column.)
- The optional flag, , indicates that
- values of this data type are passed
- by value rather than by reference. Note that you
- may not pass by value types whose internal representation is
- longer than the width of the Datum> type (four bytes on
- most machines, eight bytes on a few).
+ The optional flag PASSEDBYVALUE indicates that
+ values of this data type are passed by value rather than by
+ reference. You may not pass by value types whose internal
+ representation is larger than the size of the Datum> type
+ (4 bytes on most machines, 8 bytes on a few).
- The alignment keyword
+ The alignment parameter
specifies the storage alignment required for the data type. The
allowed values equate to alignment on 1, 2, 4, or 8 byte boundaries.
Note that variable-length types must have an alignment of at least
- The storage keyword
- allows selection of storage strategies for variable-length data types
- (only plain is allowed for fixed-length types).
- plain disables TOAST for the data type: it will always
- be stored in-line and not compressed.
- extended gives full TOAST capability: the system will
- first try to compress a long data value, and will move the value out of
+ The storage parameter
+ allows selection of storage strategies for variable-length data
+ types. (Only plain is allowed for fixed-length
+ types.) plain specifies that data of the type
+ will always be stored in-line and not compressed.
+ extended specifies that the system will first
+ try to compress a long data value, and will move the value out of
the main table row if it's still too long.
- external allows the value to be moved out of the main
- table, but the system will not try to compress it.
- main allows compression, but discourages moving the
- value out of the main table. (Data items with this storage method may
- still be moved out of the main table if there is no other way to make
- a row fit, but they will be kept in the main table preferentially over
- extended and external items.)
+ external allows the value to be moved out of the
+ main table, but the system will not try to compress it.
+ main allows compression, but discourages moving
+ the value out of the main table. (Data items with this storage
+ strategy may still be moved out of the main table if there is no
+ other way to make a row fit, but they will be kept in the main
+ table preferentially over extended and
+ external items.)
The second form of CREATE TYPE
creates a composite type.
- The composite type is specified by a list of column names and data types.
+ The composite type is specified by a list of attribute names and data types.
This is essentially the same as the row type
of a table, but using CREATE TYPE avoids the need to
create an actual table when all that is wanted is to define a type.
- You might reasonably ask why is there
an
- option, if the system makes the correct array type automatically?
+ You might reasonably ask why there is an
+ option, if the system makes the correct array type automatically.
The only case where it's useful to use
- making a fixed-length type that happens to be internally an array of N
- identical things, and you want to allow the N things to be accessed
+ making a fixed-length type that happens to be internally an array of a number of
+ identical things, and you want to allow these things to be accessed
directly by subscripting, in addition to whatever operations you plan
to provide for the type as a whole. For example, type name>
- allows its constituent char>s to be accessed this way.
- A 2-D point> type could allow its two component floats to be
+ allows its constituent char> elements to be accessed this way.
+ A 2-D point> type could allow its two component numbers to be
accessed like point[0]> and point[1]>.
Note that
this facility only works for fixed-length types whose internal form
- is exactly a sequence of N identical fixed-length fields. A subscriptable
+ is exactly a sequence of identical fixed-length fields. A subscriptable
variable-length type must have the generalized internal representation
used by array_in> and array_out>.
For historical reasons (i.e., this is clearly wrong but it's far too
+
+
+
Parameter
+
+
+
+ typename
+
+ The name (optionally schema-qualified) of a type to be created.
+
+
+
+
+
+ internallength
+
+ A numeric constant that specifies the internal length of the new
+ type.
+
+
+
+
+
+ input_function
+
+ The name of a function that converts data from the type's
+ external form to the its internal form.
+
+
+
+
+
+ output_function
+
+ The name of a function that converts data from the type's
+ internal form to a form suitable for display.
+
+
+
+
+
+ element
+
+ The type being created is an array; this specifies the type of
+ the array elements.
+
+
+
+
+
+ delimiter
+
+ The delimiter character to be used between values in arrays made
+ of this type.
+
+
+
+
+
+ default
+
+ The default value for the data type. If this is omitted, the
+ default is null.
+
+
+
+
+
+ alignment
+
+ The storage alignment requirement of the data type. If specified,
+ it must be char, int2,
+ int4, or double; the
+ default is int4.
+
+
+
+
+
+ storage
+
+ The storage strateg for the data type. If specified, must be
+ plain, external,
+ extended, or main; the
+ default is plain.
+
+
+
+
+
+ attribute_name
+
+ The name of an attribute of the composite type.
+
+
+
+
+
+ data_type
+
+ The name of an existing data type.
+
+
+
+
+
+
+
+
Diagnostics
+
+
+
+ CREATE TYPE
+
+ Message returned if the type was successfully created.
+
+
+
+
+
Notes
- User-defined type names cannot begin with the underscore character
- (_
) and can only be 62
- characters long (or in general NAMEDATALEN - 2, rather than
- the NAMEDATALEN - 1 characters allowed for other names).
- Type names beginning with underscore are
- reserved for internally-created array type names.
-
+ User-defined type names cannot begin with the underscore character
+ (_) and can only be 62 characters
+ long (or in general NAMEDATALEN - 2, rather than
+ the NAMEDATALEN - 1 characters allowed for other
+ names). Type names beginning with underscore are reserved for
+ internally-created array type names.
+
+
+ In
PostgreSQL versions before 7.3, it
+ was customary to avoid creating a shell type by replacing the
+ functions' forward references to the type name with the placeholder
+ pseudotype opaque>. The cstring> arguments and
+ results also had to be declared as opaque> before 7.3. To
+ support loading of old dump files, CREATE TYPE> will
+ accept functions declared using opaque>, but it will issue
+ a notice and change the function's declaration to use the correct
+ types.
+
Examples
+
- This example creates the box data type and then uses the
+ This example creates the data type box and then uses the
type in a table definition:
-CREATE TYPE box (INTERNALLENGTH = 16,
- INPUT = my_procedure_1, OUTPUT = my_procedure_2);
-CREATE TABLE myboxes (id INT4, description box);
+CREATE TYPE box (
+ INTERNALLENGTH = 16,
+ INPUT = my_box_in_function,
+ OUTPUT = my_box_out_function
+);
+
+CREATE TABLE myboxes (
+ id integer,
+ description box
+);
- If box's internal structure were an array of four
- float4>s, we might instead say
+ If the internal structure of box were an array of four
+ float4> elements, we might instead use
-CREATE TYPE box (INTERNALLENGTH = 16,
- INPUT = my_procedure_1, OUTPUT = my_procedure_2,
- ELEMENT = float4);
+CREATE TYPE box (
+ INTERNALLENGTH = 16,
+ INPUT = my_box_in_function,
+ OUTPUT = my_box_out_function,
+ ELEMENT = float4
+);
- which would allow a box value's component floats to be accessed
+ which would allow a box value's component numbers to be accessed
by subscripting. Otherwise the type behaves the same as before.
This example creates a large object type and uses it in
a table definition:
-CREATE TYPE bigobj (INPUT = lo_filein, OUTPUT = lo_fileout,
- INTERNALLENGTH = VARIABLE);
-CREATE TABLE big_objs (id int4, obj bigobj);
+CREATE TYPE bigobj (
+ INPUT = lo_filein, OUTPUT = lo_fileout,
+ INTERNALLENGTH = VARIABLE
+);
+CREATE TABLE big_objs (
+ id integer,
+ obj bigobj
+);
This example creates a composite type and uses it in
- a table function definition:
+ a function definition:
CREATE TYPE compfoo AS (f1 int, f2 text);
CREATE FUNCTION getfoo() RETURNS SETOF compfoo AS 'SELECT fooid, fooname FROM foo' LANGUAGE SQL;
+
+ More examples, including suitable input and output functions, are
+ in .
+
Description
- CREATE USER will add a new user to an instance
- of
PostgreSQL. Refer to
- for information about managing users and authentication. You must
- be a database superuser to use this command.
+ CREATE USER adds a new user to a
+
PostgreSQL database cluster. Refer to
+
and
+ linkend="client-authentication"> for information about managing
+ users and authentication. You must be a database superuser to use
+ this command.
+
-
-
Parameters
-
+
+
Parameters
The SYSID clause can be used to choose the
PostgreSQL user ID of the user that
- is being created. It is not at all necessary that those match
- the Unix user IDs, but some people choose to keep the numbers
- the same.
+ is being created. This is not normally not necessary, but may
+ be useful if you need to recreate the owner of an orphaned
+ object.
If this is not specified, the highest assigned user ID plus one
Sets the user's password. If you do not plan to use password
- authentication you can omit this option, but the user
- won't be able to connect to a password-authenticated server.
- The password can be set or changed later, using
- .
+ authentication you can omit this option, but then the user
+ won't be able to connect if you decide to switch to password
+ authentication. The password can be set or changed later,
+ using
+ endterm="SQL-ALTERUSER-title">.
UNENCRYPTED>
- These keywords control whether the password is stored
- encrypted in pg_shadow>. (If neither is specified,
- the default behavior is determined by the
- PASSWORD_ENCRYPTION server parameter.) If
- the presented string is already in MD5-encrypted format, then
- it is stored as-is, regardless of whether
- ENCRYPTED> or UNENCRYPTED> is specified.
- This allows reloading of encrypted passwords during
- dump/restore.
+ These key words control whether the password is stored
+ encrypted in the system catalogs. (If neither is specified,
+ the default behavior is determined by the configuration
+ parameter password_encryption.) If the
+ presented password string is already in MD5-encrypted format,
+ then it is stored encrypted as-is, regardless of whether
+ ENCRYPTED> or UNENCRYPTED> is specified
+ (since the system cannot decrypt the specified encrypted
+ password string). This allows reloading of encrypted
+ passwords during dump/restore.
- See
- for details on how to set up authentication mechanisms. Note
- that older clients may lack support for the MD5 authentication
- mechanism that is needed to work with passwords that are
- stored encrypted.
+ Note that older clients may lack support for the MD5
+ authentication mechanism that is needed to work with passwords
+ that are stored encrypted.
-
-
-
Diagnostics
CREATE USER
- Message returned if the command completes successfully.
+ Message returned if the user account was successfully created.
-
endterm="SQL-DROPUSER-title"> to remove a user. Use
linkend="SQL-ALTERGROUP" endterm="SQL-ALTERGROUP-title"> to add the
user to groups or remove the user from groups.
+
+
PostgreSQL includes a program
linkend="APP-CREATEUSER" endterm="APP-CREATEUSER-title"> that has
- the same functionality as this command (in fact, it calls this
+ the same functionality as CREATE USER (in fact, it calls this
command) but can be run from the command shell.
- Create a user with a password, whose account is valid until the end of 2001.
- Note that after one second has ticked in 2002, the account is not
- valid:
+ Create a user with a password that is valid until the end of 2004.
+ After one second has ticked in 2005, the password is no longer
+ valid.
-CREATE USER miriam WITH PASSWORD 'jw8s0F4' VALID UNTIL 'Jan 1 2002';
+CREATE USER miriam WITH PASSWORD 'jw8s0F4' VALID UNTIL '2005-01-01';
CREATE VIEW
SQL - Language Statements
+
-
- CREATE VIEW
-
-
- define a new view
-
+ CREATE VIEW
+ define a new view
-
-
- 2000-03-25
-
-
-CREATE [ OR REPLACE ] VIEW
view [ (
-class="PARAMETER">column name list ) ] AS SELECT query
-
-
-
-
- 2000-03-25
-
-
- Inputs
-
-
-
-
- view
-
- The name (optionally schema-qualified) of a view to be created.
-
-
-
-
- column name list
-
- An optional list of names to be used for columns of the view.
- If given, these names override the column names that would be
- deduced from the SQL query.
-
-
-
-
- query
-
- An SQL query (that is, a SELECT> statement)
- which will provide the columns and rows of the view.
-
- Refer to for more information
- about valid arguments.
-
-
-
-
-
-
-
-
-
- 2000-03-25
-
-
- Outputs
-
-
-
-
-CREATE VIEW
-
-
- The message returned if the view is successfully created.
-
-
-
-
-
-ERROR: Relation 'view' already exists
-
-
- This error occurs if the view specified already exists in the database.
-
-
-
-
-
-WARNING: Attribute 'column' has an unknown type
-
-
- The view will be created having a column with an unknown type
- if you do not specify it. For example, the following command gives
- a warning:
-CREATE VIEW vista AS SELECT 'Hello World'
-
-
- whereas this command does not:
-CREATE VIEW vista AS SELECT text 'Hello World'
-
-
-
-
-
-
-
+
+
+CREATE [ OR REPLACE ] VIEW
name [ (
+class="PARAMETER">column_name [, ...] ) ] AS query
+
-
-
- 2000-03-25
-
-
- Description
-
+
+
Description
- CREATE VIEW defines a view of a query.
- The view is not physically materialized. Instead, a query
- rewrite rule (an ON SELECT> rule) is automatically generated to
- support SELECT operations on views.
+ CREATE VIEW defines a view of a query. The view
+ is not physically materialized. Instead, the query is run everytime
+ the view is referenced in a query.
If a schema name is given (for example, CREATE VIEW
myschema.myview ...>) then the view is created in the
- specified schema. Otherwise it is created in the current schema (the one
- at the front of the search path; see CURRENT_SCHEMA()>).
+ specified schema. Otherwise it is created in the current schema.
The view name must be distinct from the name of any other view, table,
sequence, or index in the same schema.
+
-
-
- 2000-03-25
-
-
- Notes
-
+
+
Parameters
+
+
+
+ name
+
+ The name (optionally schema-qualified) of a view to be created.
+
+
+
+
+
+ column_name
+
+ An optional list of names to be used for columns of the view.
+ If not given, the column names are deduced from the query.
+
+
+
+
+
+ query
+
+ A query (that is, a SELECT> statement) which will
+ provide the columns and rows of the view.
+
+
+ Refer to
+ for more information about valid queries.
+
+
+
+
+
+
+
+
Diagnostics
+
+
+
+ CREATE VIEW
+
+ Message returned if the view was successfully created.
+
+
+
+
+
+ WARNING: Attribute 'column' has an unknown type
+
+ The view will be created having a column with an unknown type if
+ you do not specify it. For example, the following command gives
+ this warning:
+CREATE VIEW vista AS SELECT 'Hello World'
+
+ whereas this command does not:
+CREATE VIEW vista AS SELECT text 'Hello World'
+
+
+
+
+
+
+
+
+
Notes
Currently, views are read only: the system will not allow an insert,
Use the DROP VIEW statement to drop views.
-
-
-
- Usage
-
+
+
Examples
+
- Create a view consisting of all Comedy films:
+ Create a view consisting of all comedy films:
-CREATE VIEW kinds AS
+CREATE VIEW comedies AS
SELECT *
FROM films
WHERE kind = 'Comedy';
-
-SELECT * FROM kinds;
-
- code | title | did | date_prod | kind | len
--------+---------------------------+-----+------------+--------+-------
- UA502 | Bananas | 105 | 1971-07-13 | Comedy | 01:22
- C_701 | There's a Girl in my Soup | 107 | 1970-06-11 | Comedy | 01:36
-(2 rows)
-
+
-
-
- Compatibility
-
-
-
-
- 2000-03-25
-
-
- SQL92
-
+
+
Compatibility
- SQL92 specifies some additional capabilities for the
- CREATE VIEW statement:
-
-
-CREATE VIEW view [ column [, ...] ]
- AS SELECT expression [ AS colname ] [, ...]
- FROM table [ WHERE condition ]
+ The SQL standard specifies some additional capabilities for the
+ CREATE VIEW statement:
+
+CREATE VIEW name [ ( column [, ...] ) ]
+ AS query
[ WITH [ CASCADE | LOCAL ] CHECK OPTION ]
-
+
+
- The optional clauses for the full SQL92 command are:
+ The optional clauses for the full SQL command are:
- CHECK OPTION
+ CHECK OPTION
- This option is to do with updatable views.
- All INSERT> and UPDATE> commands on the view will be
- checked to ensure data satisfy the view-defining
- condition. If they do not, the update will be rejected.
+ This option is to do with updatable views. All
+ INSERT> and UPDATE> commands on the view
+ will be checked to ensure data satisfy the view-defining
+ condition (that is, the new data would be visible through the
+ view). If they do not, the update will be rejected.
- LOCAL
+ LOCAL
- Check for integrity on this view.
+ Check for integrity on this view.
- CASCADE
+ CASCADE
- Check for integrity on this view and on any dependent
- view. CASCADE is assumed if neither CASCADE nor LOCAL is specified.
+ Check for integrity on this view and on any dependent
+ view. CASCADE> is assumed if neither
+ CASCADE> nor LOCAL> is specified.
-
-
-
- CREATE OR REPLACE VIEW is a
-
PostgreSQL language extension.
-
+
+
-
+ CREATE OR REPLACE VIEW is a
+
PostgreSQL language extension.
+