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 / SCHEMAS, VIEWS AND OTHER OBJECTS

Schemas, views and other objects

This page covers the database objects other than tables and indexes: schemas, views, materialized views, sequences, functions, procedures, DO blocks, triggers, enum types, domains, row-level security policies and comments. It also shows how to list what a database holds through information_schema and pg_catalog. Tables are in Tables and data types. Roles and GRANT are in Security.

Every statement here uses PostgreSQL's syntax. Each object definition is stored inside the database and survives a restart. Creating or dropping one inside a transaction block is undone by ROLLBACK (see Transactions and schema objects).

Schemas

A database has one namespace, public. Schemas are accepted so that migrations and tools written for PostgreSQL run unchanged, but no separate namespace is created.

  • CREATE SCHEMA and DROP SCHEMA succeed and create or remove nothing.
  • A schema-qualified name refers to the object named by its last part. app.orders, public.orders, "public"."orders" and orders are the same table.
  • SET search_path TO … is accepted, and SHOW search_path and current_setting('search_path') return what you set. It does not change how names are found.
  • current_schema() returns public, and the catalogues report every object in schema public.
sql
CREATE SCHEMA app;
CREATE TABLE app.orders (id int PRIMARY KEY, total numeric(10, 2));
INSERT INTO app.orders VALUES (1, 9.50);
SELECT total FROM orders WHERE id = 1;   -- the same table

Because of this, two schemas cannot hold tables with the same name. Give them distinct names, or keep them in separate databases.

Views

A view is a stored query. It is read wherever a table can be read: in FROM, in joins, in subqueries and in CTEs. Each read runs the query against the current data.

sql
CREATE TABLE orders (id int PRIMARY KEY, customer text, amount int);
INSERT INTO orders VALUES (1, 'ann', 10), (2, 'bob', 20), (3, 'ann', 30);

CREATE VIEW big_orders AS
    SELECT id, customer, amount * 2 AS doubled FROM orders WHERE amount > 10;

CREATE VIEW totals (who, n) AS
    SELECT customer, count(*) FROM orders GROUP BY customer;

SELECT * FROM big_orders ORDER BY id;
text
 id | customer | doubled
----+----------+---------
  2 | bob      |      40
  3 | ann      |      60
  • The optional column list after the name renames the query's columns in order. It may not name more columns than the query returns.
  • The query may start with SELECT, WITH, VALUES or TABLE. It may read other views. A view whose query names a missing relation is refused with 42P01.
  • Unquoted names are folded to lower case, as in PostgreSQL.

Replacing a view

CREATE OR REPLACE VIEW changes a view's query. As in PostgreSQL, the new query must keep every existing column, in the same order and under the same name. It may add columns after them.

sql
CREATE OR REPLACE VIEW big_orders AS
    SELECT id, customer, amount * 2 AS doubled, 'v2' AS version FROM orders WHERE amount > 10;

Dropping or renaming a column this way fails with 42P16. Drop the view and create it again instead.

Renaming and dropping views

sql
ALTER VIEW big_orders RENAME TO large_orders;
DROP VIEW IF EXISTS totals;
DROP VIEW large_orders CASCADE;
  • DROP VIEW takes several names, separated by commas.
  • A view that other views read cannot be dropped (2BP01) unless you add CASCADE, which drops those views too.
  • A table that a view reads cannot be dropped either. DROP TABLE … CASCADE drops the table and the views that read it.
  • When you rename a table with ALTER TABLE … RENAME TO, the views that read it follow the new name.
  • ALTER VIEW supports only RENAME TO. Other forms fail with 0A000.

Views are read-only

INSERT, UPDATE and DELETE on a view fail with 55000. Write to the table the view reads instead. For the same reason, WITH CHECK OPTION and INSTEAD OF triggers are refused with 0A000.

Materialized views

A materialized view stores its query's rows when it is created. Reads return the stored rows until you refresh it.

sql
CREATE MATERIALIZED VIEW order_snapshot AS SELECT id, customer FROM orders;

INSERT INTO orders VALUES (4, 'cy', 40);
SELECT count(*) FROM order_snapshot;      -- still 3

