NEW RasterizedDB 1.1.0 is out: sharding and the gateway, the message broker, roles and row-level security, compression, .NET on NuGet, and the enterprise edition. What's new ›
DOCS / RASTERIZEDDB SERVER / TABLES AND DATA TYPES

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

sql
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 NULL or is part of the PRIMARY KEY.
  • CREATE TABLE IF NOT EXISTS succeeds 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.orders and sales.orders name the same table. See Schemas, views and other objects.
  • CREATE UNLOGGED TABLE creates an ordinary table. Every table is written to the write-ahead log.
  • Storage parameters after the column list, such as WITH (fillfactor = 70), and TABLESPACE, are accepted and ignored.
  • To split a table across partitions, add PARTITION BY HASH (…); see Partitioning. PARTITION BY RANGE, PARTITION BY LIST, PARTITION OF and INHERITS are refused.

CREATE TABLE … AS

CREATE TABLE … AS creates a table from a query's result, with the query's column names and types:

sql
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:

sql
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.name still reaches the permanent one, and pg_temp.name the temporary one.
  • ON COMMIT PRESERVE ROWS (the default) keeps the rows until the session ends. ON COMMIT DELETE ROWS empties the table at the end of every transaction. ON COMMIT DROP drops it when the transaction that created it ends.
  • DROP TABLE name drops the session's temporary table first. DISCARD TEMP and DISCARD ALL drop all of them.
  • A temporary table cannot be schema-qualified when it is created (CREATE TEMP TABLE public.x … is refused with 42P16).
  • Its rows are held in memory.

Data types

Numbers

TypeAlso writtenRangeNotes
smallintint2-32,768 to 32,767
integerint, int4-2,147,483,648 to 2,147,483,647
bigintint8-9,223,372,036,854,775,808 to 9,223,372,036,854,775,807
smallserial, serial, bigserialserial2, serial4, serial8as the integer typeAn integer column, NOT NULL, numbered from a sequence. See Serial and identity columns.
numeric(p, s)decimal(p, s)up to 38 significant digitsExact. Values are rounded to s places on the way in.
numericdecimalup to 38 significant digits, up to 38 after the pointExact. Each value keeps the scale it was written with: 1.50 reads back as 1.50.
realfloat4about 6 significant digitsIEEE 754 single precision.
double precisionfloat8, floatabout 15 significant digitsIEEE 754 double precision.
moneyas numericStored 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

TypeAlso writtenNotes
textvarchar with no length, nameAny 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).
citextText 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.

sql
CREATE TABLE files (id int PRIMARY KEY, body bytea NOT NULL);
INSERT INTO files VALUES (1, '\x48656c6c6f');
SELECT encode(body, 'escape') FROM files;   -- Hello

Boolean

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

TypeAlso writtenHoldsResolution
dateA calendar date.1 day
timetime without time zoneA time of day.1 microsecond
timetztime with time zoneA time of day with a UTC offset.1 microsecond
timestamptimestamp without time zoneA date and wall-clock time, with no time zone.1 microsecond
timestamptztimestamp with time zoneAn instant in time.1 microsecond
intervalA span of time, kept as months, days and microseconds.1 microsecond
  • The session time zone is always UTC. SET TimeZone is accepted but changes nothing, and SHOW TimeZone answers UTC.
  • A timestamptz literal with an offset is converted to UTC: '2024-01-01 10:00:00+02' is stored as 08:00 UTC and shown as 2024-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).
sql
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;
text
         starts         |      local_at       |          ends
------------------------+---------------------+------------------------
 2024-03-01 04:00:00+00 | 2024-03-01 06:00:00 | 2024-03-01 12:00:00+00

UUID

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.

sql
CREATE TABLE sessions (
    id      uuid PRIMARY KEY DEFAULT uuidv7(),
    user_id bigint NOT NULL
);

Network addresses

TypeHolds
inetAn IPv4 or IPv6 host address, with an optional netmask ('192.168.0.10/24').
cidrAn IPv4 or IPv6 network ('10.0.0.0/8').
macaddrA MAC address ('08:00:2b:01:02:03').
macaddr8An 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.

sql
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 (22P02 otherwise).
  • An element that does not fit the element type is refused: '{1,x}' into an int[] is 22P02.
  • 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).

sql
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;   -- 2

A 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

sql
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, min and max on the column use the order the labels were declared in.
  • RENAME VALUE changes the stored rows too.
  • Type statements can run inside a transaction block together with the tables that use the type.
  • DROP TYPE is refused (2BP01) while a column uses the type, and DROP TYPE … CASCADE is refused too. Drop or change the columns first.
  • CREATE TYPE makes only enums. Composite types (CREATE TYPE t AS (…)) and range types are refused with 0A000.

Domains

A domain is a base type with its own NOT NULL, CHECK and default. A column declared with the domain gets them:

sql
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

