psql-style and generate commands (F4)

A command line in the query tab: psql's list and describe meta-commands, and pgtc's generate commands, which write DML, PL/pgSQL or DDL for a relation into the editor. All catalog reads use the tab's session.

The command line

The psql command window
F4 in a query tab.

Completing names

Ctrl+Space / Alt+/ completes the argument, never by itself. Offered are the relation kinds of the command (dt tables, dtv tables and views, d / dp all five kinds, generate commands their Works on kinds, gp / gf schemas).

The list of schemas and tables under the F4 input
dt + Ctrl+Space: schemas first, then tables.

List commands

CommandLists
lDatabases
dnSchemas
dtTables, partitioned tables included
dv, dm, dsViews, materialized views, sequences
diIndexes, partitioned indexes included, with their table
dfFunctions, procedures, aggregates and window functions
dTData types, without array types and row types of relations
dDDomains
du, dgRoles
dxExtensions
dbTablespaces
dpACLs of tables, views, materialized views, sequences and foreign tables, with column privileges
d (no name)Tables, views, materialized views, sequences and foreign tables

Modifiers

WriteMeaning
dtv, dti, …The letters t v m i s E (foreign tables) combine.
SInclude system objects. Without a pattern and without S, schemas pg_* and information_schema (du: roles pg_*) are left out; with a pattern they are always searched. TOAST schemas never appear.
+More columns: size, description, owner, ACL, … depending on the command.

Patterns

psql's syntax: *, ?, schema.name, "Exact Name"; unquoted text is folded to lower case. Each part becomes an anchored regular expression matched with ~.

Describing one object: d name

The result of d sales.customer
d sales.customer: one result set per section.

For a table, view, materialized view, sequence or foreign table. Empty sections are left out.

Result setColumns
RelationSchema, name, type, owner, description.
ColumnsColumn, type, collation when not the type's default, not null, default, identity or generated always as (…) stored. d+: storage and description.
IndexesName, kind (primary key, unique or empty), pg_get_indexdef.
ConstraintsName, type, pg_get_constraintdef.
TriggersName and pg_get_triggerdef; no internal triggers.
DefinitionViews and materialized views: pg_get_viewdef.

conninfo and ?

CommandWhat it does
conninfoWrites database, user, host, port, sslmode and the server's major version into Messages. Nothing is sent to the server; SSL mode is the configured value, not whether the session is encrypted.
?All commands as a result set.

What is not there

\c (a query tab is bound to one database), \i, \o (see SQL files and Export result), \copy, \x, \h, \set, \password, \g, \watch, \if. A \ line in a script is not a command: it is sent to the server as it is.

Generate commands: SQL for a table

Each reads the relation's columns (pg_attribute) and primary-key / unique constraints (pg_constraint) and inserts a statement at the editor cursor; nothing is executed. gtg, gtj, gtr and gtv also read foreign keys; gp and gf read nothing.

CommandWritesWorks on
gts tableSELECT with every columntables, views, foreign tables
gti tableINSERTtables, views, foreign tables
gtu tableUPDATE … WHERE keytables, views, foreign tables
gtd tableDELETE … WHERE keytables, views, foreign tables
gto tableINSERT … ON CONFLICT … DO UPDATEtables, views, foreign tables
gtm tableMERGE (PostgreSQL 15+)tables
gtc tablePL/pgSQL cursor looptables, views, foreign tables
gtsi tablePL/pgSQL variables and SELECT … INTO STRICT by keytables, views, foreign tables
gtrb, gtra tableTrigger function and row trigger, before / aftertables
gtsb, gtsa tableTrigger function and statement trigger, before / aftertables
gtv table table …CREATE VIEW joining the tables on their foreign keystables, views, foreign tables
gtg table [rows]Test data from generate_series, 100 rows by defaulttables
gtj tableSELECT joined to every referenced tabletables
gtr tableSELECTs of the rows that reference a rowtables
gtau tableAudit table, trigger function and triggertables
gp [schema]Empty PL/pgSQL procedure (default schema public)—
gpi, gpu, gpd, gpo tablePL/pgSQL procedure: insert / update by key / delete by key / upsert a rowtables
gf [schema]Empty PL/pgSQL function (default schema public)—
gfr, gfs, gft, gfe, gfj tablePL/pgSQL function: one row by key / RETURNS SETOF / RETURNS TABLE / row exists / row as jsonbtables, views, foreign tables

Tables = plain and partitioned. Materialized views and sequences are never accepted.

Common rules

The examples are for sales.customer: primary key customerid, filled from a sequence.

gts — SELECT

One column per line, no WHERE.

gti — INSERT

After <code>gti sales.customer</code>.
gti sales.customer
INSERT INTO sales.customer (
    personid,     -- integer
    storeid,      -- integer
    territoryid,  -- integer
    rowguid,      -- uuid, NOT NULL, default uuid_generate_v1()
    modifieddate  -- timestamp without time zone, NOT NULL, default now()
) VALUES (
    [personid],
    [storeid],
    [territoryid],
    [rowguid],
    [modifieddate]
);

Left out: generated columns, identity columns and columns whose default calls nextval(). Columns with any other default are listed. Nothing left: INSERT INTO … DEFAULT VALUES.

gtu — UPDATE, gtd — DELETE

WHERE on the key. UPDATE sets every non-key column except generated and GENERATED ALWAYS identity columns; with none left, the key columns. A table with nothing that can be set gets a comment instead.

gto — upsert (INSERT … ON CONFLICT)