REFRESH MATERIALIZED VIEW order_snapshot;
SELECT count(*) FROM order_snapshot;      -- 4
  • CREATE MATERIALIZED VIEW … WITH NO DATA creates it empty. The first REFRESH fills it.
  • CREATE MATERIALIZED VIEW IF NOT EXISTS skips an existing one.
  • REFRESH MATERIALIZED VIEW replaces the rows in one step. Inside a transaction block the refresh belongs to the block, so ROLLBACK undoes it.
  • ALTER MATERIALIZED VIEW name RENAME TO new_name renames it, and DROP MATERIALIZED VIEW a, b drops one or more.
  • Writes to a materialized view fail with 42809. Only REFRESH changes its rows.
  • REFRESH MATERIALIZED VIEW CONCURRENTLY is refused. A plain REFRESH is already atomic.

Sequences

A sequence hands out increasing (or decreasing) integers. It is the usual source of surrogate keys.

sql
CREATE SEQUENCE invoice_no START 1000 INCREMENT BY 10;

CREATE TABLE invoice (
    id bigint DEFAULT nextval('invoice_no') PRIMARY KEY,
    note text
);

INSERT INTO invoice (note) VALUES ('first'), ('second') RETURNING id;
text
  id
------
 1000
 1010

Sequence options

CREATE SEQUENCE [IF NOT EXISTS] name [options] takes these options, in any order. The defaults are PostgreSQL's.

OptionDefaultWhat it does
AS smallint | integer | bigintbigintThe value type. It sets the default bounds.
INCREMENT [BY] n1The step. A negative step counts down. Zero is refused.
MINVALUE n / NO MINVALUE1 going up; the type's minimum going downThe lowest value.
MAXVALUE n / NO MAXVALUEthe type's maximum going up; -1 going downThe highest value.
START [WITH] nMINVALUE going up, MAXVALUE going downThe first value nextval returns.
CACHE n1Accepted. Must be at least 1.
CYCLE / NO CYCLENO CYCLEWith CYCLE, the sequence wraps to the other bound. Without it, nextval past a bound fails with 2200H.
OWNED BY table.column / OWNED BY NONEnoneTies the sequence to a column, so DROP TABLE drops the sequence too.

An invalid combination, such as START below MINVALUE, fails with 22023.

Using a sequence

CallWhat it returns
nextval('s')The next value.
currval('s')The value nextval('s') last returned in this session. Fails with 55000 if this session has not called it.
lastval()The value the last nextval in this session returned, for any sequence.
setval('s', n)Sets the current value, so the next nextval returns n + increment. Returns n.
setval('s', n, false)Sets it so that the next nextval returns n itself.

The name may be qualified ('public.s') or written as a cast ('s'::regclass). nextval inside a WHERE clause draws one value per row it tests, as in PostgreSQL.

A sequence can also be read as a one-row relation, as in PostgreSQL:

sql
SELECT last_value, log_cnt, is_called FROM invoice_no;

Writing to a sequence that way fails with 42809.

Values are not transactional. A value taken inside a transaction that rolls back is not handed out again. The counter is saved ahead of the values handed out, so after a crash or restart the sequence continues past every value a client could have seen, leaving a gap.

Changing and dropping a sequence

sql
ALTER SEQUENCE invoice_no RESTART WITH 5000;
ALTER SEQUENCE invoice_no INCREMENT BY 1 MAXVALUE 99999;
ALTER SEQUENCE invoice_no RENAME TO invoice_seq;
DROP SEQUENCE IF EXISTS invoice_seq CASCADE;
  • ALTER SEQUENCE takes the same options as CREATE SEQUENCE, plus RESTART (back to START) or RESTART [WITH] n, and RENAME TO.
  • DROP SEQUENCE takes several names. A sequence that a column default reads cannot be dropped (2BP01). With CASCADE it is dropped and so is that default.

Serial and identity columns

A serial, smallserial or bigserial column gets its own sequence, named <table>_<column>_seq and owned by the column. Dropping the table drops it. To reset it after loading rows with explicit ids, find it with pg_get_serial_sequence:

