Tables and data types
This page covers creating, changing and dropping tables, every column type RasterizedDB stores, and the constraints it enforces. The statements are PostgreSQL's, so a schema written for PostgreSQL, or generated by an ORM's migrations, usually runs as it is.
Creating a table
CREATE TABLE customers (
id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
email varchar(200) NOT NULL UNIQUE,
name text NOT NULL,
country char(2) NOT NULL DEFAULT 'GR',
created_at timestamptz NOT NULL DEFAULT now()
);
CREATE TABLE orders (
id bigserial PRIMARY KEY,
customer_id bigint NOT NULL REFERENCES customers (id) ON DELETE CASCADE,
status text NOT NULL DEFAULT 'open' CHECK (status IN ('open', 'paid', 'shipped')),
total numeric(12, 2) NOT NULL CHECK (total >= 0),
tags text[],
placed_on date NOT NULL DEFAULT CURRENT_DATE
);- A column is nullable unless it is declared
NOT NULLor is part of thePRIMARY KEY. CREATE TABLE IF NOT EXISTSsucceeds without doing anything when the table already exists.- Unquoted names are folded to lower case, as in PostgreSQL, and
"Quoted"names keep their case. Two tables whose names differ only by case cannot both exist. - A schema prefix is accepted (
public.orders), but there is one namespace per database:public.ordersandsales.ordersname the same table. See Schemas, views and other objects. CREATE UNLOGGED TABLEcreates an ordinary table. Every table is written to the write-ahead log.- Storage parameters after the column list, such as
WITH (fillfactor = 70), andTABLESPACE, are accepted and ignored. - To split a table across partitions, add
PARTITION BY HASH (…); see Partitioning.PARTITION BY RANGE,PARTITION BY LIST,PARTITION OFandINHERITSare refused.
CREATE TABLE … AS
CREATE TABLE … AS creates a table from a query's result, with the query's column names and types:
CREATE TABLE paid_orders AS
SELECT id, customer_id, total FROM orders WHERE status = 'paid';
CREATE TABLE order_totals (customer_id, order_total) AS
SELECT customer_id, sum(total) FROM orders GROUP BY customer_id;
CREATE TABLE orders_shape AS SELECT * FROM orders WITH NO DATA;As in PostgreSQL, constraints are not copied, NOT NULL included. WITH NO DATA creates the empty table. SELECT … INTO new_table FROM … does the same as CREATE TABLE … AS.
CREATE TABLE … (LIKE other …) is not supported. Use CREATE TABLE … AS SELECT * FROM other WITH NO DATA for the columns, then add the constraints.
Temporary tables
A temporary table is visible only to the session that created it, and is dropped when that session ends:
CREATE TEMP TABLE import_batch (sku text, qty int);
CREATE TEMPORARY TABLE daily AS
SELECT placed_on, count(*) AS n FROM orders GROUP BY placed_on;- A temporary table hides a permanent table of the same name for its session.
public.namestill reaches the permanent one, andpg_temp.namethe temporary one. ON COMMIT PRESERVE ROWS(the default) keeps the rows until the session ends.ON COMMIT DELETE ROWSempties the table at the end of every transaction.ON COMMIT DROPdrops it when the transaction that created it ends.DROP TABLE namedrops the session's temporary table first.DISCARD TEMPandDISCARD ALLdrop all of them.- A temporary table cannot be schema-qualified when it is created (
CREATE TEMP TABLE public.x …is refused with42P16). - Its rows are held in memory.
Data types
Numbers
| Type | Also written | Range | Notes |
|---|---|---|---|
smallint | int2 | -32,768 to 32,767 | |
integer | int, int4 | -2,147,483,648 to 2,147,483,647 | |
bigint | int8 | -9,223,372,036,854,775,808 to 9,223,372,036,854,775,807 | |
smallserial, serial, bigserial | serial2, serial4, serial8 | as the integer type | An integer column, NOT NULL, numbered from a sequence. See Serial and identity columns. |
numeric(p, s) | decimal(p, s) | up to 38 significant digits | Exact. Values are rounded to s places on the way in. |
numeric | decimal | up to 38 significant digits, up to 38 after the point | Exact. Each value keeps the scale it was written with: 1.50 reads back as 1.50. |
real | float4 | about 6 significant digits | IEEE 754 single precision. |
double precision | float8, float | about 15 significant digits | IEEE 754 double precision. |
money | as numeric | Stored as a numeric; shown as a plain number (12.5), not as $12.50. |
A value outside an integer type's range is refused with 22003.
NUMERIC. A numeric(p, s) column rounds each value half away from zero to s places and refuses one that needs more than p digits (22003). The scale s can be at most 30. numeric(p) means numeric(p, 0). Arithmetic on NUMERIC values is exact and follows PostgreSQL's rules for the scale of a result (1.0 / 3 is 0.33333333333333333333). A value or a result that needs more than 38 digits is refused, never rounded silently. PostgreSQL's numeric has no such limit.
NaN, Infinity and -Infinity cannot be stored in a NUMERIC column. Writing one is refused with 0A000. real and double precision columns do store them, as well as -0.
A float is shown as PostgreSQL shows it: the shortest digits that read back as the same value, with an exponent for very large or very small values (1e+20, 1e-07).
Text
| Type | Also written | Notes |
|---|---|---|
text | varchar with no length, name | Any length. |
varchar(n) | character varying(n) | At most n characters. A longer value is refused with 22001, unless every character past n is a space; those are cut off. |
char(n) | character(n), bpchar(n) | Exactly n characters, padded with spaces. A bare char is char(1). |
citext | Text compared without regard to case. See Full-text search and collations. |
A length can be at most 10,485,760. Text is UTF-8.
char(n) behaves as in PostgreSQL. Trailing spaces do not count when values are compared, so 'b' and 'b ' are the same value and the same key. The value is padded to n when it is returned, and LIKE matches the padded value. Read as text (with ||, length or ::text) it has no trailing spaces.
A text column can be declared with a collation, for example name text COLLATE rdb_ci for case-insensitive comparison. See Full-text search and collations.
Binary data
bytea holds bytes. It accepts both of PostgreSQL's input formats: hex ('\xdeadbeef', whitespace allowed between pairs) and escape ('abc\001'). Values are returned in hex format.
CREATE TABLE files (id int PRIMARY KEY, body bytea NOT NULL);
INSERT INTO files VALUES (1, '\x48656c6c6f');
SELECT encode(body, 'escape') FROM files; -- HelloBoolean
boolean (or bool) holds true, false or NULL. As input it accepts PostgreSQL's spellings: true/false, t/f, yes/no, y/n, on/off and 1/0, in any case.
Dates and times
| Type | Also written | Holds | Resolution |
|---|---|---|---|
date | A calendar date. | 1 day | |
time | time without time zone | A time of day. | 1 microsecond |
timetz | time with time zone | A time of day with a UTC offset. | 1 microsecond |
timestamp | timestamp without time zone | A date and wall-clock time, with no time zone. | 1 microsecond |
timestamptz | timestamp with time zone | An instant in time. | 1 microsecond |
interval | A span of time, kept as months, days and microseconds. | 1 microsecond |
- The session time zone is always UTC.
SET TimeZoneis accepted but changes nothing, andSHOW TimeZoneanswersUTC. - A
timestamptzliteral with an offset is converted to UTC:'2024-01-01 10:00:00+02'is stored as 08:00 UTC and shown as2024-01-01 08:00:00+00. - A
timestamp(without time zone) literal keeps its wall-clock time and ignores any offset, as PostgreSQL does:'2024-01-01 10:00:00+02'is stored as 10:00. - A precision can be declared:
timestamp(0),timestamptz(3),time(2),interval(0). Values written to such a column are rounded to that many fractional digits. - Input with more than six fractional digits is rounded to the microsecond.
- An impossible date such as
'2026-02-30'is refused. - To convert between zones in a query, use
AT TIME ZONE(see Functions and operators).
CREATE TABLE shifts (
id int PRIMARY KEY,
starts timestamptz NOT NULL,
local_at timestamp(0),
length interval NOT NULL DEFAULT '8 hours'
);
INSERT INTO shifts (id, starts, local_at) VALUES (1, '2024-03-01 06:00:00+02', '2024-03-01 06:00:00');
SELECT starts, local_at, starts + length AS ends FROM shifts; starts | local_at | ends
------------------------+---------------------+------------------------
2024-03-01 04:00:00+00 | 2024-03-01 06:00:00 | 2024-03-01 12:00:00+00UUID
uuid holds a 128-bit UUID, written in the usual hyphenated form. gen_random_uuid() makes a random (version 4) UUID and uuidv7() a time-ordered (version 7) one. Version 7 keys are a good choice for a primary key: new rows sort after old ones.
CREATE TABLE sessions (
id uuid PRIMARY KEY DEFAULT uuidv7(),
user_id bigint NOT NULL
);Network addresses
| Type | Holds |
|---|---|
inet | An IPv4 or IPv6 host address, with an optional netmask ('192.168.0.10/24'). |
cidr | An IPv4 or IPv6 network ('10.0.0.0/8'). |
macaddr | A MAC address ('08:00:2b:01:02:03'). |
macaddr8 | An EUI-64 MAC address. |
Bit strings
bit(n) holds exactly n bits and bit varying(n) (or varbit(n)) up to n bits. Literals are written B'1010'.
Geometric types
point, line, lseg, box, path, polygon and circle are stored and returned in PostgreSQL's formats. Their containment and overlap operators work on bounding boxes; see Functions and operators. They cannot be indexed.
Arrays
Any type above followed by [] is an array of it: int[], text[], numeric(10,2)[], varchar(20)[]. Each element is checked against the element type on the way in, and arrays sort element by element in that type.
CREATE TABLE posts (id int PRIMARY KEY, tags text[], scores int[]);
INSERT INTO posts VALUES (1, '{rust,db}', ARRAY[3, 5, 8]);
INSERT INTO posts VALUES (2, '{"needs review"}', '{{1,2},{3,4}}');
SELECT tags[1], 5 = ANY(scores), array_length(scores, 1) FROM posts WHERE id = 1;- Indexes start at 1, as in PostgreSQL.
- Multidimensional arrays are supported. Every sub-array must have the same length (
22P02otherwise). - An element that does not fit the element type is refused:
'{1,x}'into anint[]is22P02. - An array column cannot be indexed, and an element cannot be assigned on its own (
UPDATE … SET a[1] = …). Replace the whole array instead.
Array functions and operators are listed in Functions and operators.
JSON and JSONB
json keeps a document exactly as it was written. jsonb stores it in a decoded form that supports containment and key operators and can be indexed. Both accept any JSON value. See JSON and JSONB.
Range types
int4range, int8range, numrange, daterange, tsrange and tstzrange hold a range of values with inclusive or exclusive bounds. They are read and shown as in PostgreSQL. Discrete ranges are shown in canonical form, so '[1,5]'::int4range is shown as [1,6).
CREATE TABLE price_bands (id int PRIMARY KEY, band int4range NOT NULL);
INSERT INTO price_bands VALUES (1, '[0,20)'), (2, '[20,50)'), (3, '[50,100)');
SELECT id FROM price_bands WHERE band @> 25; -- 2A range whose lower bound is above its upper bound ('[5,1)') is refused with 22000. Multirange types and CREATE TYPE … AS RANGE are not supported. Range functions and operators are in Functions and operators.
Enumerated types
CREATE TYPE order_state AS ENUM ('new', 'paid', 'shipped');
CREATE TABLE shipments (
id int PRIMARY KEY,
state order_state NOT NULL DEFAULT 'new'
);
ALTER TYPE order_state ADD VALUE 'cancelled';
ALTER TYPE order_state ADD VALUE IF NOT EXISTS 'returned' AFTER 'shipped';
ALTER TYPE order_state RENAME VALUE 'new' TO 'created';
ALTER TYPE order_state RENAME TO shipment_state;
DROP TYPE IF EXISTS some_old_type;- A column of an enum type, or an array of one, takes only the type's labels. Any other value is refused with
22P02. ORDER BY,<,>,BETWEEN,minandmaxon the column use the order the labels were declared in.RENAME VALUEchanges the stored rows too.- Type statements can run inside a transaction block together with the tables that use the type.
DROP TYPEis refused (2BP01) while a column uses the type, andDROP TYPE … CASCADEis refused too. Drop or change the columns first.CREATE TYPEmakes only enums. Composite types (CREATE TYPE t AS (…)) and range types are refused with0A000.
Domains
A domain is a base type with its own NOT NULL, CHECK and default. A column declared with the domain gets them:
CREATE DOMAIN positive_int AS integer CHECK (VALUE > 0);
CREATE DOMAIN email_address AS text CONSTRAINT has_at CHECK (VALUE LIKE '%@%') NOT NULL;
CREATE TABLE contacts (id int PRIMARY KEY, age positive_int, email email_address);A value that breaks the domain's check is refused with 23514. ALTER DOMAIN and the rest are described in Schemas, views and other objects.
Constraints
| Constraint | Violation SQLSTATE |
|---|---|
NOT NULL | 23502 |
UNIQUE, PRIMARY KEY | 23505 |
FOREIGN KEY | 23503 |
CHECK | 23514 |
Each constraint can be declared on the column, as a table constraint in the column list, or later with ALTER TABLE … ADD. Give it a name with CONSTRAINT name; an unnamed one gets PostgreSQL's name (orders_pkey, customers_email_key, orders_customer_id_fkey, orders_total_check). A constraint name can be up to 128 bytes.
PRIMARY KEY and UNIQUE
CREATE TABLE order_lines (
order_id bigint NOT NULL,
line_no int NOT NULL,
sku text NOT NULL,
qty int NOT NULL,
PRIMARY KEY (order_id, line_no),
CONSTRAINT order_lines_sku_once UNIQUE (order_id, sku)
);- A primary key makes its columns
NOT NULL. - A key can have up to 8 columns.
- NULLs never conflict with each other: a
UNIQUEcolumn can hold any number of NULLs.UNIQUE NULLS NOT DISTINCTis refused. - Uniqueness holds across concurrent transactions: two sessions inserting the same key at once cannot both commit it.
- The error names the constraint and the conflicting key, as PostgreSQL's does.
- A
CREATE UNIQUE INDEXon plain columns creates a unique constraint too; see Indexes.
NOT NULL
NOT NULL refuses a NULL in the column. It can be added or removed later with ALTER COLUMN … SET NOT NULL and DROP NOT NULL. SET NOT NULL is refused while a row holds a NULL.
CHECK
CREATE TABLE products (
id int PRIMARY KEY,
price numeric(10, 2) NOT NULL CHECK (price > 0),
discount numeric(10, 2) NOT NULL DEFAULT 0,
code text NOT NULL,
CONSTRAINT discount_below_price CHECK (discount >= 0 AND discount < price),
CONSTRAINT code_format CHECK (code ~ '^[A-Z]{3}-[0-9]{4}$')
);- A check refuses a row only when it is false. A NULL result passes, as in PostgreSQL.
- A check may use comparisons,
BETWEEN,IN,IS [NOT] NULL,IS [NOT] DISTINCT FROM,LIKE/ILIKE,SIMILAR TO, POSIX regular expressions (~,~*,!~,!~*),CASE,COALESCE, common text functions such aslength,upper,lowerandbtrim, JSON tests such asdoc ? 'key'andjsonb_typeof(doc), andAND/OR/NOTof these. The formspg_dumpwrites, such as(status = ANY (ARRAY['a'::text, 'b'::text])), are accepted. - A check that cannot be evaluated is refused when you declare it (
0A000), rather than stored and not enforced. ALTER TABLE … ADD CONSTRAINT … CHECK (…)checks the rows already in the table and is refused if one breaks it.- A check expression can be up to 512 characters.
A few regular-expression features cannot be matched exactly as PostgreSQL matches them, for example back-references and look-around. A check that uses one is still created, but it is not enforced, and the server sends a warning. SHOW CHECKS lists every check with whether it is enforced:
SHOW CHECKS;DEFAULT
A default applies when an INSERT leaves the column out or writes DEFAULT. A default can be:
- a constant:
DEFAULT 0,DEFAULT 'open',DEFAULT true,DEFAULT NULL, or a constant with a cast such asDEFAULT '{}'::jsonborDEFAULT '{}'::text[]; - the current time:
now(),CURRENT_TIMESTAMP(with an optional precision,CURRENT_TIMESTAMP(3)),LOCALTIMESTAMP,transaction_timestamp(),statement_timestamp(),clock_timestamp(),CURRENT_DATE,CURRENT_TIME,LOCALTIME; - a new UUID:
gen_random_uuid(),uuid_generate_v4(),uuidv7(); - the next value of a sequence:
nextval('order_numbers').
Other expressions are refused when you declare them. now() and CURRENT_TIMESTAMP give every row of a transaction the same value, the time the transaction started; clock_timestamp() gives each row the time it was written. A default expression can be up to 256 characters.
Foreign keys
CREATE TABLE authors (id int PRIMARY KEY, name text NOT NULL);
CREATE TABLE books (
id int PRIMARY KEY,
author_id int REFERENCES authors (id) ON DELETE SET NULL ON UPDATE CASCADE,
title text NOT NULL
);
CREATE TABLE editions (
book_id int,
edition int,
PRIMARY KEY (book_id, edition)
);
CREATE TABLE prints (
id int PRIMARY KEY,
book_id int,
edition int,
CONSTRAINT prints_edition_fkey
FOREIGN KEY (book_id, edition) REFERENCES editions (book_id, edition)
MATCH FULL ON DELETE CASCADE
);- Inserts and updates of the referencing table check that the referenced row exists. A NULL key is not checked.
- The referenced columns must be exactly a
PRIMARY KEYorUNIQUEconstraint of the referenced table (42830otherwise).REFERENCES authorswith no column list means its primary key. - Both sides must be comparable types. Integer types of different widths may reference each other; mismatched types are refused with
42804. - Composite keys are checked as a whole: a row must match one referenced row on all key columns.
MATCH SIMPLE(the default) skips the check when any key column is NULL.MATCH FULLrequires all key columns NULL or none.MATCH PARTIALis refused.ADD CONSTRAINT … FOREIGN KEYchecks the existing rows. AddNOT VALIDto skip that and check only new writes, then runALTER TABLE … VALIDATE CONSTRAINT namelater.- Checks hold across concurrent sessions: a child insert and a delete of its parent cannot both commit.
The actions for ON DELETE and ON UPDATE:
| Action | What happens to referencing rows when the referenced row is deleted or its key changes |
|---|---|
NO ACTION (default), RESTRICT | The statement is refused (23503) while a row still references it. |
CASCADE | Referencing rows are deleted, or their key is changed to the new value. |
SET NULL | The referencing key columns are set to NULL. ON DELETE SET NULL (col, …) sets only the listed columns. |
SET DEFAULT | The referencing key columns are set to their defaults. The default must itself reference an existing row. |
Dropping a table that another table references is refused (2BP01) unless you add CASCADE, which drops the referencing foreign keys and keeps their tables. The same applies to dropping a referenced UNIQUE or PRIMARY KEY constraint.
DEFERRABLE and INITIALLY DEFERRED are accepted, but checks are not deferred to commit: each is made when the statement runs. A key that references its own table is checked at the end of the statement. SET CONSTRAINTS is not supported.
Serial and identity columns
Both make an integer column that numbers new rows.
CREATE TABLE invoices (
id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
note text
);
CREATE TABLE tickets (
id int GENERATED BY DEFAULT AS IDENTITY PRIMARY KEY,
note text
);
CREATE TABLE legacy (
id serial PRIMARY KEY,
note text
);serial,bigserialandsmallserialareinteger,bigintandsmallintcolumns,NOT NULL, defaulting tonextvalof a sequence named<table>_<column>_seq.GENERATED BY DEFAULT AS IDENTITYnumbers a row when the value is left out, and accepts a value you write.GENERATED ALWAYS AS IDENTITYrefuses a written value (428C9) unless theINSERTsaysOVERRIDING SYSTEM VALUE; see Modifying data.- An identity column must be
smallint,integerorbigint. - Identity options are accepted only where they describe what the column does anyway:
START WITH 1,INCREMENT BY 1,MINVALUE 1,MAXVALUE n,CACHE n,NO MINVALUE,NO MAXVALUE,NO CYCLE. Any other start or increment is refused with0A000. ALTER TABLE … ALTER COLUMN c ADD GENERATED ALWAYS AS IDENTITY(andBY DEFAULT) turns an existingNOT NULLinteger column into an identity column. This is whatpg_dumpwrites.ALTER TABLE … ADD COLUMNwithserialor an identity clause is refused. Declare the column when you create the table.
Explicit sequences (CREATE SEQUENCE) are covered in Schemas, views and other objects.
Generated columns
A generated column is computed from the other columns of its row and stored. It is recomputed whenever the row is updated.
CREATE TABLE line_items (
id int PRIMARY KEY,
qty int NOT NULL,
unit_price numeric(10, 2) NOT NULL,
total numeric(12, 2) GENERATED ALWAYS AS (qty * unit_price) STORED,
label text GENERATED ALWAYS AS (CASE WHEN qty > 10 THEN 'bulk' ELSE 'single' END) STORED
);- Writing a value into a generated column is refused with
428C9.UPDATE … SET total = DEFAULTis allowed. - The expression may not read another generated column, and may not call a function whose result changes between calls, such as
now(),random()orgen_random_uuid()(42P17). Subqueries are refused (0A000). ALTER TABLE … ADD COLUMN … GENERATED ALWAYS AS (…) STOREDadds one and computes it for the existing rows.- The expression can be up to 512 characters.
Changing a table
ALTER TABLE takes one action or several separated by commas. ALTER TABLE IF EXISTS does nothing when the table is missing.
ALTER TABLE customers
ADD COLUMN phone text,
ADD COLUMN IF NOT EXISTS vip boolean NOT NULL DEFAULT false;Columns
| Statement | What it does |
|---|---|
ADD [COLUMN] [IF NOT EXISTS] name type [constraints] | Adds a column. Inline DEFAULT, NOT NULL, UNIQUE, PRIMARY KEY, REFERENCES, CHECK and GENERATED ALWAYS AS (…) STORED work as in CREATE TABLE. |
DROP [COLUMN] [IF EXISTS] name | Removes a column. |
RENAME [COLUMN] old TO new | Renames a column. Its constraints and default follow it. |
ALTER [COLUMN] name [SET DATA] TYPE type [USING expr] | Changes the column's type, converting every row. |
ALTER [COLUMN] name SET DEFAULT expr | Sets the default for new rows. |
ALTER [COLUMN] name DROP DEFAULT | Removes the default. |
ALTER [COLUMN] name SET NOT NULL | Refused while a row holds a NULL. |
ALTER [COLUMN] name DROP NOT NULL | Allows NULLs. |
Adding a column to a table that has rows fills it with its default, or NULL, in every existing row. ADD COLUMN … NOT NULL without a DEFAULT is refused on a table that has rows, because the existing rows would have nothing to hold. On an empty table it is accepted.
Adding a column to a table with rows rewrites every row, so on a large table it takes time. Dropping a column does not rewrite rows.
Changing a type. Without USING, each value is converted as PostgreSQL's assignment cast converts it: integer to bigint, text to varchar(50), numeric to numeric(10,2), and so on. A pair with no such cast is refused with 42804, a value that does not fit with 22003 (out of range) or 22001 (too long), and two key values that become equal with 23505. A refused change leaves the column as it was. With USING, each row's new value is the expression, computed from the row as it was:
ALTER TABLE orders ALTER COLUMN id TYPE bigint;
ALTER TABLE events ALTER COLUMN happened_on TYPE date USING to_date(happened_on, 'DD/MM/YYYY');
ALTER TABLE flags ALTER COLUMN active TYPE boolean USING active::boolean;
ALTER TABLE legacy ALTER COLUMN raw_tags TYPE integer[] USING raw_tags::integer[];The USING expression may not contain a subquery, an aggregate or a window function. On an array column, USING must be the column itself cast to the new array type. Changing between timestamp and timestamptz does not rewrite rows. A change to an enum or domain type is refused.
Constraints
| Statement | What it does |
|---|---|
ADD [CONSTRAINT name] PRIMARY KEY (cols) | Adds a primary key. Refused if a key column holds a NULL or a duplicate. |
ADD [CONSTRAINT name] UNIQUE (cols) | Adds a unique constraint, checking existing rows. |
ADD [CONSTRAINT name] CHECK (expr) | Adds a check, checking existing rows. |
ADD [CONSTRAINT name] FOREIGN KEY (cols) REFERENCES … [NOT VALID] | Adds a foreign key, checking existing rows unless NOT VALID. |
ADD CONSTRAINT IF NOT EXISTS name … or ADD IF NOT EXISTS CONSTRAINT name … | Does nothing when a constraint of that name exists. This is an extension; PostgreSQL has neither form. |
DROP CONSTRAINT [IF EXISTS] name [CASCADE] | Drops a constraint. A constraint a foreign key depends on needs CASCADE. |
RENAME CONSTRAINT old TO new | Renames a constraint. |
VALIDATE CONSTRAINT name | Checks existing rows against a foreign key added NOT VALID. |
The table itself
| Statement | What it does |
|---|---|
RENAME TO new_name | Renames the table. Its constraints, indexes and the foreign keys that reference it keep working. |
OWNER TO, CLUSTER ON, SET (…), RESET (…), SET TABLESPACE, SET SCHEMA | Accepted and ignored, except SET (row_compression = …) and RESET (row_compression), which are acted on; see Compression. |
An ALTER COLUMN action this page does not list, such as SET STATISTICS, is accepted and ignored.
Dropping a table
DROP TABLE IF EXISTS import_batch;
DROP TABLE order_lines, orders CASCADE;IF EXISTS makes a missing table a success. Several tables can be dropped in one statement; either all of them are dropped or none. CASCADE also drops the foreign keys of other tables that reference them. RESTRICT (the default) refuses while one does (2BP01).
Emptying a table: TRUNCATE
TRUNCATE import_batch;
TRUNCATE TABLE orders, order_lines RESTART IDENTITY;
TRUNCATE customers CASCADE;TRUNCATEremoves every row of the tables it names.RESTART IDENTITYrestarts the tables' serial and identity sequences at 1.CONTINUE IDENTITY(the default) leaves them.- A table another table's foreign key references is refused (
0A000) unless that table is truncated in the same statement, by name or withCASCADE. TRUNCATEis transactional: aROLLBACKbrings the rows back, and aRESTART IDENTITYthat is rolled back is undone too. Disk space is returned by the next vacuum, not immediately; see Maintenance.- It takes an
ACCESS EXCLUSIVElock on each table, so it waits for open transactions that use them.
Schema changes and transactions
CREATE TABLE, ALTER TABLE, DROP TABLE, TRUNCATE and the type statements can run inside a transaction block and roll back with it. See Transactions for the details and the few statements that must run on their own.
Inspecting tables
Tools and ORMs read table definitions from information_schema and pg_catalog, so psql's \d table, \dt and a database GUI's schema browser work. For example:
SELECT column_name, data_type, is_nullable, column_default
FROM information_schema.columns
WHERE table_name = 'orders'
ORDER BY ordinal_position;Limits
- A column name cannot contain a space, and names beginning with
__null_are reserved. Table names beginning with__cte_are reserved (42939). - Each database has one namespace for tables: a schema prefix is accepted and ignored.
ALTER TABLE … SET SCHEMAchanges nothing. - NUMERIC values are limited to 38 significant digits, and a declared scale to 30. NUMERIC cannot hold
NaNor infinity. DEFAULTtakes only constants, the time functions, UUID functions andnextval(…).- Foreign-key checks are never deferred to commit;
DEFERRABLEis accepted and has no effect. UNIQUE NULLS NOT DISTINCT,CREATE TABLE … (LIKE …),INHERITS,PARTITION BY RANGE/LIST, composite and rangeCREATE TYPE, and multirange types are not supported.ALTER TABLE … ADD COLUMNcannot add aserialor identity column.- Identity columns always start at 1 and increment by 1.
- Arrays, geometric types and
bitstrings cannot be indexed, and array elements cannot be updated one at a time. - A unique or primary key can have at most 8 columns.
moneyvalues are shown as plain numbers.