gtm — MERGE

MERGE INTO sales.customer AS t
USING (VALUES (
    [customerid]::integer,                       -- integer, NOT NULL, default nextval(…)
    [personid]::integer,                         -- integer
    …
)) AS s (customerid, personid, storeid, territoryid, rowguid, modifieddate)
ON t.customerid = s.customerid                   -- primary key
WHEN MATCHED THEN
    UPDATE SET
        personid = s.personid,
        …
WHEN NOT MATCHED THEN
    INSERT (customerid, personid, storeid, territoryid, rowguid, modifieddate)
    VALUES (s.customerid, s.personid, s.storeid, s.territoryid, s.rowguid, s.modifieddate);

gtc — cursor loop (PL/pgSQL)

A DECLARE … BEGIN … END block: explicit cursor over all columns, FETCH into a record, the fields listed as comments, --PROCESS THE ROW HERE. No placeholders: it runs as it is in PL/pgSQL mode.

gtsi — read one row into variables (PL/pgSQL)

One v_column variable per column, declared with %TYPE, and SELECT … INTO STRICT … WHERE key. A column name that is not a plain identifier gets a usable variable name ("Due Date" → v_due_date).

gtrb, gtra, gtsb, gtsa — trigger function and trigger

CREATE OR REPLACE FUNCTION schema.[function_name]() RETURNS trigger with a TG_OP branch per event, then CREATE TRIGGER … INSERT OR UPDATE OR DELETE.

CommandFiresTrigger nameThe function
gtrbBEFORE … FOR EACH ROWcustomer_rb_trgLists the NEW. / OLD. fields; returns NEW or OLD per branch.
gtraAFTER … FOR EACH ROWcustomer_ra_trgLists the fields; no RETURN in the branches.
gtsbBEFORE … FOR EACH STATEMENTcustomer_sb_trgNo fields; also fires for TRUNCATE, with its own branch.
gtsaAFTER … FOR EACH STATEMENTcustomer_sa_trg

gtv — a view over several tables

gtv sales.salesorderheader sales.customer sales.salesterritory
A generated view
The generated view.

gtg — test data

gtg sales.customer 500
INSERT INTO sales.customer (
    personid,
    storeid,
    territoryid
)
SELECT
    p1.businessentityid,  -- FK_Customer_Person_PersonID, a random row of person.person
    p2.businessentityid,  -- FK_Customer_Store_StoreID, a random row of sales.store
    p3.territoryid        -- FK_Customer_SalesTerritory_TerritoryID, a random row of sales.salesterritory
FROM generate_series(1, 500) AS g
-- "WHERE g IS NOT NULL": a new random row for each row, not one for all
LEFT JOIN LATERAL (SELECT businessentityid FROM person.person WHERE g IS NOT NULL ORDER BY random() LIMIT 1) AS p1 ON true
…

gtj — join the parent tables

The joins of gtv for the table and everything its foreign keys reference, as a plain SELECT. One join per constraint (a table referenced twice is joined twice). Foreign keys a partition inherits from its parent are left out.

gtr — rows that reference a row

-- FK_SalesOrderHeader_Customer_CustomerID
SELECT
    salesorderid,
    orderdate,
    customerid,
    totaldue
FROM sales.salesorderheader
WHERE customerid = [customerid];  -- sales.customer.customerid: integer

One SELECT per foreign-key constraint that references the table. None: No foreign key references ….

gtau — audit every change

Writes three statements:

gp — an empty procedure

CREATE OR REPLACE PROCEDURE schema.[procedure_name]() LANGUAGE plpgsql with an empty body. The schema is not checked. With a parameter dialog: the developer template Create procedure.

gpi, gpu, gpd, gpo — procedures for one row of a table

CREATE OR REPLACE PROCEDURE sales.[procedure_name](
    p_personid          integer,
    p_storeid           integer,
    p_territoryid       integer,
    p_rowguid           uuid,                         -- NOT NULL, default uuid_generate_v1()
    p_modifieddate      timestamp without time zone,  -- NOT NULL, default now()
    INOUT p_customerid  integer DEFAULT NULL          -- primary key, filled by the database
)
LANGUAGE plpgsql
AS $$
BEGIN
    INSERT INTO sales.customer (…) VALUES (…)
    RETURNING customerid INTO p_customerid;
END;
$$;
CommandParametersBody
gpiThe columns of gti; keys the database fills as INOUT … DEFAULT NULLINSERT … RETURNING … INTO
gpuThe key, then the columns of gtuUPDATE … WHERE key; RAISE EXCEPTION if no row was found
gpdThe keyDELETE … WHERE key; RAISE EXCEPTION if no row was found
gpoThe columns of gto, the key includedINSERT … ON CONFLICT (key) DO UPDATE

gf — an empty function

As gp: CREATE OR REPLACE FUNCTION schema.[function_name]() RETURNS [return_type] with RETURN [value]. With a parameter dialog: the developer template Create function.

gfr, gfs, gft, gfe, gfj — functions that read a table

Declared STABLE, created in the table's schema as [function_name].

CommandParametersReturnsBody
gfrThe keyThe row type of the tableSELECT … INTO a row variable; NULL when not found
gfs—SETOF the tableRETURN QUERY SELECT … WHERE [condition]
gft—TABLE (…), every columnAs gfs, with T1. before every column
gfeThe keybooleanRETURN EXISTS (SELECT 1 … WHERE key)
gfjThe keyjsonbRETURN (SELECT to_jsonb(T1) … WHERE key); NULL when not found