sql
CREATE TABLE ticket (id serial PRIMARY KEY, title text);
INSERT INTO ticket (id, title) VALUES (1, 'a'), (2, 'b'), (50, 'c');

SELECT setval(pg_get_serial_sequence('ticket', 'id'), 50);
INSERT INTO ticket (title) VALUES ('d') RETURNING id;   -- 51

pg_get_serial_sequence returns the name as public.ticket_id_seq, or NULL for a column without one. Declaring serial and identity columns is covered in Tables and data types.

Functions

CREATE FUNCTION defines a function you can call in any expression, like a built-in one. The body is written in SQL, or in PL/pgSQL in the forms described below. The built-in functions are listed in Functions and operators.

SQL functions

sql
CREATE FUNCTION add_tax(amount numeric, rate numeric) RETURNS numeric
    LANGUAGE sql IMMUTABLE
    AS $$ SELECT amount * (1 + rate) $$;

CREATE FUNCTION double_it(int) RETURNS int AS 'SELECT $1 * 2' LANGUAGE sql;

CREATE FUNCTION order_count() RETURNS bigint LANGUAGE sql
    AS 'SELECT count(*) FROM orders';

CREATE FUNCTION square(x double precision) RETURNS double precision RETURN x * x;

SELECT add_tax(100, 0.2), double_it(21), order_count(), square(3);
  • Parameters are referred to by name, or by position as $1, $2, …. Each argument is cast to its parameter's type, and the result is cast to the return type.
  • The body is a quoted string ('…' or $$ … $$), or an SQL-standard body: RETURN expression, or BEGIN ATOMIC statement; END.
  • The body is one statement. A body of several statements is refused when the function is called.
  • RETURNS void is accepted.
  • IMMUTABLE, STABLE, VOLATILE, STRICT, CALLED ON NULL INPUT, LEAKPROOF, PARALLEL …, COST n and ROWS n are accepted.
  • A function may call other functions. A function that calls itself is refused with 54001.
  • Parameters bound by a driver reach the body: SELECT double_it($1) works through the extended protocol.

A function that returns rows (RETURNS SETOF table_name or RETURNS TABLE (…)) is called in FROM:

sql
CREATE FUNCTION orders_over(minimum int) RETURNS SETOF orders LANGUAGE sql
    AS 'SELECT * FROM orders WHERE amount >= minimum';

SELECT id, customer FROM orders_over(20) o ORDER BY id;

A set-returning function called anywhere else fails with 0A000.

PL/pgSQL functions

A LANGUAGE plpgsql function can be called as a value only when its body is a single RETURN:

sql
CREATE FUNCTION shout(t text) RETURNS text LANGUAGE plpgsql
    AS $$ BEGIN RETURN upper(t) || '!'; END $$;

SELECT shout(customer) FROM orders;

Any other PL/pgSQL body is accepted by CREATE FUNCTION but fails with 0A000 when it is called. Use such bodies for trigger functions, which run the full PL/pgSQL described in PL/pgSQL statements, or put the logic in a DO block.

Replacing and dropping functions

sql
CREATE OR REPLACE FUNCTION double_it(int) RETURNS int AS 'SELECT $1 * 3' LANGUAGE sql;
DROP FUNCTION double_it(int);
DROP FUNCTION IF EXISTS add_tax(numeric, numeric), square;
  • Functions are told apart by name and number of arguments. Creating one that already exists fails with 42723. Use OR REPLACE.
  • CREATE OR REPLACE cannot change the return type (42P13).
  • DROP FUNCTION without an argument list drops the function of that name. A function that a trigger uses cannot be dropped (2BP01).
  • SECURITY INVOKER, the default, runs the function with the caller's privileges. SECURITY DEFINER makes it run with its owner's privileges. See Security. Before 1.1.0, SECURITY DEFINER was accepted and ignored.

Procedures

A procedure is a list of SQL statements run by CALL, in the caller's transaction.