ConstraintViolation SQLSTATE
NOT NULL23502
UNIQUE, PRIMARY KEY23505
FOREIGN KEY23503
CHECK23514

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

sql
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 UNIQUE column can hold any number of NULLs. UNIQUE NULLS NOT DISTINCT is 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 INDEX on 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

sql
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 as length, upper, lower and btrim, JSON tests such as doc ? 'key' and jsonb_typeof(doc), and AND/OR/NOT of these. The forms pg_dump writes, 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:

sql
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 as DEFAULT '{}'::jsonb or DEFAULT '{}'::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

sql
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 KEY or UNIQUE constraint of the referenced table (42830 otherwise). REFERENCES authors with 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 FULL requires all key columns NULL or none. MATCH PARTIAL is refused.
  • ADD CONSTRAINT … FOREIGN KEY checks the existing rows. Add NOT VALID to skip that and check only new writes, then run ALTER TABLE … VALIDATE CONSTRAINT name later.
  • 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:

ActionWhat happens to referencing rows when the referenced row is deleted or its key changes
NO ACTION (default), RESTRICTThe statement is refused (23503) while a row still references it.
CASCADEReferencing rows are deleted, or their key is changed to the new value.
SET NULLThe referencing key columns are set to NULL. ON DELETE SET NULL (col, …) sets only the listed columns.
SET DEFAULTThe 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.

sql
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, bigserial and smallserial are integer, bigint and smallint columns, NOT NULL, defaulting to nextval of a sequence named <table>_<column>_seq.
  • GENERATED BY DEFAULT AS IDENTITY numbers a row when the value is left out, and accepts a value you write.
  • GENERATED ALWAYS AS IDENTITY refuses a written value (428C9) unless the INSERT says OVERRIDING SYSTEM VALUE; see Modifying data.
  • An identity column must be smallint, integer or bigint.
  • 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 with 0A000.
  • ALTER TABLE … ALTER COLUMN c ADD GENERATED ALWAYS AS IDENTITY (and BY DEFAULT) turns an existing NOT NULL integer column into an identity column. This is what pg_dump writes.
  • ALTER TABLE … ADD COLUMN with serial or 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.

sql
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 = DEFAULT is allowed.
  • The expression may not read another generated column, and may not call a function whose result changes between calls, such as now(), random() or gen_random_uuid() (42P17). Subqueries are refused (0A000).
  • ALTER TABLE … ADD COLUMN … GENERATED ALWAYS AS (…) STORED adds 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.

sql
ALTER TABLE customers
    ADD COLUMN phone text,
    ADD COLUMN IF NOT EXISTS vip boolean NOT NULL DEFAULT false;

Columns

StatementWhat 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] nameRemoves a column.
RENAME [COLUMN] old TO newRenames 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 exprSets the default for new rows.
ALTER [COLUMN] name DROP DEFAULTRemoves the default.
ALTER [COLUMN] name SET NOT NULLRefused while a row holds a NULL.
ALTER [COLUMN] name DROP NOT NULLAllows 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:

sql
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

StatementWhat 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 newRenames a constraint.
VALIDATE CONSTRAINT nameChecks existing rows against a foreign key added NOT VALID.

The table itself

StatementWhat it does
RENAME TO new_nameRenames the table. Its constraints, indexes and the foreign keys that reference it keep working.
OWNER TO, CLUSTER ON, SET (…), RESET (…), SET TABLESPACE, SET SCHEMAAccepted 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

sql
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

sql
TRUNCATE import_batch;
TRUNCATE TABLE orders, order_lines RESTART IDENTITY;
TRUNCATE customers CASCADE;
  • TRUNCATE removes every row of the tables it names.
  • RESTART IDENTITY restarts 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 with CASCADE.
  • TRUNCATE is transactional: a ROLLBACK brings the rows back, and a RESTART IDENTITY that is rolled back is undone too. Disk space is returned by the next vacuum, not immediately; see Maintenance.
  • It takes an ACCESS EXCLUSIVE lock 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:

sql
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 SCHEMA changes nothing.
  • NUMERIC values are limited to 38 significant digits, and a declared scale to 30. NUMERIC cannot hold NaN or infinity.
  • DEFAULT takes only constants, the time functions, UUID functions and nextval(…).
  • Foreign-key checks are never deferred to commit; DEFERRABLE is accepted and has no effect.
  • UNIQUE NULLS NOT DISTINCT, CREATE TABLE … (LIKE …), INHERITS, PARTITION BY RANGE/LIST, composite and range CREATE TYPE, and multirange types are not supported.
  • ALTER TABLE … ADD COLUMN cannot add a serial or identity column.
  • Identity columns always start at 1 and increment by 1.
  • Arrays, geometric types and bit strings cannot be indexed, and array elements cannot be updated one at a time.
  • A unique or primary key can have at most 8 columns.
  • money values are shown as plain numbers.
✓ page rendered in 464 µs axum + tera + htmx · no other javascript