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 SCHEMAandDROP SCHEMAsucceed and create or remove nothing.- A schema-qualified name refers to the object named by its last part.
app.orders,public.orders,"public"."orders"andordersare the same table. SET search_path TO …is accepted, andSHOW search_pathandcurrent_setting('search_path')return what you set. It does not change how names are found.current_schema()returnspublic, and the catalogues report every object in schemapublic.
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 tableBecause 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.
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; 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,VALUESorTABLE. It may read other views. A view whose query names a missing relation is refused with42P01. - 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.
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
ALTER VIEW big_orders RENAME TO large_orders;
DROP VIEW IF EXISTS totals;
DROP VIEW large_orders CASCADE;DROP VIEWtakes several names, separated by commas.- A view that other views read cannot be dropped (
2BP01) unless you addCASCADE, which drops those views too. - A table that a view reads cannot be dropped either.
DROP TABLE … CASCADEdrops 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 VIEWsupports onlyRENAME TO. Other forms fail with0A000.
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.
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; -- 4CREATE MATERIALIZED VIEW … WITH NO DATAcreates it empty. The firstREFRESHfills it.CREATE MATERIALIZED VIEW IF NOT EXISTSskips an existing one.REFRESH MATERIALIZED VIEWreplaces the rows in one step. Inside a transaction block the refresh belongs to the block, soROLLBACKundoes it.ALTER MATERIALIZED VIEW name RENAME TO new_namerenames it, andDROP MATERIALIZED VIEW a, bdrops one or more.- Writes to a materialized view fail with
42809. OnlyREFRESHchanges its rows. REFRESH MATERIALIZED VIEW CONCURRENTLYis refused. A plainREFRESHis already atomic.
Sequences
A sequence hands out increasing (or decreasing) integers. It is the usual source of surrogate keys.
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; id
------
1000
1010Sequence options
CREATE SEQUENCE [IF NOT EXISTS] name [options] takes these options, in any order. The defaults are PostgreSQL's.
| Option | Default | What it does |
|---|---|---|
AS smallint | integer | bigint | bigint | The value type. It sets the default bounds. |
INCREMENT [BY] n | 1 | The step. A negative step counts down. Zero is refused. |
MINVALUE n / NO MINVALUE | 1 going up; the type's minimum going down | The lowest value. |
MAXVALUE n / NO MAXVALUE | the type's maximum going up; -1 going down | The highest value. |
START [WITH] n | MINVALUE going up, MAXVALUE going down | The first value nextval returns. |
CACHE n | 1 | Accepted. Must be at least 1. |
CYCLE / NO CYCLE | NO CYCLE | With CYCLE, the sequence wraps to the other bound. Without it, nextval past a bound fails with 2200H. |
OWNED BY table.column / OWNED BY NONE | none | Ties 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
| Call | What 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:
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
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 SEQUENCEtakes the same options asCREATE SEQUENCE, plusRESTART(back toSTART) orRESTART [WITH] n, andRENAME TO.DROP SEQUENCEtakes several names. A sequence that a column default reads cannot be dropped (2BP01). WithCASCADEit 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:
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; -- 51pg_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
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, orBEGIN ATOMIC statement; END. - The body is one statement. A body of several statements is refused when the function is called.
RETURNS voidis accepted.IMMUTABLE,STABLE,VOLATILE,STRICT,CALLED ON NULL INPUT,LEAKPROOF,PARALLEL …,COST nandROWS nare 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:
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:
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
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. UseOR REPLACE. CREATE OR REPLACEcannot change the return type (42P13).DROP FUNCTIONwithout 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 DEFINERmakes it run with its owner's privileges. See Security. Before 1.1.0,SECURITY DEFINERwas accepted and ignored.
Procedures
A procedure is a list of SQL statements run by CALL, in the caller's transaction.
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.
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 with0A000.RETURNwith 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:
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:
| Name | What it holds |
|---|---|
NEW | The new row, in INSERT and UPDATE row triggers. Assign to NEW.column in a BEFORE trigger to change what is stored. |
OLD | The old row, in UPDATE and DELETE row triggers. It cannot be assigned to. |
TG_OP | 'INSERT', 'UPDATE', 'DELETE' or 'TRUNCATE'. |
TG_NAME | The trigger's name. |
TG_WHEN | 'BEFORE' or 'AFTER'. |
TG_LEVEL | 'ROW' or 'STATEMENT'. |
TG_TABLE_NAME, TG_RELNAME | The 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
CREATE [OR REPLACE] TRIGGER name
{ BEFORE | AFTER } event [OR event …]
ON table
[FOR [EACH] { ROW | STATEMENT }]
[WHEN (condition)]
EXECUTE { FUNCTION | PROCEDURE } function_name ( [argument, …] )eventisINSERT,UPDATE,UPDATE OF column, …,DELETEorTRUNCATE. WithUPDATE OF, the trigger fires only when theUPDATEsets 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 toNEW.columnandOLD.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
42710unless you writeOR REPLACE.
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
BEFOREtrigger sees theNEWthe previous one returned. - An
AFTERrow 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,
ROLLBACKtakes 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.
| Construct | Form |
|---|---|
| Declarations | DECLARE name type [:= expression | DEFAULT expression];, CONSTANT, and record variables, which take the shape of the row assigned to them |
| Assignment | name := expression;, name = expression;, NEW.column := expression; |
| Conditions | IF … THEN … [ELSIF … THEN …] [ELSE …] END IF; |
| Loops | LOOP … END LOOP;, WHILE condition LOOP … END LOOP; |
| Integer loops | FOR i IN [REVERSE] a..b [BY step] LOOP … END LOOP; |
| Query loops | FOR target IN query LOOP … END LOOP; and FOR target IN EXECUTE text LOOP …, where target is a record or one variable per column |
| Leaving loops | EXIT [WHEN condition];, CONTINUE [WHEN condition]; |
| SQL | INSERT, UPDATE, DELETE, SELECT and WITH statements, and DDL such as CREATE, ALTER, DROP, TRUNCATE, GRANT and REVOKE |
| Query into variables | SELECT … INTO [STRICT] a, b FROM …; |
| Dynamic SQL | EXECUTE text_expression [INTO targets];, for example EXECUTE format('…', …) |
| Running for effect | PERFORM expression_or_query;, NULL; |
| Messages and errors | RAISE [EXCEPTION | NOTICE | WARNING | INFO | LOG | DEBUG] 'format %', arg [USING ERRCODE = 'xxxxx']; |
| Ending | RETURN; in a DO block; RETURN NEW | OLD | NULL; in a trigger function |
| Error handling | BEGIN … 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.
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
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<,<=,>,>=andBETWEENagainst a label or another column of the type, and inminandmax. enum_first(NULL::status),enum_last(NULL::status)andenum_range(NULL::status)(orenum_range(a, b)) return the labels.ALTER TYPE … ADD VALUEcan place the new labelBEFOREorAFTERan existing one. A label that already exists fails with42710.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_typeandpg_enumlist the type and its labels.CREATE TYPEmakes enums only. Composite (AS (…)) and range types are refused with0A000.
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.
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');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 aNOT NULLdomain column is23502. - An unnamed check is named as PostgreSQL names it:
<domain>_check, then<domain>_check1, and so on. - A cast to a domain,
x::positive_intorCAST(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.
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 … CHECKandSET NOT NULLfirst test every existing row. A row that fails reports its column and table (23514or23502).VALIDATE CONSTRAINT nameis accepted. Every constraint is already validated when it is added.OWNER TOandSET SCHEMA publicare 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:
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 arePERMISSIVE,FOR ALLandTO 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 withAND. A policy withoutWITH CHECKchecks new rows with itsUSINGcondition. A new row that fails the check fails with42501. - The table's owner, superusers and roles with
BYPASSRLSare exempt.ALTER TABLE … FORCE ROW LEVEL SECURITYapplies the policies to the owner too, andNO FORCEreverses it.DISABLE ROW LEVEL SECURITYturns it off. ALTER POLICY name ON tablecan changeTO,USINGandWITH CHECK, orRENAME TO. To changeASorFOR, drop the policy and create it again.DROP POLICY [IF EXISTS] name ON tabledrops 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 with0A000.
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:
| View | What it lists |
|---|---|
information_schema.tables | Tables (BASE TABLE) and views (VIEW) |
information_schema.columns | Columns of tables and views, with types, defaults, identity and generated columns |
information_schema.views | Views |
information_schema.sequences | Sequences, including those behind serial columns |
information_schema.table_constraints, key_column_usage, referential_constraints | Primary 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.
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_pathis shown but not followed. - Views are read-only. There are no updatable views, no
WITH CHECK OPTIONand noINSTEAD OFtriggers.CREATE TEMPORARY VIEW,CREATE RECURSIVE VIEW(useWITH RECURSIVEinside the view), view options (WITH (…)) andALTER VIEWforms other thanRENAME TOare refused.CREATE VIEW IF NOT EXISTSis 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 SEQUENCEis 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
sqlandplpgsql. 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,INOUTandVARIADICparameters are refused. So are aSETclause,WINDOWfunctions 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. UseCREATE OR REPLACE FUNCTION.
- The languages are
- Procedures must be
LANGUAGE sql. - Triggers:
- The function must be
LANGUAGE plpgsql. UPDATEandDELETErow triggers need a table with a primary key.- On a table with triggers,
INSERT … ON CONFLICT,UPDATE … FROMandDELETE … USINGare refused with0A000. INSTEAD OF, constraint triggers,DEFERRABLE, transition tables (REFERENCING) andTRUNCATE … FOR EACH ROWare refused.- Triggers do not appear in
pg_trigger.
- The function must be
- PL/pgSQL covers the subset in PL/pgSQL statements. Outside a transaction block, the statements of a
DOblock commit one by one. Inside a multi-statement query string, which runs as one implicit transaction, anEXCEPTIONhandler 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, andinformation_schemareports it astext. 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 raises22P02.ALTER TABLE … ALTER COLUMN … TYPEto an enum andDROP TYPE … CASCADEwith columns of the type are refused. - Domains: a cast to a domain is typed as its base type (
pg_typeof(5::positive_int)isinteger). A cast of an expression that calls a volatile function (random()::positive_int) is refused.ADD CONSTRAINT … NOT VALID,SET SCHEMAto another schema,DROP DOMAIN … CASCADEwith columns of the domain andALTER COLUMN … TYPEto a domain are refused. A NULL in aNOT NULLdomain column reports the column's message, notdomain … does not allow null values.pg_typelists no domains, sopsql's\dDshows none. - Comments are not stored.