sql
CREATE PROCEDURE add_order(i int, who text) LANGUAGE sql AS $$
    INSERT INTO orders (id, customer, amount) VALUES (i, who, 0);
    INSERT INTO orders (id, customer, amount) VALUES (i + 100, who, 0)
$$;

CALL add_order(5, 'dee');
DROP PROCEDURE add_order;

Only LANGUAGE sql procedures can be called. CALL of a missing procedure, or with the wrong number of arguments, fails with 42883.

DO blocks

DO runs a block of PL/pgSQL once, without storing it. Migrations use it for conditional steps.

sql
DO $$
DECLARE
    n int;
BEGIN
    SELECT count(*) INTO n FROM orders;
    IF n = 0 THEN
        INSERT INTO orders VALUES (1, 'seed', 0);
    END IF;
    RAISE NOTICE 'orders: %', n;
END
$$;
  • DO LANGUAGE plpgsql $$ … $$ is accepted. Any other language fails with 0A000.
  • RETURN with no value ends the block early.
  • Outside a transaction block, each statement in the block commits on its own. To make the whole block all-or-nothing, run it inside BEGIN … COMMIT.

The statements a block can use are listed in PL/pgSQL statements.

Triggers

A trigger runs a PL/pgSQL function when rows of a table are inserted, updated or deleted, or when the table is truncated.

Writing a trigger function

A trigger function takes no arguments, returns trigger, and is written in plpgsql:

sql
CREATE TABLE item (id int PRIMARY KEY, name text, qty int, changed_at timestamptz);
CREATE TABLE item_log (n serial PRIMARY KEY, op text, item_id int, old_name text, new_name text);

CREATE FUNCTION item_touch() RETURNS trigger LANGUAGE plpgsql AS $$
BEGIN
    NEW.changed_at := now();
    IF NEW.qty IS NULL THEN
        NEW.qty := 0;
    END IF;
    RETURN NEW;
END
$$;

CREATE FUNCTION item_audit() RETURNS trigger LANGUAGE plpgsql AS $$
BEGIN
    IF TG_OP = 'DELETE' THEN
        INSERT INTO item_log (op, item_id, old_name) VALUES (TG_OP, OLD.id, OLD.name);
        RETURN OLD;
    END IF;
    INSERT INTO item_log (op, item_id, old_name, new_name)
        VALUES (TG_OP, NEW.id, CASE WHEN TG_OP = 'UPDATE' THEN OLD.name END, NEW.name);
    RETURN NEW;
END
$$;

CREATE TRIGGER item_touch BEFORE INSERT OR UPDATE ON item
    FOR EACH ROW EXECUTE FUNCTION item_touch();

CREATE TRIGGER item_audit AFTER INSERT OR UPDATE OR DELETE ON item
    FOR EACH ROW EXECUTE FUNCTION item_audit();

Inside a trigger function:

NameWhat it holds
NEWThe new row, in INSERT and UPDATE row triggers. Assign to NEW.column in a BEFORE trigger to change what is stored.
OLDThe old row, in UPDATE and DELETE row triggers. It cannot be assigned to.
TG_OP'INSERT', 'UPDATE', 'DELETE' or 'TRUNCATE'.
TG_NAMEThe trigger's name.
TG_WHEN'BEFORE' or 'AFTER'.
TG_LEVEL'ROW' or 'STATEMENT'.
TG_TABLE_NAME, TG_RELNAMEThe table's name.
TG_TABLE_SCHEMA'public'.
TG_NARGS, TG_ARGV[i]The number of arguments given in CREATE TRIGGER, and each one as text.

A BEFORE row trigger returns NEW (possibly changed) to go on, or NULL to skip the row. The return value of an AFTER trigger is ignored. RAISE EXCEPTION fails the statement, and the statement's other rows are undone with it.

CREATE TRIGGER

text
CREATE [OR REPLACE] TRIGGER name
    { BEFORE | AFTER } event [OR event …]
    ON table
    [FOR [EACH] { ROW | STATEMENT }]
    [WHEN (condition)]
    EXECUTE { FUNCTION | PROCEDURE } function_name ( [argument, …] )
  • event is INSERT, UPDATE, UPDATE OF column, …, DELETE or TRUNCATE. With UPDATE OF, the trigger fires only when the UPDATE sets one of those columns.
  • Without FOR EACH ROW, the trigger is a statement trigger and runs once per statement.
  • WHEN (condition) limits a row trigger to rows the condition is true for. It may refer to NEW.column and OLD.column. A statement trigger's condition cannot (42P17).
  • The arguments are string constants, passed to the function as TG_ARGV.
  • A trigger with the same name on the same table fails with 42710 unless you write OR REPLACE.
sql
CREATE FUNCTION item_guard() RETURNS trigger LANGUAGE plpgsql AS $$
BEGIN
    IF NEW.qty < 0 THEN
        RAISE EXCEPTION 'qty must not be negative, got %', NEW.qty USING ERRCODE = '23514';
    END IF;
    RETURN NEW;
END
$$;

CREATE TRIGGER item_guard BEFORE INSERT ON item
    FOR EACH ROW WHEN (NEW.id > 100) EXECUTE FUNCTION item_guard();

DROP TRIGGER item_guard ON item;
DROP TRIGGER IF EXISTS item_guard ON item;

Dropping a table drops its triggers.

When triggers fire

  • Row triggers of the same timing run in order of their names. Each BEFORE trigger sees the NEW the previous one returned.
  • An AFTER row trigger runs right after its row is stored. PostgreSQL runs them at the end of the statement. The difference shows only when the trigger reads the table that fired it.
  • Statement triggers run once before and once after the statement.
  • A write to a table with triggers runs inside a transaction. If you are not in a block, the statement gets one of its own, so a trigger that fails takes back the whole statement. Inside a block, ROLLBACK takes back what the triggers wrote too.
  • Triggers fire for statements sent with the simple and the extended query protocol alike.

PL/pgSQL statements

DO blocks and trigger functions run this subset of PL/pgSQL. A statement outside it is refused with 0A000 ("PL/pgSQL … is not supported yet"), never skipped. A trigger function is checked when you create the trigger.

ConstructForm
DeclarationsDECLARE name type [:= expression | DEFAULT expression];, CONSTANT, and record variables, which take the shape of the row assigned to them
Assignmentname := expression;, name = expression;, NEW.column := expression;
ConditionsIF … THEN … [ELSIF … THEN …] [ELSE …] END IF;
LoopsLOOP … END LOOP;, WHILE condition LOOP … END LOOP;
Integer loopsFOR i IN [REVERSE] a..b [BY step] LOOP … END LOOP;
Query loopsFOR target IN query LOOP … END LOOP; and FOR target IN EXECUTE text LOOP …, where target is a record or one variable per column
Leaving loopsEXIT [WHEN condition];, CONTINUE [WHEN condition];
SQLINSERT, UPDATE, DELETE, SELECT and WITH statements, and DDL such as CREATE, ALTER, DROP, TRUNCATE, GRANT and REVOKE
Query into variablesSELECT … INTO [STRICT] a, b FROM …;
Dynamic SQLEXECUTE text_expression [INTO targets];, for example EXECUTE format('…', …)
Running for effectPERFORM expression_or_query;, NULL;
Messages and errorsRAISE [EXCEPTION | NOTICE | WARNING | INFO | LOG | DEBUG] 'format %', arg [USING ERRCODE = 'xxxxx'];
EndingRETURN; in a DO block; RETURN NEW | OLD | NULL; in a trigger function
Error handlingBEGIN … EXCEPTION WHEN condition [OR condition] THEN … END;

RAISE without a level is EXCEPTION, with SQLSTATE P0001 unless ERRCODE gives another. The other levels send a notice to the client and go on.

An EXCEPTION handler names conditions by their PostgreSQL names (unique_violation, foreign_key_violation, check_violation, not_null_violation, division_by_zero, serialization_failure, undefined_table, and the other common ones), by SQLSTATE 'xxxxx', or as OTHERS. Inside the handler, SQLSTATE and SQLERRM hold the error's code and message.

sql
CREATE TABLE tag (id int PRIMARY KEY, name text UNIQUE);
INSERT INTO tag VALUES (1, 'red');

BEGIN;
DO $$
BEGIN
    BEGIN
        INSERT INTO tag VALUES (2, 'red');
    EXCEPTION WHEN unique_violation THEN
        RAISE NOTICE 'skipped: %', SQLERRM;
    END;
END
$$;
COMMIT;

Inside a transaction block, a handled error rolls back to where its BEGIN … EXCEPTION block started, and the transaction goes on, as in PostgreSQL.

Not supported: %TYPE and %ROWTYPE, a nested DECLARE, block and loop labels, CASE statements, FOREACH, GET DIAGNOSTICS, cursors (OPEN, FETCH, CLOSE), COMMIT and ROLLBACK inside a block, CALL, ASSERT, RETURN NEXT and RETURN QUERY, and EXECUTE … USING.

Enum types

sql
CREATE TYPE status AS ENUM ('new', 'paid', 'shipped');

CREATE TABLE shipment (id int PRIMARY KEY, state status NOT NULL, history status[]);
INSERT INTO shipment VALUES (1, 'paid', '{new,paid}'), (2, 'new', '{new}');

SELECT id FROM shipment WHERE state < 'shipped' ORDER BY state;

ALTER TYPE status ADD VALUE 'cancelled';
ALTER TYPE status ADD VALUE IF NOT EXISTS 'returned' AFTER 'shipped';
ALTER TYPE status RENAME VALUE 'new' TO 'open';
ALTER TYPE status RENAME TO shipment_status;
  • A column of the type, or an array of it, takes only its labels. Another value fails with 22P02.
  • Values order by the labels' declared order in ORDER BY, in <, <=, >, >= and BETWEEN against a label or another column of the type, and in min and max.
  • enum_first(NULL::status), enum_last(NULL::status) and enum_range(NULL::status) (or enum_range(a, b)) return the labels.
  • ALTER TYPE … ADD VALUE can place the new label BEFORE or AFTER an existing one. A label that already exists fails with 42710.
  • DROP TYPE [IF EXISTS] name [, …] drops the type. A type still used by a column cannot be dropped (2BP01). Drop or change the columns first.
  • pg_type and pg_enum list the type and its labels.
  • CREATE TYPE makes enums only. Composite (AS (…)) and range types are refused with 0A000.

Domains

A domain is a base type with constraints and an optional default. Each column of the domain gets its checks, its NOT NULL and its default.

sql
CREATE DOMAIN positive_int AS int CHECK (VALUE > 0);
CREATE DOMAIN email AS text CONSTRAINT has_at CHECK (VALUE LIKE '%@%') NOT NULL;
CREATE DOMAIN five AS int DEFAULT 5;

CREATE TABLE account (id int PRIMARY KEY, credits positive_int, contact email, tier five);
INSERT INTO account (id, credits, contact) VALUES (1, 10, 'a@example.com');
INSERT INTO account (id, credits, contact) VALUES (2, 0, 'b@example.com');
text
ERROR:  value for domain positive_int violates check constraint "positive_int_check"

CREATE DOMAIN name [AS] base_type [COLLATE collation] [DEFAULT expression] [NOT NULL | NULL] [[CONSTRAINT name] CHECK (expression using VALUE)] …

  • A failed check is 23514. A NULL in a NOT NULL domain column is 23502.
  • An unnamed check is named as PostgreSQL names it: <domain>_check, then <domain>_check1, and so on.
  • A cast to a domain, x::positive_int or CAST(x AS positive_int), checks the value against the domain's constraints.
  • A domain's default applies to a column that has no default of its own.

ALTER DOMAIN changes the domain and every column of it in one statement. A failure undoes the whole statement.

sql
ALTER DOMAIN positive_int ADD CONSTRAINT under_1000 CHECK (VALUE < 1000);
ALTER DOMAIN positive_int RENAME CONSTRAINT under_1000 TO small;
ALTER DOMAIN positive_int DROP CONSTRAINT IF EXISTS small;
ALTER DOMAIN positive_int SET NOT NULL;
ALTER DOMAIN positive_int DROP NOT NULL;
ALTER DOMAIN five SET DEFAULT 6;
ALTER DOMAIN five DROP DEFAULT;
ALTER DOMAIN five RENAME TO tier_level;
  • ADD … CHECK and SET NOT NULL first test every existing row. A row that fails reports its column and table (23514 or 23502).
  • VALIDATE CONSTRAINT name is accepted. Every constraint is already validated when it is added.
  • OWNER TO and SET SCHEMA public are accepted and change nothing.
  • DROP DOMAIN [IF EXISTS] name [, …] drops domains. A domain still used by a column cannot be dropped (2BP01).

Row-level security

Row-level security limits the rows each role can read and write in a table. Turn it on per table, then add policies:

sql
CREATE TABLE note (id int PRIMARY KEY, owner text, body text);
ALTER TABLE note ENABLE ROW LEVEL SECURITY;

CREATE POLICY own_notes ON note
    FOR ALL TO PUBLIC
    USING (owner = current_user)
    WITH CHECK (owner = current_user);
  • CREATE POLICY name ON table [AS PERMISSIVE | RESTRICTIVE] [FOR ALL | SELECT | INSERT | UPDATE | DELETE] [TO role [, …]] [USING (condition)] [WITH CHECK (condition)]. The defaults are PERMISSIVE, FOR ALL and TO PUBLIC.
  • A table with row-level security on and no policy for a command shows a role no rows and lets it write none.
  • Permissive policies are combined with OR, restrictive ones with AND. A policy without WITH CHECK checks new rows with its USING condition. A new row that fails the check fails with 42501.
  • The table's owner, superusers and roles with BYPASSRLS are exempt. ALTER TABLE … FORCE ROW LEVEL SECURITY applies the policies to the owner too, and NO FORCE reverses it. DISABLE ROW LEVEL SECURITY turns it off.
  • ALTER POLICY name ON table can change TO, USING and WITH CHECK, or RENAME TO. To change AS or FOR, drop the policy and create it again.
  • DROP POLICY [IF EXISTS] name ON table drops one. Dropping or renaming a table takes its policies with it.
  • A write to a table with row-level security must be the statement itself. Inside a CTE or a MERGE, it is refused with 0A000.

Roles and privileges are described in Security.

Comments

COMMENT ON … IS '…' is accepted so that migrations and dump files run, but the comment is not stored. obj_description, col_description and shobj_description always return NULL.

Transactions and schema objects

Creating, changing and dropping views, materialized views, sequences, functions, procedures, triggers, enum types and domains are transactional. Inside a block they are visible only to your session until COMMIT, and ROLLBACK undoes them. A migration can create a type, a domain and the tables that use them in one block.

Sequence values are the exception: nextval is never rolled back. Which table statements are transactional is listed in Transactions.

Listing what a database holds

Drivers, ORMs and psql read the same catalogues they read on PostgreSQL. psql's \d and \d+ describe a table, and an ORM's schema tools can read its tables, columns, keys and indexes.

These information_schema views exist. Write them with the information_schema. prefix:

ViewWhat it lists
information_schema.tablesTables (BASE TABLE) and views (VIEW)
information_schema.columnsColumns of tables and views, with types, defaults, identity and generated columns
information_schema.viewsViews
information_schema.sequencesSequences, including those behind serial columns
information_schema.table_constraints, key_column_usage, referential_constraintsPrimary keys, unique keys, foreign keys and checks

information_schema.table_privileges, role_table_grants, usage_privileges and routine_privileges list the grants.

These pg_catalog relations exist: pg_class, pg_namespace, pg_attribute, pg_attrdef, pg_constraint, pg_index, pg_indexes, pg_tables, pg_views, pg_matviews, pg_sequences, pg_type, pg_enum, pg_range, pg_proc, pg_collation, pg_am, pg_database, pg_roles, pg_user, pg_policy, pg_inherits, pg_partitioned_table, pg_stat_user_tables and pg_replication_slots. In pg_class, a view has relkind v, a materialized view m, and a sequence S.

pg_description, pg_trigger, pg_rewrite, pg_depend, pg_extension, pg_statistic_ext and the pg_publication relations exist so that tools' queries run, but they have no rows.

sql
SELECT table_name, table_type
FROM information_schema.tables
WHERE table_schema = 'public'
ORDER BY 1;

SELECT sequence_name, data_type, start_value, increment
FROM information_schema.sequences;

RasterizedDB also has its own statements that describe a database, such as SHOW TABLES, SHOW COLUMNS FROM table and SHOW SCHEMA MAP. See Monitoring.

Internal tables

Views, sequences, functions, triggers, types, policies and privileges are stored in system tables whose names begin with __rdb_. They are hidden from the catalogues. Do not read or write them directly: change these objects only through the statements on this page.

Any table whose name begins with two underscores (__) is left out of the catalogues. Do not give your own tables such names.

Limits

  • One namespace. Schemas are accepted but not created. A qualified name refers to the object named by its last part, so two schemas cannot hold objects with the same name. search_path is shown but not followed.
  • Views are read-only. There are no updatable views, no WITH CHECK OPTION and no INSTEAD OF triggers. CREATE TEMPORARY VIEW, CREATE RECURSIVE VIEW (use WITH RECURSIVE inside the view), view options (WITH (…)) and ALTER VIEW forms other than RENAME TO are refused. CREATE VIEW IF NOT EXISTS is a syntax error, as in PostgreSQL. A view whose query returns two columns with the same name cannot be given a column list.
  • Materialized views have no REFRESH … CONCURRENTLY.
  • Sequences: CREATE TEMPORARY SEQUENCE is refused. A serial or identity column's counter restarts above the largest value stored in its column, so after a restart it can hand out values that a rolled-back transaction had taken. PostgreSQL leaves a gap there. No key is ever handed out twice.
  • Functions:
    • The languages are sql and plpgsql. C functions and other languages are refused.
    • Functions are distinguished by name and number of arguments, not by argument types. Two functions with the same name and the same number of arguments cannot both exist.
    • Parameter defaults and OUT, INOUT and VARIADIC parameters are refused. So are a SET clause, WINDOW functions and SQL bodies of more than one statement.
    • A PL/pgSQL function can be called as a value only when its body is BEGIN RETURN expression; END.
    • There is no ALTER FUNCTION. Use CREATE OR REPLACE FUNCTION.
  • Procedures must be LANGUAGE sql.
  • Triggers:
    • The function must be LANGUAGE plpgsql.
    • UPDATE and DELETE row triggers need a table with a primary key.
    • On a table with triggers, INSERT … ON CONFLICT, UPDATE … FROM and DELETE … USING are refused with 0A000.
    • INSTEAD OF, constraint triggers, DEFERRABLE, transition tables (REFERENCING) and TRUNCATE … FOR EACH ROW are refused.
    • Triggers do not appear in pg_trigger.
  • PL/pgSQL covers the subset in PL/pgSQL statements. Outside a transaction block, the statements of a DO block commit one by one. Inside a multi-statement query string, which runs as one implicit transaction, an EXCEPTION handler does not catch the error: the error fails the whole string.
  • Enum types: a column of an enum type is sent to clients as text, and information_schema reports it as text. The labels' order applies only where the column is certain: comparing with a text expression or a parameter compares the text instead. A parameter that is not a label matches nothing, where PostgreSQL raises 22P02. ALTER TABLE … ALTER COLUMN … TYPE to an enum and DROP TYPE … CASCADE with columns of the type are refused.
  • Domains: a cast to a domain is typed as its base type (pg_typeof(5::positive_int) is integer). A cast of an expression that calls a volatile function (random()::positive_int) is refused. ADD CONSTRAINT … NOT VALID, SET SCHEMA to another schema, DROP DOMAIN … CASCADE with columns of the domain and ALTER COLUMN … TYPE to a domain are refused. A NULL in a NOT NULL domain column reports the column's message, not domain … does not allow null values. pg_type lists no domains, so psql's \dD shows none.
  • Comments are not stored.
✓ page rendered in 223 µs axum + tera + htmx · no other javascript