Question: Write the PL/pgSQL object from PostgreSQL regression test 'psql' (example 233).

$$ LANGUAGE plpgsql;

\set ON_ERROR_ROLLBACK on
\echo '# ON_ERROR_ROLLBACK:' :ON_ERROR_ROLLBACK
\echo '# AUTOCOMMIT:' :AUTOCOMMIT

BEGIN;
CREATE TABLE bla(s NO_SUCH_TYPE);               -- fails
CREATE TABLE bla(s TEXT);                       -- succeeds
SELECT psql_error('oops!');                     -- fails
INSERT INTO bla VALUES ('Calvin'), ('Hobbes');
COMMIT;

SELECT * FROM bla ORDER BY 1;

BEGIN;
INSERT INTO bla VALUES ('Susie');         -- succeeds
-- now with combined queries
INSERT INTO bla VALUES ('Rosalyn') \;     -- will rollback
SELECT 'before error' AS show \;          -- will show nevertheless!
  SELECT psql_error('boum!') \;           -- failure
  SELECT 'after error' AS noshow;         -- hidden by preceding error
INSERT INTO bla(s) VALUES ('Moe') \;      -- will rollback
  SELECT psql_error('bam!');
INSERT INTO bla VALUES ('Miss Wormwood'); -- succeeds
COMMIT;
SELECT * FROM bla ORDER BY 1;

-- some with autocommit off
\set AUTOCOMMIT off
\echo '# AUTOCOMMIT:' :AUTOCOMMIT

-- implicit BEGIN
INSERT INTO bla VALUES ('Dad');           -- succeeds
SELECT psql_error('bad!');                -- implicit partial rollback

INSERT INTO bla VALUES ('Mum') \;         -- will rollback
SELECT COUNT(*) AS "#mum"
FROM bla WHERE s = 'Mum' \;               -- but be counted here
SELECT psql_error('bad!');                -- implicit partial rollback
COMMIT;

SELECT COUNT(*) AS "#mum"
FROM bla WHERE s = 'Mum' \;               -- no mum here
SELECT * FROM bla ORDER BY 1;
COMMIT;

-- reset all
\set AUTOCOMMIT on
\set ON_ERROR_ROLLBACK off
\echo '# final ON_ERROR_ROLLBACK:' :ON_ERROR_ROLLBACK
DROP TABLE bla;
DROP FUNCTION psql_error;

-- check describing invalid multipart names
\dA regression.heap
\dA nonesuch.heap
\dt host.regression.pg_catalog.pg_class
\dt |.pg_catalog.pg_class
\dt nonesuch.pg_catalog.pg_class
\da host.regression.pg_catalog.sum
\da +.pg_catalog.sum
\da nonesuch.pg_catalog.sum
\dAc nonesuch.brin
\dAc regression.brin
\dAf nonesuch.brin
\dAf regression.brin
\dAo nonesuch.brin
\dAo regression.brin
\dAp nonesuch.brin
\dAp regression.brin
\db nonesuch.pg_default
\db regression.pg_default
\dc host.regression.public.conversion
\dc (.public.conversion
\dc nonesuch.public.conversion
\dC host.regression.pg_catalog.int8
\dC ).pg_catalog.int8
\dC nonesuch.pg_catalog.int8
\dd host.regression.pg_catalog.pg_class
\dd [.pg_catalog.pg_class
\dd nonesuch.pg_catalog.pg_class
\dD host.regression.public.gtestdomain1
\dD ].public.gtestdomain1
\dD nonesuch.public.gtestdomain1
\ddp host.regression.pg_catalog.pg_class
\ddp {.pg_catalog.pg_class
\ddp nonesuch.pg_catalog.pg_class
\dE host.regression.public.ft
\dE }.public.ft
\dE nonesuch.public.ft
\di host.regression.public.tenk1_hundred
\di ..public.tenk1_hundred
\di nonesuch.public.tenk1_hundred
\dm host.regression.public.mvtest_bb
\dm ^.public.mvtest_bb
\dm nonesuch.public.mvtest_bb
\ds host.regression.public.check_seq
\ds regression|mydb.public.check_seq
\ds nonesuch.public.check_seq
\dt host.regression.public.b_star
\dt regres+ion.public.b_star
\dt nonesuch.public.b_star
\dv host.regression.public.shoe
\dv regress(ion).public.shoe
\dv nonesuch.public.shoe
\des nonesuch.server
\des regression.server
\des nonesuch.server
\des regression.server
\des nonesuch.username
\des regression.username
\dew nonesuch.fdw
\dew regression.fdw
\df host.regression.public.namelen
\df regres[qrstuv]ion.public.namelen
\df nonesuch.public.namelen
\dF host.regression.pg_catalog.arabic
\dF regres{1,2}ion.pg_catalog.arabic
\dF nonesuch.pg_catalog.arabic
\dFd host.regression.pg_catalog.arabic_stem
\dFd regres?ion.pg_catalog.arabic_stem
\dFd nonesuch.pg_catalog.arabic_stem
\dFp host.regression.pg_catalog.default
\dFp ^regression.pg_catalog.default
\dFp nonesuch.pg_catalog.default
\dFt host.regression.pg_catalog.ispell
\dFt regression$.pg_catalog.ispell
\dFt nonesuch.pg_catalog.ispell
\dg nonesuch.pg_database_owner
\dg regression.pg_database_owner
\dL host.regression.plpgsql
\dL *.plpgsql
\dL nonesuch.plpgsql
\dn host.regression.public
\dn """".public
\dn nonesuch.public
\do host.regression.public.!=-
\do "regression|mydb".public.!=-
\do nonesuch.public.!=-
\dO host.regression.pg_catalog.POSIX
\dO .pg_catalog.POSIX
\dO nonesuch.pg_catalog.POSIX
\dp host.regression.public.a_star
\dp "regres+ion".public.a_star
\dp nonesuch.public.a_star
\dP host.regression.public.mlparted
\dP "regres(sion)".public.mlparted
\dP nonesuch.public.mlparted
\drds nonesuch.lc_messages
\drds regression.lc_messages
\dRp public.mypub
\dRp regression.mypub
\dRs public.mysub
\dRs regression.mysub
\dT host.regression.public.widget
\dT "regression{1,2}".public.widget
\dT nonesuch.public.widget
\dx regression.plpgsql
\dx nonesuch.plpgsql
\dX host.regression.public.func_deps_stat
\dX "^regression$".public.func_deps_stat
\dX nonesuch.public.func_deps_stat
\dy regression.myevt
\dy nonesuch.myevt

-- check that dots within quoted name segments are not counted
\dA "no.such.access.method"
\dt "no.such.table.relation"
\da "no.such.aggregate.function"
\dAc "no.such.operator.class"
\dAf "no.such.operator.family"
\dAo "no.such.operator.of.operator.family"
\dAp "no.such.operator.support.function.of.operator.family"
\db "no.such.tablespace"
\dc "no.such.conversion"
\dC "no.such.cast"
\dd "no.such.object.description"
\dD "no.such.domain"
\ddp "no.such.default.access.privilege"
\di "no.such.index.relation"
\dm "no.such.materialized.view"
\ds "no.such.relation"
\dt "no.such.relation"
\dv "no.such.relation"
\des "no.such.foreign.server"
\dew "no.such.foreign.data.wrapper"
\df "no.such.function"
\dF "no.such.text.search.configuration"
\dFd "no.such.text.search.dictionary"
\dFp "no.such.text.search.parser"
\dFt "no.such.text.search.template"
\dg "no.such.role"
\dL "no.such.language"
\dn "no.such.schema"
\do "no.such.operator"
\dO "no.such.collation"
\dp "no.such.access.privilege"
\dP "no.such.partitioned.relation"
\drds "no.such.setting"
\dRp "no.such.publication"
\dRs "no.such.subscription"
\dT "no.such.data.type"
\dx "no.such.installed.extension"
\dX "no.such.extended.statistics"
\dy "no.such.event.trigger"

-- again, but with dotted schema qualifications.
\dA "no.such.schema"."no.such.access.method"
\dt "no.such.schema"."no.such.table.relation"
\da "no.such.schema"."no.such.aggregate.function"
\dAc "no.such.schema"."no.such.operator.class"
\dAf "no.such.schema"."no.such.operator.family"
\dAo "no.such.schema"."no.such.operator.of.operator.family"
\dAp "no.such.schema"."no.such.operator.support.function.of.operator.family"
\db "no.such.schema"."no.such.tablespace"
\dc "no.such.schema"."no.such.conversion"
\dC "no.such.schema"."no.such.cast"
\dd "no.such.schema"."no.such.object.description"
\dD "no.such.schema"."no.such.domain"
\ddp "no.such.schema"."no.such.default.access.privilege"
\di "no.such.schema"."no.such.index.relation"
\dm "no.such.schema"."no.such.materialized.view"
\ds "no.such.schema"."no.such.relation"
\dt "no.such.schema"."no.such.relation"
\dv "no.such.schema"."no.such.relation"
\des "no.such.schema"."no.such.foreign.server"
\dew "no.such.schema"."no.such.foreign.data.wrapper"
\df "no.such.schema"."no.such.function"
\dF "no.such.schema"."no.such.text.search.configuration"
\dFd "no.such.schema"."no.such.text.search.dictionary"
\dFp "no.such.schema"."no.such.text.search.parser"
\dFt "no.such.schema"."no.such.text.search.template"
\dg "no.such.schema"."no.such.role"
\dL "no.such.schema"."no.such.language"
\do "no.such.schema"."no.such.operator"
\dO "no.such.schema"."no.such.collation"
\dp "no.such.schema"."no.such.access.privilege"
\dP "no.such.schema"."no.such.partitioned.relation"
\drds "no.such.schema"."no.such.setting"
\dRp "no.such.schema"."no.such.publication"
\dRs "no.such.schema"."no.such.subscription"
\dT "no.such.schema"."no.such.data.type"
\dx "no.such.schema"."no.such.installed.extension"
\dX "no.such.schema"."no.such.extended.statistics"
\dy "no.such.schema"."no.such.event.trigger"

-- again, but with current database and dotted schema qualifications.
\dt regression."no.such.schema"."no.such.table.relation"
\da regression."no.such.schema"."no.such.aggregate.function"
\dc regression."no.such.schema"."no.such.conversion"
\dC regression."no.such.schema"."no.such.cast"
\dd regression."no.such.schema"."no.such.object.description"
\dD regression."no.such.schema"."no.such.domain"
\di regression."no.such.schema"."no.such.index.relation"
\dm regression."no.such.schema"."no.such.materialized.view"
\ds regression."no.such.schema"."no.such.relation"
\dt regression."no.such.schema"."no.such.relation"
\dv regression."no.such.schema"."no.such.relation"
\df regression."no.such.schema"."no.such.function"
\dF regression."no.such.schema"."no.such.text.search.configuration"
\dFd regression."no.such.schema"."no.such.text.search.dictionary"
\dFp regression."no.such.schema"."no.such.text.search.parser"
\dFt regression."no.such.schema"."no.such.text.search.template"
\do regression."no.such.schema"."no.such.operator"
\dO regression."no.such.schema"."no.such.collation"
\dp regression."no.such.schema"."no.such.access.privilege"
\dP regression."no.such.schema"."no.such.partitioned.relation"
\dT regression."no.such.schema"."no.such.data.type"
\dX regression."no.such.schema"."no.such.extended.statistics"

-- again, but with dotted database and dotted schema qualifications.
\dt "no.such.database"."no.such.schema"."no.such.table.relation"
\da "no.such.database"."no.such.schema"."no.such.aggregate.function"
\dc "no.such.database"."no.such.schema"."no.such.conversion"
\dC "no.such.database"."no.such.schema"."no.such.cast"
\dd "no.such.database"."no.such.schema"."no.such.object.description"
\dD "no.such.database"."no.such.schema"."no.such.domain"
\ddp "no.such.database"."no.such.schema"."no.such.default.access.privilege"
\di "no.such.database"."no.such.schema"."no.such.index.relation"
\dm "no.such.database"."no.such.schema"."no.such.materialized.view"
\ds "no.such.database"."no.such.schema"."no.such.relation"
\dt "no.such.database"."no.such.schema"."no.such.relation"
\dv "no.such.database"."no.such.schema"."no.such.relation"
\df "no.such.database"."no.such.schema"."no.such.function"
\dF "no.such.database"."no.such.schema"."no.such.text.search.configuration"
\dFd "no.such.database"."no.such.schema"."no.such.text.search.dictionary"
\dFp "no.such.database"."no.such.schema"."no.such.text.search.parser"
\dFt "no.such.database"."no.such.schema"."no.such.text.search.template"
\do "no.such.database"."no.such.schema"."no.such.operator"
\dO "no.such.database"."no.such.schema"."no.such.collation"
\dp "no.such.database"."no.such.schema"."no.such.access.privilege"
\dP "no.such.database"."no.such.schema"."no.such.partitioned.relation"
\dT "no.such.database"."no.such.schema"."no.such.data.type"
\dX "no.such.database"."no.such.schema"."no.such.extended.statistics"

-- check \drg and \du
CREATE ROLE regress_du_role0;
CREATE ROLE regress_du_role1;
CREATE ROLE regress_du_role2;
CREATE ROLE regress_du_admin;

GRANT regress_du_role0 TO regress_du_admin WITH ADMIN TRUE;
GRANT regress_du_role1 TO regress_du_admin WITH ADMIN TRUE;
GRANT regress_du_role2 TO regress_du_admin WITH ADMIN TRUE;

GRANT regress_du_role0 TO regress_du_role1 WITH ADMIN TRUE,  INHERIT TRUE,  SET TRUE  GRANTED BY regress_du_admin;
GRANT regress_du_role0 TO regress_du_role2 WITH ADMIN TRUE,  INHERIT FALSE, SET FALSE GRANTED BY regress_du_admin;
GRANT regress_du_role1 TO regress_du_role2 WITH ADMIN TRUE , INHERIT FALSE, SET TRUE  GRANTED BY regress_du_admin;
GRANT regress_du_role0 TO regress_du_role1 WITH ADMIN FALSE, INHERIT TRUE,  SET FALSE GRANTED BY regress_du_role1;
GRANT regress_du_role0 TO regress_du_role2 WITH ADMIN FALSE, INHERIT TRUE , SET TRUE  GRANTED BY regress_du_role1;
GRANT regress_du_role0 TO regress_du_role1 WITH ADMIN FALSE, INHERIT FALSE, SET TRUE  GRANTED BY regress_du_role2;
GRANT regress_du_role0 TO regress_du_role2 WITH ADMIN FALSE, INHERIT FALSE, SET FALSE GRANTED BY regress_du_role2;

\drg regress_du_role*
\du regress_du_role*

DROP ROLE regress_du_role0;
DROP ROLE regress_du_role1;
DROP ROLE regress_du_role2;
DROP ROLE regress_du_admin;

-- Test display of empty privileges.
BEGIN;
-- Create an owner for tested objects because output contains owner name.
CREATE ROLE regress_zeropriv_owner;
SET LOCAL ROLE regress_zeropriv_owner;

CREATE DOMAIN regress_zeropriv_domain AS int;
REVOKE ALL ON DOMAIN regress_zeropriv_domain FROM CURRENT_USER, PUBLIC;
\dD+ regress_zeropriv_domain

CREATE PROCEDURE regress_zeropriv_proc() LANGUAGE sql AS '';
REVOKE ALL ON PROCEDURE regress_zeropriv_proc() FROM CURRENT_USER, PUBLIC;
\df+ regress_zeropriv_proc

CREATE TABLE regress_zeropriv_tbl (a int);
REVOKE ALL ON TABLE regress_zeropriv_tbl FROM CURRENT_USER;
\dp regress_zeropriv_tbl

CREATE TYPE regress_zeropriv_type AS (a int);
REVOKE ALL ON TYPE regress_zeropriv_type FROM CURRENT_USER, PUBLIC;
\dT+ regress_zeropriv_type

ROLLBACK;

-- Test display of default privileges with \pset null.
CREATE TABLE defprivs (a int);
\pset null '(default)'
\z defprivs
\zx defprivs
\pset null ''
DROP TABLE defprivs;

Explanation: PL/pgSQL object from PostgreSQL core test for Psql.


Question: PostgreSQL regression test 'timestamptz': Write the SELECT query (example 175).

SELECT to_char(d1, 'YYYY A.D. YYYY a.d. YYYY bc HH:MI:SS P.M. HH:MI:SS p.m. HH:MI:SS pm')
   FROM TIMESTAMPTZ_TBL;

Explanation: Regression test for Timestamptz in PostgreSQL core test suite.

SELECT count(*) FROM (SELECT to_char(d1, 'YYYY A.D. YYYY a.d. YYYY bc HH:MI:SS P.M. HH:MI:SS p.m. HH:MI:SS pm')
   FROM TIMESTAMPTZ_TBL) AS _sub;


Question: Write the PL/pgSQL object from PostgreSQL regression test 'triggers' (example 126).

$$;

delete from parent where aid = 1;
select * from parent; select * from child;

drop table parent, child;

drop function parent_upd_func();
drop function parent_del_func();
drop function child_ins_func();
drop function child_del_func();

-- similar case, but with a self-referencing FK so that parent and child
-- rows can be affected by a single operation

create temp table self_ref_trigger (
    id int primary key,
    parent int references self_ref_trigger,
    data text,
    nchildren int not null default 0
);

create function self_ref_trigger_ins_func()
  returns trigger language plpgsql as
$$
begin
  if new.parent is not null then
    update self_ref_trigger set nchildren = nchildren + 1
      where id = new.parent;

Explanation: PL/pgSQL object from PostgreSQL core test for Triggers.


Question: Write the SQL definition from PostgreSQL contrib extension 'contrib' (item 59).

-- these are obsolete/deprecated:
CREATE OPERATOR @ (
	LEFTARG = cube, RIGHTARG = cube, PROCEDURE = cube_contains,
	COMMUTATOR = '~',
	RESTRICT = contsel, JOIN = contjoinsel
);

Explanation: SQL definition from the 'contrib' PostgreSQL contrib extension.


Question: Write the DDL statement from PostgreSQL regression test 'brin' (example 84).

CREATE INDEX brin_test_toast_idx ON brintest_3 USING brin (b, c);

Explanation: DDL from PostgreSQL core regression test for Brin.


Question: pgTAP test for Functap (assertion 80).

SELECT * FROM check_test(
    function_lang_is( 'someproc', 'sql', 'whatever' ),
    true,
    'function_lang_is(schema, proc, desc)',
    'whatever',
    ''
);

Explanation: SQL assertion from pgTAP test suite for Functap.


Question: Write the DML statement from PostgreSQL regression test 'partition_join' (example 6).

INSERT INTO prt1 SELECT i, i % 25, to_char(i, 'FM0000') FROM generate_series(0, 599) i WHERE i % 2 = 0;

Explanation: DML from PostgreSQL core regression test for Partition Join.


Question: pgTAP test for Pgtap--Unpackaged--0.91.0 (assertion 23).

ALTER EXTENSION pgtap ADD FUNCTION diag( VARIADIC text[] );

Explanation: SQL assertion from pgTAP test suite for Pgtap--Unpackaged--0.91.0.


Question: Write the DDL statement from PostgreSQL regression test 'domain' (example 3).

create domain dependenttypetest domaindroptest;

Explanation: DDL from PostgreSQL core regression test for Domain.


Question: Write the DDL statement from PostgreSQL regression test 'stats_ext' (example 11).

Explanation: DDL from PostgreSQL core regression test for Stats Ext.


Question: Write the DDL statement from PostgreSQL regression test 'partition_info' (example 12).

CREATE TABLE ptif_test2 PARTITION OF ptif_test
  FOR VALUES FROM (100) TO (200);

Explanation: DDL from PostgreSQL core regression test for Partition Info.


Question: Write the DDL statement from PostgreSQL regression test 'rangefuncs' (example 18).

create temporary view vw_ord as select * from (values (1)) v(n) join rows from(rngfunct(1),rngfunct(2)) with ordinality as z(a,b,c,d,ord) on (n=ord);

Explanation: DDL from PostgreSQL core regression test for Rangefuncs.


Question: Show a query using PostgreSQL contrib extension 'cube' (example 204).

Explanation: Example query from the 'cube' extension test/demo.


Question: pgTAP test for Aretap (assertion 129).

SELECT * FROM check_test(
    rules_are( 'fou', ARRAY['ins_me', 'upd_me', 'del_me'] ),
    false,
    'rules_are(table, rules) + missing',
    'Relation fou should have the correct rules',
    '    Missing rules:
        del_me'
);

Explanation: SQL assertion from pgTAP test suite for Aretap.


Question: Write the DML statement from PostgreSQL regression test 'matview' (example 82).

Explanation: DML from PostgreSQL core regression test for Matview.


Question: Write the DML statement from PostgreSQL regression test 'inet' (example 16).

INSERT INTO INET_TBL (c, i) VALUES ('10', '9.1.2.3/8');

Explanation: DML from PostgreSQL core regression test for Inet.


Question: Write the DML statement from PostgreSQL regression test 'rules' (example 157).

Explanation: DML from PostgreSQL core regression test for Rules.


Question: Write the DML statement from PostgreSQL regression test 'domain' (example 208).

update domnotnull set col1 = null;		-- fails
select conname, pg_get_constraintdef(oid) from pg_constraint
 where contypid = 'dnotnulltest'::regtype;

Explanation: DML from PostgreSQL core regression test for Domain.


Question: PostgreSQL regression test 'int2': Write the SELECT query (example 25).

SELECT i.* FROM INT2_TBL i WHERE i.f1 <= int2 '0';

Explanation: Regression test for Int2 in PostgreSQL core test suite.

SELECT count(*) FROM (SELECT i.* FROM INT2_TBL i WHERE i.f1 <= int2 '0') AS _sub;


Question: PL/pgSQL test: Plpython Trigger (example 5).

CREATE TRIGGER users_update_trig BEFORE UPDATE ON users FOR EACH ROW
	EXECUTE PROCEDURE users_update ('willem');

Explanation: PL/pgSQL example from PostgreSQL source test for Plpython Trigger.


Question: PostgreSQL regression test 'foreign_data': Write the SELECT query (example 268).

SELECT has_server_privilege(
    (SELECT oid FROM pg_roles WHERE rolname='regress_test_role'), 's8', 'USAGE');

Explanation: Regression test for Foreign Data in PostgreSQL core test suite.

SELECT count(*) FROM (SELECT has_server_privilege(
    (SELECT oid FROM pg_roles WHERE rolname='regress_test_role'), 's8', 'USAGE')) AS _sub;


Question: PostgreSQL regression test 'inet': Write the SELECT query (example 63).

SELECT * FROM inet_tbl WHERE i >= '192.168.1.0/24'::cidr ORDER BY i;

Explanation: Regression test for Inet in PostgreSQL core test suite.

SELECT count(*) FROM (SELECT * FROM inet_tbl WHERE i >= '192.168.1.0/24'::cidr ORDER BY i) AS _sub;


Question: Show a SQL definition from the citus project (row_types, item 9).

CREATE OR REPLACE FUNCTION identity_returner(x anyelement)
RETURNS anyelement
AS $$
BEGIN
	RETURN x;
END;
$$ language plpgsql;

Explanation: SQL definition from the open-source citus PostgreSQL project.


Question: PostgreSQL regression test 'roleattributes': Write the SELECT query (example 44).

SELECT rolname, rolsuper, rolinherit, rolcreaterole, rolcreatedb, rolcanlogin, rolreplication, rolbypassrls, rolconnlimit, rolpassword, rolvaliduntil FROM pg_authid WHERE rolname = 'regress_test_user_canlogin';

Explanation: Regression test for Roleattributes in PostgreSQL core test suite.

SELECT count(*) FROM (SELECT rolname, rolsuper, rolinherit, rolcreaterole, rolcreatedb, rolcanlogin, rolreplication, rolbypassrls, rolconnlimit, rolpassword, rolvaliduntil FROM pg_authid WHERE rolname = 'regress_test_user_canlogin') AS _sub;


Question: Show a query using PostgreSQL contrib extension 'citext' (example 299).

INSERT INTO caster (uuid)          VALUES ('a0eebc99-9c0b-4ef8-bb6d-6bb9bd380a11'::citext);

Explanation: Example query from the 'citext' extension test/demo.


Question: pgTAP test for Resultset (assertion 182).

INSERT INTO names (name) VALUES ('Jesse');

Explanation: SQL assertion from pgTAP test suite for Resultset.


Question: Show a query using PostgreSQL contrib extension 'btree_gin' (example 5).

SELECT * FROM test_date WHERE i<'2004-10-26'::date ORDER BY i;

Explanation: Example query from the 'btree_gin' extension test/demo.


Question: PostgreSQL Indices: show example 1.

CREATE TABLE test1 ( id integer, content varchar );

Explanation: Example from PostgreSQL documentation on Indices.


Question: Show a SQL definition from the pg_partman project (pg_partman--4.6.1--4.6.2, item 12).

CREATE OR REPLACE FUNCTION @extschema@.apply_foreign_keys(p_parent_table text, p_child_table text, p_job_id bigint DEFAULT NULL, p_debug boolean DEFAULT false) RETURNS void
    LANGUAGE plpgsql
    AS $$
DECLARE

ex_context          text;
ex_detail           text;
ex_hint             text;
ex_message          text;
v_count             int := 0;
v_job_id            bigint;
v_jobmon            text;
v_jobmon_schema     text;
v_new_search_path   text;
v_old_search_path   text;
v_parent_schema     text;
v_parent_tablename  text;
v_ref_schema        text;
v_ref_table         text;
v_relkind           char;
v_row               record;
v_schemaname        text;
v_sql               text;
v_step_id           bigint;
v_tablename         text;

BEGIN
/*
 * Apply foreign keys that exist on the given parent to the given child table
 */

SELECT jobmon INTO v_jobmon FROM @extschema@.part_config WHERE parent_table = p_parent_table;

IF v_jobmon THEN
    SELECT nspname INTO v_jobmon_schema FROM pg_catalog.pg_namespace n, pg_catalog.pg_extension e WHERE e.extname = 'pg_jobmon' AND e.extnamespace = n.oid;
    IF v_jobmon_schema IS NOT NULL THEN
        SELECT current_setting('search_path') INTO v_old_search_path;
        IF length(v_old_search_path) > 0 THEN
           v_new_search_path := '@extschema@,pg_temp,'||v_old_search_path;
        ELSE
            v_new_search_path := '@extschema@,pg_temp';
        END IF;
        v_new_search_path := format('%s,%s',v_jobmon_schema, v_new_search_path);
        EXECUTE format('SELECT set_config(%L, %L, %L)', 'search_path', v_new_search_path, 'false');
    END IF;
END IF;

SELECT n.nspname, c.relname, c.relkind INTO v_parent_schema, v_parent_tablename, v_relkind
FROM pg_catalog.pg_class c
JOIN pg_catalog.pg_namespace n ON c.relnamespace = n.oid
WHERE n.nspname = split_part(p_parent_table, '.', 1)::name
AND c.relname = split_part(p_parent_table, '.', 2)::name;

IF v_relkind = 'p' THEN
    RAISE EXCEPTION 'This function cannot run on natively partitioned tables';
ELSIF v_relkind IS NULL THEN
    RAISE EXCEPTION 'Unable to find given table in system catalogs: %.%', v_parent_schema, v_parent_tablename;
END IF;

SELECT n.nspname, c.relname INTO v_schemaname, v_tablename
FROM pg_catalog.pg_class c
JOIN pg_catalog.pg_namespace n ON c.relnamespace = n.oid
WHERE n.nspname = split_part(p_child_table, '.', 1)::name
AND c.relname = split_part(p_child_table, '.', 2)::name;

IF v_jobmon_schema IS NOT NULL THEN
    IF p_job_id IS NULL THEN
        v_job_id := add_job(format('PARTMAN APPLYING FOREIGN KEYS: %s', p_parent_table));
    ELSE -- Don't create a new job, add steps into given job
        v_job_id := p_job_id;
    END IF;
END IF;

IF v_jobmon_schema IS NOT NULL THEN
    v_step_id := add_step(v_job_id, format('Applying foreign keys to %s if they exist on parent', p_child_table));
END IF;

IF v_tablename IS NULL THEN
    IF v_jobmon_schema IS NOT NULL THEN
        PERFORM update_step(v_step_id, 'CRITICAL', format('Target child table (%s) does not exist.', p_child_table));
        PERFORM fail_job(v_job_id);
        EXECUTE format('SELECT set_config(%L, %L, %L)', 'search_path', v_old_search_path, 'false');
    END IF;
    RAISE EXCEPTION 'Target child table (%) does not exist.', p_child_table;
    RETURN;
END IF;

FOR v_row IN
    SELECT pg_get_constraintdef(con.oid) AS constraint_def
    FROM pg_catalog.pg_constraint con
    JOIN pg_catalog.pg_class c ON con.conrelid = c.oid
    JOIN pg_catalog.pg_namespace n ON c.relnamespace = n.oid
    WHERE c.relname = v_parent_tablename
    AND n.nspname = v_parent_schema
    AND contype = 'f'
LOOP
    v_sql := format('ALTER TABLE %I.%I ADD %s'
                    , v_schemaname
                    , v_tablename
                    , v_row.constraint_def);

    IF p_debug THEN
        RAISE NOTICE 'Constraint creation query: %', v_sql;
    END IF;

    EXECUTE v_sql;

    IF v_jobmon_schema IS NOT NULL THEN
        PERFORM update_step(v_step_id, 'OK', 'FK applied');
    END IF;
    v_count := v_count + 1;

END LOOP;

IF v_count = 0 AND v_jobmon_schema IS NOT NULL THEN
    PERFORM update_step(v_step_id, 'OK', 'No FKs found on parent');
END IF;

IF v_jobmon_schema IS NOT NULL THEN
    PERFORM close_job(v_job_id);
    EXECUTE format('SELECT set_config(%L, %L, %L)', 'search_path', v_old_search_path, 'false');
END IF;

EXCEPTION
    WHEN OTHERS THEN
        GET STACKED DIAGNOSTICS ex_message = MESSAGE_TEXT,
                                ex_context = PG_EXCEPTION_CONTEXT,
                                ex_detail = PG_EXCEPTION_DETAIL,
                                ex_hint = PG_EXCEPTION_HINT;
        IF v_jobmon_schema IS NOT NULL THEN
            IF v_job_id IS NULL THEN
                EXECUTE format('SELECT %I.add_job(''PARTMAN CREATE APPLYING FOREIGN KEYS: %s'')', v_jobmon_schema, p_parent_table) INTO v_job_id;
                EXECUTE format('SELECT %I.add_step(%s, ''EXCEPTION before job logging started'')', v_jobmon_schema, v_job_id, p_parent_table) INTO v_step_id;
            ELSIF v_step_id IS NULL THEN
                EXECUTE format('SELECT %I.add_step(%s, ''EXCEPTION before first step logged'')', v_jobmon_schema, v_job_id) INTO v_step_id;
            END IF;
            EXECUTE format('SELECT %I.update_step(%s, ''CRITICAL'', %L)', v_jobmon_schema, v_step_id, 'ERROR: '||coalesce(SQLERRM,'unknown'));
            EXECUTE format('SELECT %I.fail_job(%s)', v_jobmon_schema, v_job_id);
        END IF;
        RAISE EXCEPTION '%
CONTEXT: %
DETAIL: %
HINT: %', ex_message, ex_context, ex_detail, ex_hint;
END
$$;

Explanation: SQL definition from the open-source pg_partman PostgreSQL project.


Question: PostgreSQL Ddl: show example 41.

CREATE TABLE products ( product_no integer, price numeric, valid_at daterange );

Explanation: Example from PostgreSQL documentation on Ddl.


Question: Write the DDL statement from PostgreSQL regression test 'with' (example 254).

CREATE FUNCTION y_trigger() RETURNS trigger AS $$
begin
  raise notice 'y_trigger: a = %', new.a;
  return new;
end;
$$ LANGUAGE plpgsql;

Explanation: DDL from PostgreSQL core regression test for With.


Question: PostgreSQL regression test 'rowsecurity': Write the SELECT query (example 839).

SELECT (string_to_array(polqual, ':'))[7] AS inputcollid FROM pg_policy WHERE polrelid = 'coll_t'::regclass;

Explanation: Regression test for Rowsecurity in PostgreSQL core test suite.

SELECT count(*) FROM (SELECT (string_to_array(polqual, ':'))[7] AS inputcollid FROM pg_policy WHERE polrelid = 'coll_t'::regclass) AS _sub;


Question: Write the DML statement from PostgreSQL regression test 'constraints' (example 31).

Explanation: DML from PostgreSQL core regression test for Constraints.


Question: PostgreSQL regression test 'updatable_views': Write the SELECT query (example 100).

SELECT table_name, is_insertable_into
  FROM information_schema.tables
 WHERE table_name LIKE 'rw_view%'
 ORDER BY table_name;

Explanation: Regression test for Updatable Views in PostgreSQL core test suite.

SELECT count(*) FROM (SELECT table_name, is_insertable_into
  FROM information_schema.tables
 WHERE table_name LIKE 'rw_view%'
 ORDER BY table_name) AS _sub;


Question: PostgreSQL regression test 'interval': Write the SELECT query (example 374).

Explanation: Regression test for Interval in PostgreSQL core test suite.

SELECT count(*) FROM (SELECT interval 'infinity' * 'nan') AS _sub;


Question: Write the PL/pgSQL object from PostgreSQL regression test 'encoding' (example 60).

Explanation: PL/pgSQL object from PostgreSQL core test for Encoding.


Question: PostgreSQL regression test 'timestamptz': Write the SELECT query (example 134).

SELECT d1 FROM TIMESTAMPTZ_TBL
   WHERE d1 >= timestamp with time zone '1997-01-02';

Explanation: Regression test for Timestamptz in PostgreSQL core test suite.

SELECT count(*) FROM (SELECT d1 FROM TIMESTAMPTZ_TBL
   WHERE d1 >= timestamp with time zone '1997-01-02') AS _sub;


Question: Write the DDL statement from PostgreSQL regression test 'alter_table' (example 472).

CREATE TABLE fail_part (LIKE list_parted);

Explanation: DDL from PostgreSQL core regression test for Alter Table.


Question: Write the SQL definition from PostgreSQL contrib extension 'contrib' (item 3).

-- dblink_connect_u allows non-superusers to use
-- non-password authenticated connections, but initially
-- privileges are revoked from public
CREATE FUNCTION dblink_connect_u (text)
RETURNS text
AS 'MODULE_PATHNAME','dblink_connect'
LANGUAGE C STRICT PARALLEL RESTRICTED SECURITY DEFINER;

Explanation: SQL definition from the 'contrib' PostgreSQL contrib extension.


Question: PostgreSQL regression test 'interval': Write the SELECT query (example 409).

SELECT count(*) FROM (SELECT INTERVAL '2 minutes ago 5 days') AS _sub;


Question: PostgreSQL regression test 'xid': Write the SELECT query (example 44).

select * from pg_input_error_info('12:16:14,13', 'pg_snapshot');

Explanation: Regression test for Xid in PostgreSQL core test suite.

SELECT count(*) FROM (select * from pg_input_error_info('12:16:14,13', 'pg_snapshot')) AS _sub;


Question: PostgreSQL regression test 'groupingsets': Write the SELECT query (example 73).

select a, b, sum(c), sum(sum(c)) over (order by a,b) as rsum
  from gstest2 group by cube (a,b) order by rsum, a, b;

Explanation: Regression test for Groupingsets in PostgreSQL core test suite.

SELECT count(*) FROM (select a, b, sum(c), sum(sum(c)) over (order by a,b) as rsum
  from gstest2 group by cube (a,b) order by rsum, a, b) AS _sub;


Question: PostgreSQL regression test 'sqljson_queryfuncs': Write the SELECT query (example 258).

SELECT JSON_QUERY('"a"', '$.a' RETURNING queryfuncs_test_domain DEFAULT (select '"1"')::queryfuncs_test_domain ON ERROR);

Explanation: Regression test for Sqljson Queryfuncs in PostgreSQL core test suite.

SELECT count(*) FROM (SELECT JSON_QUERY('"a"', '$.a' RETURNING queryfuncs_test_domain DEFAULT (select '"1"')::queryfuncs_test_domain ON ERROR)) AS _sub;


Question: PostgreSQL regression test 'numeric': Write the SELECT query (example 963).

Explanation: Regression test for Numeric in PostgreSQL core test suite.

SELECT count(*) FROM (select scale(numeric 'inf')) AS _sub;


Question: Write the PL/pgSQL object from PostgreSQL regression test 'plpgsql' (example 528).

$$ language plpgsql parallel safe;

set debug_parallel_query to on;

explain (verbose, costs off) select error_trap_test();
select error_trap_test();

reset debug_parallel_query;

drop function error_trap_test();
drop function zero_divide();

-- check cases where implicit SQLSTATE variable could be confused with
-- SQLSTATE as a keyword, cf bug #5524
create or replace function raise_test() returns void as $$
begin
  perform 1/0;

Explanation: PL/pgSQL object from PostgreSQL core test for Plpgsql.


Question: Write the SQL definition from PostgreSQL contrib extension 'contrib' (item 5).

CREATE FUNCTION gbt_macad8_picksplit(internal, internal)
RETURNS internal
AS 'MODULE_PATHNAME'
LANGUAGE C IMMUTABLE STRICT;


Question: PostgreSQL Query: show example 2.

CREATE TABLE cities ( name varchar(80), location point );

Explanation: Example from PostgreSQL documentation on Query.


Question: Write the PL/pgSQL object from PostgreSQL regression test 'triggers' (example 107).

$$;
create trigger depth_b_tr before insert on depth_b
  for each row execute procedure depth_b_tf();

create function depth_c_tf() returns trigger
  language plpgsql as $$
begin
  raise notice '%: depth = %', tg_name, pg_trigger_depth();

Explanation: PL/pgSQL object from PostgreSQL core test for Triggers.


Question: Write the DDL statement from PostgreSQL regression test 'join' (example 540).

create temp table t (a int unique, b int);

Explanation: DDL from PostgreSQL core regression test for Join.


Question: PostgreSQL regression test 'case': Write the SELECT query (example 44).

SELECT CASE
  (CASE vol('bar')
    WHEN 'foo' THEN 'it was foo!'
    WHEN vol(null) THEN 'null input'
    WHEN 'bar' THEN 'it was bar!' END
  )
  WHEN 'it was foo!' THEN 'foo recognized'
  WHEN 'it was bar!' THEN 'bar recognized'
  ELSE 'unrecognized' END;

Explanation: Regression test for Case in PostgreSQL core test suite.

SELECT count(*) FROM (SELECT CASE
  (CASE vol('bar')
    WHEN 'foo' THEN 'it was foo!'
    WHEN vol(null) THEN 'null input'
    WHEN 'bar' THEN 'it was bar!' END
  )
  WHEN 'it was foo!' THEN 'foo recognized'
  WHEN 'it was bar!' THEN 'bar recognized'
  ELSE 'unrecognized' END) AS _sub;


Question: PL/pgSQL test: Plperl Util (example 5).

-- test quote_ident

create or replace function perl_quote_ident() returns setof text language plperl as $$
	return_next "undef: ".quote_ident(undef); # generates undef warning if warnings enabled
	return_next "$_: ".quote_ident($_)
		for q{foo}, q{a'b}, q{a"b}, q{c''d}, q{e\f}, q{g.h}, q{};
	return undef;
$$;

Explanation: PL/pgSQL example from PostgreSQL source test for Plperl Util.


Question: Write the SQL definition from PostgreSQL contrib extension 'contrib' (item 64).

CREATE FUNCTION g_cube_penalty(internal,internal,internal)
RETURNS internal
AS 'MODULE_PATHNAME'
LANGUAGE C IMMUTABLE STRICT PARALLEL SAFE;


Question: Show a query using PostgreSQL contrib extension 'jsonb_plperl' (example 14).

Explanation: Example query from the 'jsonb_plperl' extension test/demo.


Question: Show a query using PostgreSQL contrib extension 'pgcrypto' (example 13).

select encode(decrypt(encrypt('foo', '0123456', 'aes') || '\x00'::bytea, '0123456', 'aes'), 'escape');

Explanation: Example query from the 'pgcrypto' extension test/demo.


Question: pgTAP test for Pgtap--Unpackaged--0.91.0 (assertion 399).

ALTER EXTENSION pgtap ADD FUNCTION has_leftop ( NAME, NAME, NAME );

Explanation: SQL assertion from pgTAP test suite for Pgtap--Unpackaged--0.91.0.


Question: PostgreSQL regression test 'strings': Write the SELECT query (example 261).

Explanation: Regression test for Strings in PostgreSQL core test suite.

SELECT count(*) FROM (SELECT 'indio' LIKE 'in_o' AS "false") AS _sub;


Question: pgTAP test for Do Tap (assertion 10).

SELECT is(
    findfuncs('foo'),
    CASE WHEN pg_version_num() < 80300 THEN NULL ELSE '{}'::text[] END,
    'findfuncs(unknown) should find no tests'
);

Explanation: SQL assertion from pgTAP test suite for Do Tap.


Question: PostgreSQL regression test 'regex': Write the SELECT query (example 7).

select 'abc abd abc' ~ '^(\w+)( \1)+$' as f;

Explanation: Regression test for Regex in PostgreSQL core test suite.

SELECT count(*) FROM (select 'abc abd abc' ~ '^(\w+)( \1)+$' as f) AS _sub;


Question: Write the DML statement from PostgreSQL regression test 'constraints' (example 468).

INSERT INTO notnull_tbl1_upg VALUES (NULL, 1), (NULL, 2), (300, 3);

Explanation: DML from PostgreSQL core regression test for Constraints.


Question: Write the DDL statement from PostgreSQL regression test 'join' (example 786).

create table fkest (x integer, x10 integer, x10b integer, x100 integer);


Question: PostgreSQL regression test 'jsonb': Write the SELECT query (example 137).

SELECT jsonb_exists_all('{"a":null, "b":"qq"}', ARRAY['a','b']);

Explanation: Regression test for Jsonb in PostgreSQL core test suite.

SELECT count(*) FROM (SELECT jsonb_exists_all('{"a":null, "b":"qq"}', ARRAY['a','b'])) AS _sub;


Question: Write the SQL definition from PostgreSQL contrib extension 'contrib' (item 112).

CREATE FUNCTION gbt_tstz_compress(internal)
RETURNS internal
AS 'MODULE_PATHNAME'
LANGUAGE C IMMUTABLE STRICT PARALLEL SAFE;

Explanation: SQL definition from the 'contrib' PostgreSQL contrib extension.


Question: pgTAP test for Resultset (assertion 293).

CREATE table dubs (pk SERIAL PRIMARY KEY, id int, name text);

Explanation: SQL assertion from pgTAP test suite for Resultset.


Question: Write the DDL statement from PostgreSQL regression test 'create_index' (example 172).

CREATE INDEX unlogged_hash_index ON unlogged_hash_table USING hash (id int4_ops);

Explanation: DDL from PostgreSQL core regression test for Create Index.


Question: PostgreSQL regression test 'jsonb': Write the SELECT query (example 423).

SELECT count(*) FROM (select * from jsonb_to_record('{"ia2": [[[1], [2], [3]]]}') as x(ia2 int4[][])) AS _sub;


Question: Write the DML statement from PostgreSQL regression test 'timestamp' (example 91).

INSERT INTO TIMESTAMP_TBL VALUES ('Feb 29 17:32:01 1997');

Explanation: DML from PostgreSQL core regression test for Timestamp.


Question: Show a query using PostgreSQL contrib extension 'pg_surgery' (example 31).

select heap_force_freeze('mvw'::regclass, ARRAY['(0, 3)']::tid[]);

Explanation: Example query from the 'pg_surgery' extension test/demo.


Question: Show a query using PostgreSQL contrib extension 'xml2' (example 15).

SELECT * FROM
xpath_table('article_id',
            'article_xml',
            'articles',
            '/article/author|/article/pages|/article/title',
            'date_entered > ''2003-01-01'' ')
AS t(article_id integer, author text, page_count integer, title text);

Explanation: Example query from the 'xml2' extension test/demo.


Question: Show a SQL definition from the pglogical project (pglogical--2.2.1, item 50).

CREATE FUNCTION pglogical.wait_for_table_sync_complete(subscription_name name, relation regclass)
RETURNS void RETURNS NULL ON NULL INPUT VOLATILE LANGUAGE c AS 'MODULE_PATHNAME', 'pglogical_wait_for_table_sync_complete';

Explanation: SQL definition from the open-source pglogical PostgreSQL project.


Question: PostgreSQL regression test 'name': Write the SELECT query (example 18).

SELECT c.f1 FROM NAME_TBL c WHERE c.f1 ~ '.*';

Explanation: Regression test for Name in PostgreSQL core test suite.

SELECT count(*) FROM (SELECT c.f1 FROM NAME_TBL c WHERE c.f1 ~ '.*') AS _sub;


Question: PostgreSQL regression test 'arrays': Write the SELECT query (example 265).

Explanation: Regression test for Arrays in PostgreSQL core test suite.

SELECT count(*) FROM (select '[1:]={1}'::int[]) AS _sub;


Question: Write the DML statement from PostgreSQL regression test 'domain' (example 112).

insert into dcomptable values (array[row(1,2)]::dcomptypea);  -- fail on uniqueness
insert into dcomptable (d1[1]) values(row(9,10));

Explanation: DML from PostgreSQL core regression test for Domain.


Question: Show a SQL definition from the pglogical project (pglogical--2.2.1, item 39).

CREATE TABLE pglogical.queue (
    queued_at timestamp with time zone NOT NULL,
    role name NOT NULL,
    replication_sets text[],
    message_type "char" NOT NULL,
    message json NOT NULL
);


Question: PostgreSQL regression test 'jsonb': Write the SELECT query (example 150).

SELECT count(*) FROM (SELECT jsonb_typeof('[]') AS array) AS _sub;


Question: PostgreSQL regression test 'sqljson_queryfuncs': Write the SELECT query (example 145).

SELECT JSON_QUERY(jsonb '[1,2]', '$' RETURNING json);

Explanation: Regression test for Sqljson Queryfuncs in PostgreSQL core test suite.

SELECT count(*) FROM (SELECT JSON_QUERY(jsonb '[1,2]', '$' RETURNING json)) AS _sub;


Question: Write the DDL statement from PostgreSQL regression test 'returning' (example 35).

CREATE OR REPLACE RULE voo_i AS ON INSERT TO voo DO INSTEAD
  INSERT INTO foo VALUES(new.*, 57) RETURNING f1, f2;

Explanation: DDL from PostgreSQL core regression test for Returning.


Question: PostgreSQL regression test 'tsearch': Write the SELECT query (example 286).

Explanation: Regression test for Tsearch in PostgreSQL core test suite.

SELECT count(*) FROM (SELECT ts_headline('english', '

Sea view wow foo bar qq
YES
ff-bg


Question: PostgreSQL regression test 'jsonb_jsonpath': Write the SELECT query (example 591).

Explanation: Regression test for Jsonb Jsonpath in PostgreSQL core test suite.

SELECT count(*) FROM (select jsonb_path_query('"2023-08-15 12:34:56"', '$.timestamp()')) AS _sub;


Question: PostgreSQL regression test 'numeric': Write the SELECT query (example 820).

SELECT * FROM pg_input_error_info('1e400000', 'numeric');

Explanation: Regression test for Numeric in PostgreSQL core test suite.

SELECT count(*) FROM (SELECT * FROM pg_input_error_info('1e400000', 'numeric')) AS _sub;


Question: pgTAP test for Index (assertion 94).

SELECT * FROM check_test(
    is_clustered( 'idx_bar' ),
    true,
    'is_clustered() index only',
    'Table should be clustered on index idx_bar',
    ''
);

Explanation: SQL assertion from pgTAP test suite for Index.


Question: pgTAP test for Privs (assertion 80).

SELECT * FROM check_test(
    tablespace_privs_are( 'pg_default', current_user, '{CREATE}' ),
    true,
    'tablespace_privs_are(tablespace, role, privs, desc)',
    'Role ' || quote_ident(current_user) || ' should be granted CREATE on tablespace pg_default',
    ''
);

Explanation: SQL assertion from pgTAP test suite for Privs.


Question: PostgreSQL regression test 'alter_generic': Write the SELECT query (example 73).

SELECT nspname, opcname, amname, rolname
  FROM pg_opclass o, pg_am m, pg_namespace n, pg_authid a
  WHERE o.opcmethod = m.oid AND o.opcnamespace = n.oid AND o.opcowner = a.oid
    AND n.nspname IN ('alt_nsp1', 'alt_nsp2')
  ORDER BY nspname, opcname;

Explanation: Regression test for Alter Generic in PostgreSQL core test suite.

SELECT count(*) FROM (SELECT nspname, opcname, amname, rolname
  FROM pg_opclass o, pg_am m, pg_namespace n, pg_authid a
  WHERE o.opcmethod = m.oid AND o.opcnamespace = n.oid AND o.opcowner = a.oid
    AND n.nspname IN ('alt_nsp1', 'alt_nsp2')
  ORDER BY nspname, opcname) AS _sub;


Question: pgTAP test for Coltap (assertion 62).

SELECT * FROM check_test(
    col_has_default( 'sometab', '__asdfasdfs__' ),
    false,
    'col_has_default( tab, col )',
    'Column sometab.__asdfasdfs__ should have a default',
    '    Column sometab.__asdfasdfs__ does not exist'
);

Explanation: SQL assertion from pgTAP test suite for Coltap.


Question: PostgreSQL regression test 'partition_info': Write the SELECT query (example 34).

Explanation: Regression test for Partition Info in PostgreSQL core test suite.

SELECT count(*) FROM (SELECT pg_partition_root('ptif_test3_index')) AS _sub;


Question: Write the PL/pgSQL object from PostgreSQL regression test 'plpgsql' (example 226).

end$$ language plpgsql;

select multi_datum_use(42);

--
-- Test STRICT limiter in both planned and EXECUTE invocations.
-- Note that a data-modifying query is quasi strict (disallow multi rows)
-- by default in the planned case, but not in EXECUTE.
--

create temp table foo (f1 int, f2 int);

insert into foo values (1,2), (3,4);

create or replace function stricttest() returns void as $$
declare x record;

Explanation: PL/pgSQL object from PostgreSQL core test for Plpgsql.


Question: Write the SQL definition from PostgreSQL contrib extension 'contrib' (item 39).

CREATE FUNCTION cube(float8) RETURNS cube
AS 'MODULE_PATHNAME', 'cube_f8'
LANGUAGE C IMMUTABLE STRICT PARALLEL SAFE;

Explanation: SQL definition from the 'contrib' PostgreSQL contrib extension.


Question: PostgreSQL regression test 'jsonb': Write the SELECT query (example 641).

Explanation: Regression test for Jsonb in PostgreSQL core test suite.


Question: Write the DDL statement from PostgreSQL regression test 'box' (example 70).

CREATE TABLE quad_box_tbl_ord_seq2 AS
SELECT rank() OVER (ORDER BY b <-> point '123,456') n, b <-> point '123,456' dist, id
FROM quad_box_tbl WHERE b <@ box '((200,300),(500,600))';

Explanation: DDL from PostgreSQL core regression test for Box.


Question: Write the DDL statement from PostgreSQL regression test 'numeric' (example 6).

CREATE TABLE num_exp_sqrt (id int4, expected numeric(210,10));

Explanation: DDL from PostgreSQL core regression test for Numeric.


Question: pgTAP test for Hastap (assertion 55).

SELECT * FROM check_test(
    hasnt_view( '__SDFSDFD__', 'howdy' ),
    true,
    'hasnt_view(non-existent view, desc)',
    'howdy',
    ''
);

Explanation: SQL assertion from pgTAP test suite for Hastap.


Question: Write the DDL statement from PostgreSQL regression test 'constraints' (example 332).

CREATE TABLE ATACC3 (a int) INHERITS (ATACC2);

Explanation: DDL from PostgreSQL core regression test for Constraints.


Question: Write the DDL statement from PostgreSQL regression test 'spgist' (example 24).

create table spgist_domain_tbl (f1 spgist_text);

Explanation: DDL from PostgreSQL core regression test for Spgist.


Question: Write the PL/pgSQL object from PostgreSQL regression test 'truncate' (example 158).

DROP FUNCTION tp_ins_data(), tp_chk_data();

Explanation: PL/pgSQL object from PostgreSQL core test for Truncate.


Question: Write the DML statement from PostgreSQL regression test 'without_overlaps' (example 87).

Explanation: DML from PostgreSQL core regression test for Without Overlaps.


Question: Write the DDL statement from PostgreSQL regression test 'copydml' (example 43).

create rule qqq as on delete to copydml_test do also insert into copydml_test default values;

Explanation: DDL from PostgreSQL core regression test for Copydml.


Question: Write the PL/pgSQL object from PostgreSQL regression test 'update' (example 260).

DROP TRIGGER trig_skip_delete ON sub_part2;

Explanation: PL/pgSQL object from PostgreSQL core test for Update.


Question: PostgreSQL regression test 'domain': Write the SELECT query (example 95).

select m, m is not null from makedcomp(1,2) m;

Explanation: Regression test for Domain in PostgreSQL core test suite.

SELECT count(*) FROM (select m, m is not null from makedcomp(1,2) m) AS _sub;


Question: Write the SQL definition from PostgreSQL contrib extension 'contrib' (item 47).

CREATE FUNCTION isnle(ean13, ismn13)
	RETURNS boolean
	AS 'int8le'
	LANGUAGE 'internal'
	IMMUTABLE STRICT
	PARALLEL SAFE;


Question: Show a query using PostgreSQL contrib extension 'btree_gist' (example 4).

Explanation: Example query from the 'btree_gist' extension test/demo.


Question: PostgreSQL regression test 'sqljson_jsontable': Write the SELECT query (example 70).

SELECT a, a::bool FROM JSON_TABLE(jsonb '{"a":1}', '$' COLUMNS (a dint4_0 EXISTS PATH '$.b' TRUE ON ERROR));

Explanation: Regression test for Sqljson Jsontable in PostgreSQL core test suite.

SELECT count(*) FROM (SELECT a, a::bool FROM JSON_TABLE(jsonb '{"a":1}', '$' COLUMNS (a dint4_0 EXISTS PATH '$.b' TRUE ON ERROR))) AS _sub;


Question: Write the DML statement from PostgreSQL regression test 'int8' (example 7).

Explanation: DML from PostgreSQL core regression test for Int8.


Question: Write the PL/pgSQL object from PostgreSQL regression test 'plpgsql' (example 467).

$$ language plpgsql;

select compos();

-- this does not work currently (no implicit casting)
create or replace function compos() returns compostype as $$
begin
  return (1, 'hello');


Question: Show a query using PostgreSQL contrib extension 'btree_gin' (example 25).

SELECT * FROM test_int2 WHERE i<=(-32769)::int4 ORDER BY i;

Explanation: Example query from the 'btree_gin' extension test/demo.


Question: PostgreSQL regression test 'hash_func': Write the SELECT query (example 25).

SELECT v as value, uuid_hash(v)::bit(32) as standard,
       uuid_hash_extended(v, 0)::bit(32) as extended0,
       uuid_hash_extended(v, 1)::bit(32) as extended1
FROM   (VALUES (NULL::uuid), ('a0eebc99-9c0b-4ef8-bb6d-6bb9bd380a11'),
        ('5a9ba4ac-8d6f-11e7-bb31-be2e44b06b34'),
        ('99c6705c-d939-461c-a3c9-1690ad64ed7b'),
        ('7deed3ca-8d6f-11e7-bb31-be2e44b06b34'),
        ('9ad46d4f-6f2a-4edd-aadb-745993928e1e')) x(v)
WHERE  uuid_hash(v)::bit(32) != uuid_hash_extended(v, 0)::bit(32)
       OR uuid_hash(v)::bit(32) = uuid_hash_extended(v, 1)::bit(32);

Explanation: Regression test for Hash Func in PostgreSQL core test suite.

SELECT count(*) FROM (SELECT v as value, uuid_hash(v)::bit(32) as standard,
       uuid_hash_extended(v, 0)::bit(32) as extended0,
       uuid_hash_extended(v, 1)::bit(32) as extended1
FROM   (VALUES (NULL::uuid), ('a0eebc99-9c0b-4ef8-bb6d-6bb9bd380a11'),
        ('5a9ba4ac-8d6f-11e7-bb31-be2e44b06b34'),
        ('99c6705c-d939-461c-a3c9-1690ad64ed7b'),
        ('7deed3ca-8d6f-11e7-bb31-be2e44b06b34'),
        ('9ad46d4f-6f2a-4edd-aadb-745993928e1e')) x(v)
WHERE  uuid_hash(v)::bit(32) != uuid_hash_extended(v, 0)::bit(32)
       OR uuid_hash(v)::bit(32) = uuid_hash_extended(v, 1)::bit(32)) AS _sub;


Question: Write the PL/pgSQL object from PostgreSQL regression test 'aggregates' (example 263).

-- Ensure that we never choose to provide presorted input to an Aggref with
-- a volatile function in the ORDER BY / DISTINCT clause.  We want to ensure
-- these sorts are performed individually rather than at the query level.
explain (costs off)
select
  sum(unique1 order by two), sum(unique1 order by four),
  sum(unique1 order by four, two), sum(unique1 order by two, random()),
  sum(unique1 order by two, random(), random() + 1)
from tenk1
group by ten;

Explanation: PL/pgSQL object from PostgreSQL core test for Aggregates.


Question: PostgreSQL regression test 'txid': Write the SELECT query (example 36).

SELECT txid_status(1); -- BootstrapTransactionId is always committed
SELECT txid_status(2); -- FrozenTransactionId is always committed
SELECT txid_status(3); -- in regress testing FirstNormalTransactionId will always be behind oldestXmin

COMMIT;

Explanation: Regression test for Txid in PostgreSQL core test suite.

SELECT count(*) FROM (SELECT txid_status(1); -- BootstrapTransactionId is always committed
SELECT txid_status(2); -- FrozenTransactionId is always committed
SELECT txid_status(3); -- in regress testing FirstNormalTransactionId will always be behind oldestXmin

COMMIT) AS _sub;


Question: Write the DDL statement from PostgreSQL regression test 'join' (example 888).

CREATE STATISTICS group_tbl_stat (ndistinct) ON a, b FROM group_tbl;

Explanation: DDL from PostgreSQL core regression test for Join.


Question: Write the SQL definition from PostgreSQL contrib extension 'contrib' (item 5).

CREATE FUNCTION gbt_cash_sortsupport(internal)
RETURNS void
AS 'MODULE_PATHNAME'
LANGUAGE C IMMUTABLE PARALLEL SAFE STRICT;

Explanation: SQL definition from the 'contrib' PostgreSQL contrib extension.


Question: Show a query using PostgreSQL contrib extension 'btree_gist' (example 8).

SELECT a, a <-> '199 days 21:21:23' FROM intervaltmp ORDER BY a <-> '199 days 21:21:23' LIMIT 3;


Question: PostgreSQL regression test 'strings': Write the SELECT query (example 52).

SELECT ('\x' || repeat('@', 34))::bytea;

Explanation: Regression test for Strings in PostgreSQL core test suite.

SELECT count(*) FROM (SELECT ('\x' || repeat('@', 34))::bytea) AS _sub;


Question: pgTAP test for Ownership (assertion 27).

SELECT * FROM check_test(
    relation_owner_is('public', '__not__sometab', current_user, 'mumble'),
	false,
    'relation_owner_is(sch, non-tab, user)',
    'mumble',
    '    Relation public.__not__sometab does not exist'
);

Explanation: SQL assertion from pgTAP test suite for Ownership.


Question: PostgreSQL regression test 'groupingsets': Write the SELECT query (example 86).

select a, b, count(*) from gstest2 group by grouping sets ((a, b), (a)) having a > 1 and b > 1;

Explanation: Regression test for Groupingsets in PostgreSQL core test suite.

SELECT count(*) FROM (select a, b, count(*) from gstest2 group by grouping sets ((a, b), (a)) having a > 1 and b > 1) AS _sub;


Question: Show a query using PostgreSQL contrib extension 'pgcrypto' (example 15).

Explanation: Example query from the 'pgcrypto' extension test/demo.


Question: Write the DDL statement from PostgreSQL regression test 'collate.icu.utf8' (example 23).

CREATE DOMAIN testdomain_i AS int COLLATE "sv-x-icu"; -- fails
CREATE TABLE collate_test4 (
    a int,
    b testdomain_sv
);

Explanation: DDL from PostgreSQL core regression test for Collate.Icu.Utf8.


Question: pgTAP test for Hastap (assertion 84).

SELECT * FROM check_test(
    hasnt_composite( 'sometype', 'lol' ),
    false,
    'hasnt_composite(tab, desc)',
    'lol',
    ''
);

Explanation: SQL assertion from pgTAP test suite for Hastap.


Question: Write the DDL statement from PostgreSQL regression test 'rowsecurity' (example 612).

CREATE POLICY p2 ON y1 FOR SELECT USING (a > 2);

Explanation: DDL from PostgreSQL core regression test for Rowsecurity.


Question: PostgreSQL regression test 'stats_ext': Write the SELECT query (example 316).

SELECT * FROM check_estimated_rows('SELECT * FROM functional_dependencies WHERE a = ANY (ARRAY[1, 2, 51, 52]) AND b = ANY (ARRAY[''1'', ''2''])');

Explanation: Regression test for Stats Ext in PostgreSQL core test suite.

SELECT count(*) FROM (SELECT * FROM check_estimated_rows('SELECT * FROM functional_dependencies WHERE a = ANY (ARRAY[1, 2, 51, 52]) AND b = ANY (ARRAY[''1'', ''2''])')) AS _sub;


Question: Write the DDL statement from PostgreSQL regression test 'insert' (example 242).

Explanation: DDL from PostgreSQL core regression test for Insert.


Question: PostgreSQL regression test 'money': Write the SELECT query (example 104).

Explanation: Regression test for Money in PostgreSQL core test suite.

SELECT count(*) FROM (SELECT '-1'::money / 1.175494e-38::float4) AS _sub;


Question: Write the SQL definition from PostgreSQL contrib extension 'contrib' (item 1).

/* contrib/postgres_fdw/postgres_fdw--1.0--1.1.sql */

-- complain if script is sourced in psql, rather than via ALTER EXTENSION
\echo Use "ALTER EXTENSION postgres_fdw UPDATE TO '1.1'" to load this file. \quit

CREATE FUNCTION postgres_fdw_get_connections (OUT server_name text,
    OUT valid boolean)
RETURNS SETOF record
AS 'MODULE_PATHNAME'
LANGUAGE C STRICT PARALLEL RESTRICTED;


Question: Write the SQL definition from PostgreSQL contrib extension 'contrib' (item 112).

CREATE FUNCTION isnlt(isbn, ean13)
	RETURNS boolean
	AS 'int8lt'
	LANGUAGE 'internal'
	IMMUTABLE STRICT
	PARALLEL SAFE;


Question: Write the DDL statement from PostgreSQL regression test 'alter_table' (example 257).

create function alter1.same(alter1.ctype, alter1.ctype) returns boolean language sql
as 'select $1.f1 is not distinct from $2.f1 and $1.f2 is not distinct from $2.f2';

Explanation: DDL from PostgreSQL core regression test for Alter Table.


Question: PostgreSQL regression test 'int8': Write the SELECT query (example 155).

Explanation: Regression test for Int8 in PostgreSQL core test suite.

SELECT count(*) FROM (SELECT int8 '0x7FFFFFFFFFFFFFFF') AS _sub;


Question: Write the SQL definition from PostgreSQL contrib extension 'contrib' (item 164).

-- Create the operator class
CREATE OPERATOR CLASS gist_cash_ops
DEFAULT FOR TYPE money USING gist
AS
	OPERATOR	1	<  ,
	OPERATOR	2	<= ,
	OPERATOR	3	=  ,
	OPERATOR	4	>= ,
	OPERATOR	5	>  ,
	OPERATOR	6	<> ,
	OPERATOR	15	<-> FOR ORDER BY pg_catalog.money_ops ,
	FUNCTION	1	gbt_cash_consistent (internal, money, int2, oid, internal),
	FUNCTION	2	gbt_cash_union (internal, internal),
	FUNCTION	3	gbt_cash_compress (internal),
	FUNCTION	4	gbt_decompress (internal),
	FUNCTION	5	gbt_cash_penalty (internal, internal, internal),
	FUNCTION	6	gbt_cash_picksplit (internal, internal),
	FUNCTION	7	gbt_cash_same (gbtreekey16, gbtreekey16, internal),
	FUNCTION	8	gbt_cash_distance (internal, money, int2, oid, internal),
	FUNCTION	9	gbt_cash_fetch (internal),
	FUNCTION	11	gbt_cash_sortsupport (internal),
	FUNCTION	12 ("any", "any") gist_translate_cmptype_btree (int),
	STORAGE		gbtreekey16;


Question: Show a query using PostgreSQL contrib extension 'spi' (example 7).

Explanation: Example query from the 'spi' extension test/demo.


Question: pgTAP test for Pgtap--Unpackaged--0.91.0 (assertion 350).

ALTER EXTENSION pgtap ADD FUNCTION hasnt_user( NAME, TEXT );

Explanation: SQL assertion from pgTAP test suite for Pgtap--Unpackaged--0.91.0.


Question: Write the DDL statement from PostgreSQL regression test 'alter_table' (example 167).


Question: Show a query using PostgreSQL contrib extension 'test_decoding' (example 19).

SELECT 'cleanup' FROM pg_drop_replication_slot('regression_slot');

Explanation: Example query from the 'test_decoding' extension test/demo.


Question: Write the DDL statement from PostgreSQL regression test 'uuid' (example 2).

CREATE TABLE guid2
(
	guid_field UUID,
	text_field TEXT DEFAULT(now())
);

Explanation: DDL from PostgreSQL core regression test for Uuid.


Question: Write the DML statement from PostgreSQL regression test 'gin' (example 11).

delete from gin_test_tbl where i @> array[2];

Explanation: DML from PostgreSQL core regression test for Gin.


Question: PostgreSQL regression test 'jsonb': Write the SELECT query (example 421).

select * from jsonb_to_record('{"ia2": [1, 2, 3]}') as x(ia2 int[][]);

Explanation: Regression test for Jsonb in PostgreSQL core test suite.

SELECT count(*) FROM (select * from jsonb_to_record('{"ia2": [1, 2, 3]}') as x(ia2 int[][])) AS _sub;


Question: Write the DML statement from PostgreSQL regression test 'oid' (example 2).

INSERT INTO OID_TBL(f1) VALUES ('1234');

Explanation: DML from PostgreSQL core regression test for Oid.


Question: Write the DDL statement from PostgreSQL regression test 'rules' (example 495).

CREATE RULE InsertRule AS
    ON INSERT TO rule_v1
    DO INSTEAD
        INSERT INTO rule_t1 VALUES(new.a);

Explanation: DDL from PostgreSQL core regression test for Rules.


Question: pgTAP test for Pgtap--Unpackaged--0.91.0 (assertion 269).

ALTER EXTENSION pgtap ADD FUNCTION hasnt_index ( NAME, NAME, NAME, TEXT );


Question: PL/pgSQL test: Plperl (example 56).

CREATE OR REPLACE FUNCTION
perl_out_params_set(out f1 integer, out f2 text, out f3 text)
RETURNS SETOF record AS $$
    return [
        { f1 => 1, f2 => 'Hello', f3 =>  'World' },
        { f1 => 2, f2 => 'Hello', f3 =>  'PostgreSQL' },
        { f1 => 3, f2 => 'Hello', f3 =>  'PL/Perl' }
    ];
$$  LANGUAGE plperl;

Explanation: PL/pgSQL example from PostgreSQL source test for Plperl.


Question: Show a query using PostgreSQL contrib extension 'citext' (example 404).

SELECT strpos('high',         'gh'::citext) = 3 AS t;

Explanation: Example query from the 'citext' extension test/demo.


Question: PostgreSQL regression test 'jsonb': Write the SELECT query (example 410).

select * from jsonb_populate_recordset(row(1000000000::int,50::int),'[{"b":"2"},{"a":"3"}]') q (a text, b text);

SELECT count(*) FROM (select * from jsonb_populate_recordset(row(1000000000::int,50::int),'[{"b":"2"},{"a":"3"}]') q (a text, b text)) AS _sub;


Question: PostgreSQL regression test 'xml': Write the SELECT query (example 192).

Explanation: Regression test for Xml in PostgreSQL core test suite.

SELECT count(*) FROM (SELECT xml_is_well_formed('abc')) AS _sub;


Question: PostgreSQL regression test 'tsearch': Write the SELECT query (example 322).

SELECT ts_rewrite('moscow', 'SELECT keyword, sample FROM test_tsquery'::text );

Explanation: Regression test for Tsearch in PostgreSQL core test suite.

SELECT count(*) FROM (SELECT ts_rewrite('moscow', 'SELECT keyword, sample FROM test_tsquery'::text )) AS _sub;


Question: Write the DDL statement from PostgreSQL regression test 'join' (example 679).

Explanation: DDL from PostgreSQL core regression test for Join.


Question: PostgreSQL Json: show example 8.

SELECT doc->'site_name' FROM websites WHERE doc->'tags' @> '[{"term":"paris"}, {"term":"food"}]';

Explanation: Example from PostgreSQL documentation on Json.


Question: Show a query using PostgreSQL contrib extension 'btree_gist' (example 4).

SELECT count(*) FROM varbittmp WHERE a <=  '1110100111010';

Explanation: Example query from the 'btree_gist' extension test/demo.


Question: Write the DDL statement from PostgreSQL regression test 'merge' (example 3).

Explanation: DDL from PostgreSQL core regression test for Merge.


Question: PL/pgSQL test: Plperl Plperlu (example 14).

CREATE OR REPLACE FUNCTION use_plperl() RETURNS void LANGUAGE plperl
AS $$
use Errno;
$$;

Explanation: PL/pgSQL example from PostgreSQL source test for Plperl Plperlu.


Question: PL/pgSQL test: Plpython Spi (example 7).

CREATE FUNCTION join_sequences(s sequences) RETURNS text
	AS
'if not s["multipart"]:
	return s["sequence"]
q = "SELECT sequence FROM xsequences WHERE pid = ''%s''" % s["pid"]
rv = plpy.execute(q)
seq = s["sequence"]
for r in rv:
	seq = seq + r["sequence"]
return seq
'
	LANGUAGE plpython3u;

Explanation: PL/pgSQL example from PostgreSQL source test for Plpython Spi.


Question: PostgreSQL regression test 'stats_ext': Write the SELECT query (example 557).

SELECT * FROM check_estimated_rows('SELECT * FROM mcv_lists WHERE a IS NULL AND b IS NULL');

Explanation: Regression test for Stats Ext in PostgreSQL core test suite.

SELECT count(*) FROM (SELECT * FROM check_estimated_rows('SELECT * FROM mcv_lists WHERE a IS NULL AND b IS NULL')) AS _sub;


Question: Write the SQL definition from PostgreSQL contrib extension 'contrib' (item 43).

CREATE FUNCTION hstore_to_jsonb_loose(hstore)
RETURNS jsonb
AS 'MODULE_PATHNAME', 'hstore_to_jsonb_loose'
LANGUAGE C IMMUTABLE STRICT PARALLEL SAFE;

Explanation: SQL definition from the 'contrib' PostgreSQL contrib extension.


Question: PostgreSQL regression test 'jsonb': Write the SELECT query (example 424).

select * from jsonb_to_record('{"out": {"key": 1}}') as x(out json);

SELECT count(*) FROM (select * from jsonb_to_record('{"out": {"key": 1}}') as x(out json)) AS _sub;


Question: Show a query using PostgreSQL contrib extension 'btree_gist' (example 14).

SELECT count(*) FROM cidrtmp WHERE a >  '121.111.63.82'::cidr;


Question: PL/pgSQL test: Plpython Composite (example 3).

Explanation: PL/pgSQL example from PostgreSQL source test for Plpython Composite.


Question: PL/pgSQL test: Plpgsql Array (example 17).

do $$ declare a int[];
begin a := * from onecol for update; raise notice 'a = %', a; end$$;

Explanation: PL/pgSQL example from PostgreSQL source test for Plpgsql Array.


Question: PostgreSQL regression test 'regex': Write the SELECT query (example 36).

Explanation: Regression test for Regex in PostgreSQL core test suite.

SELECT count(*) FROM (select regexp_matches('foobar', '(?<=f)b+')) AS _sub;


Question: PostgreSQL regression test 'jsonb': Write the SELECT query (example 672).

Explanation: Regression test for Jsonb in PostgreSQL core test suite.

SELECT count(*) FROM (select '{"aa":1 , "b":2, "cq":3}'::jsonb || '{}') AS _sub;


Question: pgTAP test for Resultset (assertion 347).

SELECT * FROM check_test(
    set_hasnt( 'anames', 'others', 'whatever' ),
    true,
    'set_hasnt( prepared, prepared, description )',
    'whatever',
    ''
);

Explanation: SQL assertion from pgTAP test suite for Resultset.


Question: Write the SQL definition from PostgreSQL contrib extension 'postgres_fdw' (item 370).

$$ LANGUAGE plpgsql;
CREATE TRIGGER t1_br_insert BEFORE INSERT OR UPDATE
    ON "S 1"."T 1" FOR EACH ROW EXECUTE PROCEDURE "S 1".F_BRTRIG();

INSERT INTO ft2 (c1,c2,c3) VALUES (1208, 818, 'fff') RETURNING *;
INSERT INTO ft2 (c1,c2,c3,c6) VALUES (1218, 818, 'ggg', '(--;') RETURNING *;
UPDATE ft2 SET c2 = c2 + 600 WHERE c1 % 10 = 8 AND c1 < 1200 RETURNING *;

-- Test errors thrown on remote side during update
ALTER TABLE "S 1"."T 1" ADD CONSTRAINT c2positive CHECK (c2 >= 0);

INSERT INTO ft1(c1, c2) VALUES(11, 12);  -- duplicate key
INSERT INTO ft1(c1, c2) VALUES(11, 12) ON CONFLICT DO NOTHING; -- works
INSERT INTO ft1(c1, c2) VALUES(11, 12) ON CONFLICT (c1, c2) DO NOTHING; -- unsupported
INSERT INTO ft1(c1, c2) VALUES(11, 12) ON CONFLICT (c1, c2) DO UPDATE SET c3 = 'ffg'; -- unsupported
INSERT INTO ft1(c1, c2) VALUES(1111, -2);  -- c2positive
UPDATE ft1 SET c2 = -c2 WHERE c1 = 1;  -- c2positive

-- Test savepoint/rollback behavior
select c2, count(*) from ft2 where c2 < 500 group by 1 order by 1;
select c2, count(*) from "S 1"."T 1" where c2 < 500 group by 1 order by 1;
begin;
update ft2 set c2 = 42 where c2 = 0;
select c2, count(*) from ft2 where c2 < 500 group by 1 order by 1;
savepoint s1;
update ft2 set c2 = 44 where c2 = 4;
select c2, count(*) from ft2 where c2 < 500 group by 1 order by 1;
release savepoint s1;
select c2, count(*) from ft2 where c2 < 500 group by 1 order by 1;
savepoint s2;
update ft2 set c2 = 46 where c2 = 6;
select c2, count(*) from ft2 where c2 < 500 group by 1 order by 1;
rollback to savepoint s2;
select c2, count(*) from ft2 where c2 < 500 group by 1 order by 1;
release savepoint s2;
select c2, count(*) from ft2 where c2 < 500 group by 1 order by 1;
savepoint s3;
update ft2 set c2 = -2 where c2 = 42 and c1 = 10; -- fail on remote side
rollback to savepoint s3;
select c2, count(*) from ft2 where c2 < 500 group by 1 order by 1;
release savepoint s3;
select c2, count(*) from ft2 where c2 < 500 group by 1 order by 1;
-- none of the above is committed yet remotely
select c2, count(*) from "S 1"."T 1" where c2 < 500 group by 1 order by 1;
commit;
select c2, count(*) from ft2 where c2 < 500 group by 1 order by 1;
select c2, count(*) from "S 1"."T 1" where c2 < 500 group by 1 order by 1;

VACUUM ANALYZE "S 1"."T 1";

-- Above DMLs add data with c6 as NULL in ft1, so test ORDER BY NULLS LAST and NULLs
-- FIRST behavior here.
-- ORDER BY DESC NULLS LAST options
EXPLAIN (VERBOSE, COSTS OFF) SELECT * FROM ft1 ORDER BY c6 DESC NULLS LAST, c1 OFFSET 795 LIMIT 10;
SELECT * FROM ft1 ORDER BY c6 DESC NULLS LAST, c1 OFFSET 795  LIMIT 10;
-- ORDER BY DESC NULLS FIRST options
EXPLAIN (VERBOSE, COSTS OFF) SELECT * FROM ft1 ORDER BY c6 DESC NULLS FIRST, c1 OFFSET 15 LIMIT 10;
SELECT * FROM ft1 ORDER BY c6 DESC NULLS FIRST, c1 OFFSET 15 LIMIT 10;
-- ORDER BY ASC NULLS FIRST options
EXPLAIN (VERBOSE, COSTS OFF) SELECT * FROM ft1 ORDER BY c6 ASC NULLS FIRST, c1 OFFSET 15 LIMIT 10;
SELECT * FROM ft1 ORDER BY c6 ASC NULLS FIRST, c1 OFFSET 15 LIMIT 10;

-- Test ReScan code path that recreates the cursor even when no parameters
-- change (bug #17889)
CREATE TABLE loct1 (c1 int);
CREATE TABLE loct2 (c1 int, c2 text);
INSERT INTO loct1 VALUES (1001);
INSERT INTO loct1 VALUES (1002);
INSERT INTO loct2 SELECT id, to_char(id, 'FM0000') FROM generate_series(1, 1000) id;
INSERT INTO loct2 VALUES (1001, 'foo');
INSERT INTO loct2 VALUES (1002, 'bar');
CREATE FOREIGN TABLE remt2 (c1 int, c2 text) SERVER loopback OPTIONS (table_name 'loct2');
ANALYZE loct1;
ANALYZE remt2;
SET enable_mergejoin TO false;
SET enable_hashjoin TO false;
SET enable_material TO false;
EXPLAIN (VERBOSE, COSTS OFF)
UPDATE remt2 SET c2 = remt2.c2 || remt2.c2 FROM loct1 WHERE loct1.c1 = remt2.c1 RETURNING remt2.*;
UPDATE remt2 SET c2 = remt2.c2 || remt2.c2 FROM loct1 WHERE loct1.c1 = remt2.c1 RETURNING remt2.*;
RESET enable_mergejoin;
RESET enable_hashjoin;
RESET enable_material;
DROP FOREIGN TABLE remt2;
DROP TABLE loct1;
DROP TABLE loct2;

-- ===================================================================
-- test check constraints
-- ===================================================================

-- Consistent check constraints provide consistent results
ALTER FOREIGN TABLE ft1 ADD CONSTRAINT ft1_c2positive CHECK (c2 >= 0);
EXPLAIN (VERBOSE, COSTS OFF) SELECT count(*) FROM ft1 WHERE c2 < 0;
SELECT count(*) FROM ft1 WHERE c2 < 0;
SET constraint_exclusion = 'on';
EXPLAIN (VERBOSE, COSTS OFF) SELECT count(*) FROM ft1 WHERE c2 < 0;
SELECT count(*) FROM ft1 WHERE c2 < 0;
RESET constraint_exclusion;
-- check constraint is enforced on the remote side, not locally
INSERT INTO ft1(c1, c2) VALUES(1111, -2);  -- c2positive
UPDATE ft1 SET c2 = -c2 WHERE c1 = 1;  -- c2positive
ALTER FOREIGN TABLE ft1 DROP CONSTRAINT ft1_c2positive;

-- But inconsistent check constraints provide inconsistent results
ALTER FOREIGN TABLE ft1 ADD CONSTRAINT ft1_c2negative CHECK (c2 < 0);
EXPLAIN (VERBOSE, COSTS OFF) SELECT count(*) FROM ft1 WHERE c2 >= 0;
SELECT count(*) FROM ft1 WHERE c2 >= 0;
SET constraint_exclusion = 'on';
EXPLAIN (VERBOSE, COSTS OFF) SELECT count(*) FROM ft1 WHERE c2 >= 0;
SELECT count(*) FROM ft1 WHERE c2 >= 0;
RESET constraint_exclusion;
-- local check constraint is not actually enforced
INSERT INTO ft1(c1, c2) VALUES(1111, 2);
UPDATE ft1 SET c2 = c2 + 1 WHERE c1 = 1;
ALTER FOREIGN TABLE ft1 DROP CONSTRAINT ft1_c2negative;

-- ===================================================================
-- test WITH CHECK OPTION constraints
-- ===================================================================

CREATE FUNCTION row_before_insupd_trigfunc() RETURNS trigger AS $$BEGIN NEW.a := NEW.a + 10; RETURN NEW; END$$ LANGUAGE plpgsql;

Explanation: SQL definition from the 'postgres_fdw' PostgreSQL contrib extension.


Question: Write the DML statement from PostgreSQL regression test 'inherit' (example 10).

Explanation: DML from PostgreSQL core regression test for Inherit.


Question: Write the DML statement from PostgreSQL regression test 'fast_default' (example 28).

Explanation: DML from PostgreSQL core regression test for Fast Default.


Question: pgTAP test for Pgtap--Unpackaged--0.91.0 (assertion 444).

ALTER EXTENSION pgtap ADD FUNCTION has_language( NAME, TEXT );

Explanation: SQL assertion from pgTAP test suite for Pgtap--Unpackaged--0.91.0.


Question: Write the DDL statement from PostgreSQL regression test 'constraints' (example 363).

Explanation: DDL from PostgreSQL core regression test for Constraints.


Question: Write the DDL statement from PostgreSQL regression test 'plancache' (example 60).

create table pc_list_part_def partition of pc_list_parted default;

Explanation: DDL from PostgreSQL core regression test for Plancache.


Question: PostgreSQL regression test 'float8': Write the SELECT query (example 68).

Explanation: Regression test for Float8 in PostgreSQL core test suite.

SELECT count(*) FROM (SELECT power(float8 'inf', float8 '0')) AS _sub;


Question: PostgreSQL regression test 'stats_ext': Write the SELECT query (example 311).

SELECT * FROM check_estimated_rows('SELECT * FROM functional_dependencies WHERE (a = 1 OR a = 51) AND (b = ''1'' OR b = ''2'')');

SELECT count(*) FROM (SELECT * FROM check_estimated_rows('SELECT * FROM functional_dependencies WHERE (a = 1 OR a = 51) AND (b = ''1'' OR b = ''2'')')) AS _sub;


Question: pgTAP test for Todotap (assertion 12).

-- Test num only.
SELECT * FROM check_test(
    skip(1),
    true,
    'num only',
    '',
    'SKIP'
);

Explanation: SQL assertion from pgTAP test suite for Todotap.


Question: pgTAP test for Resultset (assertion 228).

-- Compare actual SELECT statements.
SELECT * FROM check_test(
    set_eq(
        'SELECT id, name FROM names WHERE name like ''An%''',
        'SELECT id, name FROM annames'
    ),
    true,
    'set_eq(select, select)',
    '',
    ''
);


Question: Write the DML statement from PostgreSQL regression test 'rules' (example 325).

INSERT INTO shoelace_arrive VALUES ('sl6', 20);

Explanation: DML from PostgreSQL core regression test for Rules.


Question: pgTAP test for Pgtap--Unpackaged--0.91.0 (assertion 254).

ALTER EXTENSION pgtap ADD FUNCTION _have_index( NAME, NAME, NAME);


Question: Show a query using PostgreSQL contrib extension 'btree_gin' (example 24).

SELECT * FROM test_int2 WHERE i<(-32769)::int4 ORDER BY i;

Explanation: Example query from the 'btree_gin' extension test/demo.


Question: PostgreSQL regression test 'timestamptz': Write the SELECT query (example 339).

SELECT '2011-03-26 23:59:59 UTC'::timestamptz AT TIME ZONE 'Europe/Moscow';

Explanation: Regression test for Timestamptz in PostgreSQL core test suite.

SELECT count(*) FROM (SELECT '2011-03-26 23:59:59 UTC'::timestamptz AT TIME ZONE 'Europe/Moscow') AS _sub;


Question: PostgreSQL regression test 'explain': Write the SELECT query (example 60).

select explain_filter('explain (analyze,buffers off,costs off) select sum(n) over(partition by m) from (SELECT n < 3 as m, n from generate_series(1,2500) a(n))');

Explanation: Regression test for Explain in PostgreSQL core test suite.

SELECT count(*) FROM (select explain_filter('explain (analyze,buffers off,costs off) select sum(n) over(partition by m) from (SELECT n < 3 as m, n from generate_series(1,2500) a(n))')) AS _sub;


Question: Write the DDL statement from PostgreSQL regression test 'memoize' (example 34).

CREATE INDEX strtest_n_idx ON strtest (n);

Explanation: DDL from PostgreSQL core regression test for Memoize.


Question: PostgreSQL regression test 'arrays': Write the SELECT query (example 49).

Explanation: Regression test for Arrays in PostgreSQL core test suite.

SELECT count(*) FROM (SELECT * FROM arrtest_s) AS _sub;


Question: PostgreSQL regression test 'partition_join': Write the SELECT query (example 214).

SELECT COUNT(*) FROM prt1_l t1 LEFT JOIN LATERAL
			  (SELECT t1.b AS t1b, t2.* FROM prt2_l t2) s
			  ON t1.a = s.b AND t1.b = s.a AND t1.c = s.c
			  WHERE s.t1b = s.a;

Explanation: Regression test for Partition Join in PostgreSQL core test suite.

SELECT count(*) FROM (SELECT COUNT(*) FROM prt1_l t1 LEFT JOIN LATERAL
			  (SELECT t1.b AS t1b, t2.* FROM prt2_l t2) s
			  ON t1.a = s.b AND t1.b = s.a AND t1.c = s.c
			  WHERE s.t1b = s.a) AS _sub;


Question: Show a query using PostgreSQL contrib extension 'test_decoding' (example 78).

Explanation: Example query from the 'test_decoding' extension test/demo.


Question: PostgreSQL regression test 'float8': Write the SELECT query (example 171).

SELECT x,
       atand(x),
       atand(x) IN (-90,-45,0,45,90) AS atand_exact
FROM (VALUES ('-Infinity'::float8), (-1), (0), (1),
      ('Infinity'::float8)) AS t(x);

SELECT count(*) FROM (SELECT x,
       atand(x),
       atand(x) IN (-90,-45,0,45,90) AS atand_exact
FROM (VALUES ('-Infinity'::float8), (-1), (0), (1),
      ('Infinity'::float8)) AS t(x)) AS _sub;


Question: Show a query using PostgreSQL contrib extension 'postgres_fdw' (example 1355).

INSERT INTO local_tbl VALUES (1505, 505, 'foo'), (2505, 505, 'bar');

Explanation: Example query from the 'postgres_fdw' extension test/demo.


Question: Show a query using PostgreSQL contrib extension 'citext' (example 177).

INSERT INTO caster (chr)           VALUES ('f'::text);

Explanation: Example query from the 'citext' extension test/demo.


Question: Show a query using PostgreSQL contrib extension 'amcheck' (example 34).

Explanation: Example query from the 'amcheck' extension test/demo.


Question: Show a SQL definition from the postgrest project (replica, item 4).

create table replica.items as select x as id from generate_series(1, 10) x;

Explanation: SQL definition from the open-source postgrest PostgreSQL project.


Question: PostgreSQL regression test 'numeric': Write the SELECT query (example 710).

Explanation: Regression test for Numeric in PostgreSQL core test suite.

SELECT count(*) FROM (SELECT to_char('100'::numeric, 'f\\"oo999')) AS _sub;


Question: Write the DML statement from PostgreSQL regression test 'alter_table' (example 599).

Explanation: DML from PostgreSQL core regression test for Alter Table.


Question: Write the DDL statement from PostgreSQL regression test 'stats_ext' (example 133).

CREATE STATISTICS tststats.s3 ON a, b FROM tststats.s;

Explanation: DDL from PostgreSQL core regression test for Stats Ext.


Question: PostgreSQL regression test 'hash_index': Write the SELECT query (example 49).

SELECT h.seqno AS f20000
   FROM hash_f8_heap h
   WHERE h.random = '488912369'::float8;

Explanation: Regression test for Hash Index in PostgreSQL core test suite.

SELECT count(*) FROM (SELECT h.seqno AS f20000
   FROM hash_f8_heap h
   WHERE h.random = '488912369'::float8) AS _sub;


Question: PostgreSQL regression test 'aggregates': Write the SELECT query (example 170).

Explanation: Regression test for Aggregates in PostgreSQL core test suite.

SELECT count(*) FROM (select max(100) from tenk1) AS _sub;


Question: Write the DDL statement from PostgreSQL regression test 'publication' (example 124).

CREATE PUBLICATION testpub_rf_no FOR TABLE testpub_rf_tbl1;

Explanation: DDL from PostgreSQL core regression test for Publication.


Question: Write the DML statement from PostgreSQL regression test 'rowsecurity' (example 297).

INSERT INTO s1 (SELECT x, public.fipshash(x::text) FROM generate_series(-10,10) x);

Explanation: DML from PostgreSQL core regression test for Rowsecurity.


Question: PostgreSQL regression test 'xml': Write the SELECT query (example 18).

Explanation: Regression test for Xml in PostgreSQL core test suite.

SELECT count(*) FROM (SELECT xmlconcat(1, 2)) AS _sub;


Question: PostgreSQL regression test 'strings': Write the SELECT query (example 49).

SELECT ('\x' || repeat('0', 34))::bytea;

Explanation: Regression test for Strings in PostgreSQL core test suite.

SELECT count(*) FROM (SELECT ('\x' || repeat('0', 34))::bytea) AS _sub;


Question: pgTAP test for Proctap (assertion 38).

SELECT * FROM check_test(
    isnt_procedure( 'procschema', 'argproc'::name ),
    false,
    'isnt_procedure(schema, proc)',
    'Function procschema.argproc() should not be a procedure',
    ''
);

Explanation: SQL assertion from pgTAP test suite for Proctap.


Question: PostgreSQL regression test 'arrays': Write the SELECT query (example 394).

select array_agg('{}'::int[]) from generate_series(1,2);

Explanation: Regression test for Arrays in PostgreSQL core test suite.

SELECT count(*) FROM (select array_agg('{}'::int[]) from generate_series(1,2)) AS _sub;


Question: Create an exclusion constraint to prevent overlapping date ranges.

CREATE EXTENSION IF NOT EXISTS btree_gist;
CREATE TABLE room_bookings (
    id serial PRIMARY KEY,
    room_id int NOT NULL,
    during tstzrange NOT NULL,
    EXCLUDE USING gist (room_id WITH =, during WITH &&)
);

Explanation: Exclusion constraint with btree_gist prevents any two rows with the same room_id from having overlapping tstzrange values (&&).


Question: Write the DML statement from PostgreSQL regression test 'arrays' (example 104).

Explanation: DML from PostgreSQL core regression test for Arrays.


Question: Write the DML statement from PostgreSQL regression test 'numeric_big' (example 473).

Explanation: DML from PostgreSQL core regression test for Numeric Big.


Question: PostgreSQL regression test 'stats_ext': Write the SELECT query (example 433).

SELECT * FROM check_estimated_rows('SELECT * FROM mcv_lists WHERE a = 1 AND b = ''1'' AND c = 1');

Explanation: Regression test for Stats Ext in PostgreSQL core test suite.

SELECT count(*) FROM (SELECT * FROM check_estimated_rows('SELECT * FROM mcv_lists WHERE a = 1 AND b = ''1'' AND c = 1')) AS _sub;


Question: Show a SQL definition from the timescaledb project (bookend, item 1).

CREATE OR REPLACE FUNCTION _timescaledb_functions.first_sfunc(internal, anyelement, "any")
RETURNS internal
AS '@MODULE_PATHNAME@', 'ts_first_sfunc'
LANGUAGE C IMMUTABLE PARALLEL SAFE;

Explanation: SQL definition from the open-source timescaledb PostgreSQL project.


Question: PL/pgSQL test: Plperl Array (example 37).

select perl_setof_array('{{1}, {2}, {3}}');

Explanation: PL/pgSQL example from PostgreSQL source test for Plperl Array.


Question: PostgreSQL regression test 'join': Write the SELECT query (example 424).

select 1 from
  int4_tbl as i4
  inner join
    ((select 42 as n from int4_tbl x1 left join int8_tbl x2 on f1 = q1) as ss1
     right join (select 1 as z) as ss2 on true)
  on false,
  lateral (select i4.f1, ss1.n from int8_tbl as i8 limit 1) as ss3;

Explanation: Regression test for Join in PostgreSQL core test suite.

SELECT count(*) FROM (select 1 from
  int4_tbl as i4
  inner join
    ((select 42 as n from int4_tbl x1 left join int8_tbl x2 on f1 = q1) as ss1
     right join (select 1 as z) as ss2 on true)
  on false,
  lateral (select i4.f1, ss1.n from int8_tbl as i8 limit 1) as ss3) AS _sub;


Question: Write the DML statement from PostgreSQL regression test 'plpgsql' (example 757).

UPDATE alter_table_under_transition_tables
  SET name = (name::text || name::text)::integer;

Explanation: DML from PostgreSQL core regression test for Plpgsql.


Question: PostgreSQL regression test 'strings': Write the SELECT query (example 241).

SELECT POSITION('\x33'::bytea IN '\x1122'::bytea) = 0 AS "0";

SELECT count(*) FROM (SELECT POSITION('\x33'::bytea IN '\x1122'::bytea) = 0 AS "0") AS _sub;


Question: PostgreSQL regression test 'conversion': Write the SELECT query (example 50).

select description, inbytes, (test_conv(inbytes, 'iso8859-5', 'utf8')).* from iso8859_5_inputs;

Explanation: Regression test for Conversion in PostgreSQL core test suite.

SELECT count(*) FROM (select description, inbytes, (test_conv(inbytes, 'iso8859-5', 'utf8')).* from iso8859_5_inputs) AS _sub;


Question: Write the DML statement from PostgreSQL regression test 'generated_stored' (example 116).

INSERT INTO gtest_varlena (a) VALUES(NULL);

Explanation: DML from PostgreSQL core regression test for Generated Stored.


Question: PostgreSQL Extend: show example 5.

(LEFTARG = text, RIGHTARG = text, FUNCTION = pair); -- "SET search_path" is easy to get right, but qualified names perform better. CREATE FUNCTION lower(pair) RETURNS pair LANGUAGE SQL AS 'SELECT ROW(lower($1.k), lower($1.v))::@extschema@.pair;' SET search_path = pg_temp; CREATE FUNCTION pair_concat(pair, pair) RETURNS pair LANGUAGE SQL AS 'SELECT ROW($1.k OPERATOR(pg_catalog.||) $2.k, $1.v OPERATOR(pg_catalog.||) $2.v)::@extschema@.pair;'; ]]>;

Explanation: Example from PostgreSQL documentation on Extend.


Question: Write the SQL definition from PostgreSQL contrib extension 'contrib' (item 237).

CREATE OPERATOR <> (
	PROCEDURE = isnne,
	LEFTARG = ean13,
	RIGHTARG = issn13,
	COMMUTATOR = <>,
	NEGATOR = =,
	RESTRICT = neqsel,
	JOIN = neqjoinsel);

Explanation: SQL definition from the 'contrib' PostgreSQL contrib extension.


Question: PL/pgSQL test: Plpgsql Record (example 5).

-- base-case return of a composite type
create function retc(int) returns two_int8s language plpgsql as
$$ begin return row($1,1)::two_int8s; end $$;
select retc(42);

-- ok to return a matching record type
create or replace function retc(int) returns two_int8s language plpgsql as
$$ begin return row($1::int8, 1::int8); end $$;

Explanation: PL/pgSQL example from PostgreSQL source test for Plpgsql Record.


Question: PostgreSQL regression test 'tstypes': Write the SELECT query (example 47).

SELECT 'a b:89  ca:23A,64b d:34c'::tsvector @@ 'd:AC & ca:A' as "true";

Explanation: Regression test for Tstypes in PostgreSQL core test suite.

SELECT count(*) FROM (SELECT 'a b:89  ca:23A,64b d:34c'::tsvector @@ 'd:AC & ca:A' as "true") AS _sub;


Question: PostgreSQL regression test 'interval': Write the SELECT query (example 11).

SELECT INTERVAL 'infinity' AS "eternity";

Explanation: Regression test for Interval in PostgreSQL core test suite.

SELECT count(*) FROM (SELECT INTERVAL 'infinity' AS "eternity") AS _sub;


Question: PostgreSQL regression test 'multirangetypes': Write the SELECT query (example 64).

Explanation: Regression test for Multirangetypes in PostgreSQL core test suite.

SELECT count(*) FROM (select textrange(null, null)::textmultirange) AS _sub;


Question: Write the PL/pgSQL object from PostgreSQL regression test 'fast_default' (example 93).

Explanation: PL/pgSQL object from PostgreSQL core test for Fast Default.


Question: Write the PL/pgSQL object from PostgreSQL regression test 'triggers' (example 373).

--
-- Verify prohibition of row triggers with transition triggers on
-- partitions
--
create table parent (a text, b int) partition by list (a);

Explanation: PL/pgSQL object from PostgreSQL core test for Triggers.


Question: Show a query using PostgreSQL contrib extension 'seg' (example 152).

SELECT '1'::seg <@ '-1 .. 1'::seg AS bool;

Explanation: Example query from the 'seg' extension test/demo.


Question: Write the SQL definition from PostgreSQL contrib extension 'contrib' (item 210).

CREATE OPERATOR = (
	PROCEDURE = isneq,
	LEFTARG = ean13,
	RIGHTARG = isbn13,
	COMMUTATOR = =,
	NEGATOR = <>,
	RESTRICT = eqsel,
	JOIN = eqjoinsel,
	MERGES,
	HASHES);


Question: Write the DML statement from PostgreSQL regression test 'rowsecurity' (example 904).

Explanation: DML from PostgreSQL core regression test for Rowsecurity.


Question: PostgreSQL regression test 'gist': Write the SELECT query (example 27).

select p from gist_tbl where p <@ box(point(0,0), point(0.5, 0.5))
order by p <-> point(0.201, 0.201);

Explanation: Regression test for Gist in PostgreSQL core test suite.

SELECT count(*) FROM (select p from gist_tbl where p <@ box(point(0,0), point(0.5, 0.5))
order by p <-> point(0.201, 0.201)) AS _sub;


Question: Show a SQL definition from the timescaledb project (create_table_with, item 45).

CREATE TABLE IF NOT EXISTS t9(time timestamp NOT NULL, device text, value float) WITH (tsdb.columnstore=false,tsdb.hypertable,tsdb.partition_column='time',tsdb.chunk_interval='23 days');

Explanation: SQL definition from the open-source timescaledb PostgreSQL project.


Question: PostgreSQL regression test 'collate.icu.utf8': Write the SELECT query (example 102).

SELECT array_agg(b ORDER BY b) FROM collate_test2;

Explanation: Regression test for Collate.Icu.Utf8 in PostgreSQL core test suite.

SELECT count(*) FROM (SELECT array_agg(b ORDER BY b) FROM collate_test2) AS _sub;


Question: PostgreSQL regression test 'encoding': Write the SELECT query (example 18).

SELECT reverse(truncated) FROM regress_encoding;

Explanation: Regression test for Encoding in PostgreSQL core test suite.

SELECT count(*) FROM (SELECT reverse(truncated) FROM regress_encoding) AS _sub;


Question: Show a query using PostgreSQL contrib extension 'citext' (example 363).

SELECT regexp_replace('Thomas'::citext, '.[mN]a.',         'M') = 'ThM' AS t;

Explanation: Example query from the 'citext' extension test/demo.


Question: Show a query using PostgreSQL contrib extension 'unaccent' (example 10).

Explanation: Example query from the 'unaccent' extension test/demo.


Question: Write the DML statement from PostgreSQL regression test 'returning' (example 41).

update voo set f1 = f1 + 1 where f2 = 'zoo2';

Explanation: DML from PostgreSQL core regression test for Returning.


Question: Write the DML statement from PostgreSQL regression test 'identity' (example 30).

INSERT INTO itest5 OVERRIDING SYSTEM VALUE VALUES (DEFAULT, 'dd'), (-4, 'ee');

Explanation: DML from PostgreSQL core regression test for Identity.


Question: pgTAP test for Aretap (assertion 114).

SELECT * FROM check_test(
    opclasses_are( 'public', '{}'::name[], 'whatever' ),
    false,
    'opclasses_are(schema, opclasses, desc) + extra',
    'whatever',
    '    Extra operator classes:
        goofy_ops'
);

Explanation: SQL assertion from pgTAP test suite for Aretap.


Question: Show a query using PostgreSQL contrib extension 'cube' (example 17).

Explanation: Example query from the 'cube' extension test/demo.


Question: PostgreSQL regression test 'multirangetypes': Write the SELECT query (example 62).

SELECT count(*) FROM (select textrange('a', 'c')::textmultirange) AS _sub;


Question: pgTAP test for Resultset (assertion 135).

INSERT INTO names (name) VALUES ('Andrea');

Explanation: SQL assertion from pgTAP test suite for Resultset.


Question: pgTAP test for Pgtap--0.91.0--0.92.0 (assertion 105).

-- sequence_privs_are ( schema, sequence, user, privileges[] )
CREATE OR REPLACE FUNCTION sequence_privs_are ( NAME, NAME, NAME, NAME[] )
RETURNS TEXT AS $$
    SELECT sequence_privs_are(
        $1, $2, $3, $4,
        'Role ' || quote_ident($3) || ' should be granted '
            || CASE WHEN $4[1] IS NULL THEN 'no privileges' ELSE array_to_string($4, ', ') END
            || ' on sequence '|| quote_ident($1) || '.' || quote_ident($2)
    );
$$ LANGUAGE SQL;

Explanation: SQL assertion from pgTAP test suite for Pgtap--0.91.0--0.92.0.


Question: pgTAP test for Functap (assertion 96).

SELECT * FROM check_test(
    function_returns( 'oww', ARRAY['int', 'text'], 'boolean' ),
    true,
    'function_returns(func, args, bool)',
    'Function oww(int, text) should return boolean',
    ''
);

Explanation: SQL assertion from pgTAP test suite for Functap.


Question: PostgreSQL regression test 'object_address': Write the SELECT query (example 44).

SELECT pg_get_object_address('language', '{one,two}', '{}');

Explanation: Regression test for Object Address in PostgreSQL core test suite.

SELECT count(*) FROM (SELECT pg_get_object_address('language', '{one,two}', '{}')) AS _sub;


Question: PostgreSQL regression test 'int2': Write the SELECT query (example 73).

Explanation: Regression test for Int2 in PostgreSQL core test suite.

SELECT count(*) FROM (SELECT int2 '0b_10_0101') AS _sub;


Question: Show a SQL definition from the pglogical project (pglogical--1.0.0, item 9).

CREATE FUNCTION pglogical.create_subscription(subscription_name name, provider_dsn text,
    replication_sets text[] = '{default,default_insert_only}', synchronize_structure boolean = true,
    synchronize_data boolean = true, forward_origins text[] = '{all}')
RETURNS oid STRICT VOLATILE LANGUAGE c AS 'MODULE_PATHNAME', 'pglogical_create_subscription';

Explanation: SQL definition from the open-source pglogical PostgreSQL project.


Question: PostgreSQL regression test 'select_distinct': Write the SELECT query (example 7).

SELECT count(*) FROM
  (SELECT DISTINCT two, four, two FROM tenk1) ss;

Explanation: Regression test for Select Distinct in PostgreSQL core test suite.

SELECT count(*) FROM (SELECT count(*) FROM
  (SELECT DISTINCT two, four, two FROM tenk1) ss) AS _sub;


Question: PostgreSQL regression test 'float8': Write the SELECT query (example 64).

SELECT power(float8 'NaN', float8 'NaN');

Explanation: Regression test for Float8 in PostgreSQL core test suite.

SELECT count(*) FROM (SELECT power(float8 'NaN', float8 'NaN')) AS _sub;


Question: PostgreSQL regression test 'jsonb': Write the SELECT query (example 490).

SELECT count(*) FROM testjsonb WHERE j @@ '$.array[*] == "foo"';

Explanation: Regression test for Jsonb in PostgreSQL core test suite.

SELECT count(*) FROM (SELECT count(*) FROM testjsonb WHERE j @@ '$.array[*] == "foo"') AS _sub;


Question: PostgreSQL regression test 'enum': Write the SELECT query (example 4).

Explanation: Regression test for Enum in PostgreSQL core test suite.

SELECT count(*) FROM (SELECT 'mauve'::rainbow) AS _sub;


Question: Show a query using PostgreSQL contrib extension 'btree_gist' (example 18).

Explanation: Example query from the 'btree_gist' extension test/demo.


Question: Show a SQL definition from the timescaledb project (create_table_with, item 13).

CREATE TABLE t2(time timestamptz, device text, value float) WITH (tsdb.create_default_indexes='time');

Explanation: SQL definition from the open-source timescaledb PostgreSQL project.


Question: Show an example of PostgreSQL ALTER AGGREGATE (example 3).

ALTER AGGREGATE mypercentile(float8 ORDER BY integer) SET SCHEMA myschema;

Explanation: PostgreSQL ALTER AGGREGATE command.


Question: Write the SQL definition from PostgreSQL contrib extension 'contrib' (item 131).

CREATE FUNCTION isnle(ismn13, ean13)
	RETURNS boolean
	AS 'int8le'
	LANGUAGE 'internal'
	IMMUTABLE STRICT
	PARALLEL SAFE;

Explanation: SQL definition from the 'contrib' PostgreSQL contrib extension.


Question: pgTAP test for Policy (assertion 49).

SELECT * FROM check_test(
    policy_cmd_is( 'passwd', 'daemon_insert', 'insert', 'whatever' ),
    true,
    'policy_cmd_is(table, policy, command, desc) for INSERT',
    'whatever',
    ''
);

Explanation: SQL assertion from pgTAP test suite for Policy.


Question: PostgreSQL regression test 'join': Write the SELECT query (example 257).

select * from tt5,tt6 where tt5.f1 = tt6.f1 and tt5.f1 = tt5.f2 - tt6.f2;

Explanation: Regression test for Join in PostgreSQL core test suite.

SELECT count(*) FROM (select * from tt5,tt6 where tt5.f1 = tt6.f1 and tt5.f1 = tt5.f2 - tt6.f2) AS _sub;


Question: Show a query using PostgreSQL contrib extension 'pgstattuple' (example 15).

Explanation: Example query from the 'pgstattuple' extension test/demo.


Question: PostgreSQL regression test 'jsonb_jsonpath': Write the SELECT query (example 746).

Explanation: Regression test for Jsonb Jsonpath in PostgreSQL core test suite.


Question: PL/pgSQL test: Pltcl Trigger (example 20).

--
-- Trigger function to force references from T_dta2 follow changes
-- in T_pkey2 or be deleted too. This must be done AFTER the changes
-- in T_pkey2 are done so the trigger for primkey check on T_dta2
-- fired on our updates will see the new key values in T_pkey2.
--
create function trig_pkey2_after() returns trigger as E'
    #
    # Prepare plans on first call
    #
    if {![info exists GD]} {
	#
	# Plan to update references from T_dta2
	#
        set GD(plan_dta2_upd) [spi_prepare			\\
	    "update T_dta2 set ref1 = \\$3, ref2 = \\$4		\\
	        where ref1 = \\$1 and ref2 = \\$2"		\\
	    {int4 bpchar int4 bpchar}]
	#
	# Plan to delete references from T_dta2
	#
        set GD(plan_dta2_del) [spi_prepare			\\
	    "delete from T_dta2 				\\
	        where ref1 = \\$1 and ref2 = \\$2"		\\
	    {int4 bpchar}]
    }

    #
    # Initialize flags
    #
    set old_ref_follow 0
    set old_ref_delete 0

    switch $TG_op {
	UPDATE {
	    #
	    # On update we must let old references follow
	    #
	    set NEW(key2) [string toupper $NEW(key2)]

	    if {[string compare $NEW(key1) $OLD(key1)] != 0} {
	        set old_ref_follow 1
	    }
	    if {[string compare $NEW(key2) $OLD(key2)] != 0} {
	        set old_ref_follow 1
	    }
	}
	DELETE {
	    #
	    # On delete we must delete references too
	    #
	    set old_ref_delete 1
	}
    }

    if {$old_ref_follow} {
	#
	# Let old references follow and fire NOTICE message if
	# there where some
	#
        set n [spi_execp $GD(plan_dta2_upd) \\
	    [list $OLD(key1) $OLD(key2) $NEW(key1) $NEW(key2)]]
	if {$n > 0} {
	    elog NOTICE \\
		"updated $n entries in T_dta2 for new key in T_pkey2"
        }
    }

    if {$old_ref_delete} {
	#
	# delete references and fire NOTICE message if
	# there where some
	#
        set n [spi_execp $GD(plan_dta2_del) \\
	    [list $OLD(key1) $OLD(key2)]]
	if {$n > 0} {
	    elog NOTICE \\
		"deleted $n entries from T_dta2"
        }
    }

    return OK
' language pltcl;

Explanation: PL/pgSQL example from PostgreSQL source test for Pltcl Trigger.


Question: PostgreSQL regression test 'largeobject': Write the SELECT query (example 53).

SELECT lo_truncate64(fd, 5000000000) FROM lotest_stash_values;

Explanation: Regression test for Largeobject in PostgreSQL core test suite.

SELECT count(*) FROM (SELECT lo_truncate64(fd, 5000000000) FROM lotest_stash_values) AS _sub;


Question: Write the DML statement from PostgreSQL regression test 'without_overlaps' (example 616).

INSERT INTO temporal_partitioned_fk_mltrng2mltrng (id, valid_at, parent_id) VALUES
  ('[3,4)', datemultirange(daterange('2000-01-01', '2000-02-15')), '[3,4)');

Explanation: DML from PostgreSQL core regression test for Without Overlaps.


Question: PostgreSQL regression test 'rowtypes': Write the SELECT query (example 165).

Explanation: Regression test for Rowtypes in PostgreSQL core test suite.

SELECT count(*) FROM (select fullname::text from fullname) AS _sub;


Question: PostgreSQL Ddl: show example 50.

ALTER TABLE products ADD CHECK (name <> ''); ALTER TABLE products ADD CONSTRAINT some_name UNIQUE (product_no); ALTER TABLE products ADD FOREIGN KEY (product_group_id) REFERENCES product_groups;

Explanation: Example from PostgreSQL documentation on Ddl.


Question: PostgreSQL regression test 'object_address': Write the SELECT query (example 61).

SELECT pg_get_object_address('extension', '{one,two}', '{}');

Explanation: Regression test for Object Address in PostgreSQL core test suite.

SELECT count(*) FROM (SELECT pg_get_object_address('extension', '{one,two}', '{}')) AS _sub;


Question: Write the DML statement from PostgreSQL regression test 'rules' (example 345).

Explanation: DML from PostgreSQL core regression test for Rules.


Question: PostgreSQL regression test 'numeric': Write the SELECT query (example 968).

Explanation: Regression test for Numeric in PostgreSQL core test suite.

SELECT count(*) FROM (select scale(1.12345)) AS _sub;


Question: pgTAP test for Functap (assertion 242).

-- is_aggregate( NAME, NAME[] )
-- isnt_aggregate( NAME, NAME[] )
SELECT * FROM check_test(
    is_aggregate( 'tap_accum', ARRAY[etype()] ),
    true,
    'is_aggregate(agg, arg)',
    'Function tap_accum(' || etype() || ') should be an aggregate function',
    ''
);

Explanation: SQL assertion from pgTAP test suite for Functap.


Question: PostgreSQL Queries: show example 15.

SELECT * FROM foo, LATERAL (SELECT * FROM bar WHERE bar.id = foo.bar_id) ss;

Explanation: Example from PostgreSQL documentation on Queries.


Question: Show a SQL definition from the citus project (multi_behavioral_analytics_create_table, item 44).

CREATE INDEX is_index4 ON events_table(event_type);

Explanation: SQL definition from the open-source citus PostgreSQL project.


Question: pgTAP test for Pgtap--Unpackaged--0.91.0 (assertion 449).

ALTER EXTENSION pgtap ADD FUNCTION language_is_trusted( NAME );

Explanation: SQL assertion from pgTAP test suite for Pgtap--Unpackaged--0.91.0.


Question: PostgreSQL regression test 'xml': Write the SELECT query (example 267).

Explanation: Regression test for Xml in PostgreSQL core test suite.

SELECT count(*) FROM (SELECT xmltext('foo `$_-+?=*^%!|/\()[]{}')) AS _sub;


Question: Write the SQL definition from PostgreSQL contrib extension 'contrib' (item 163).

CREATE FUNCTION gbt_cash_sortsupport(internal)
RETURNS void
AS 'MODULE_PATHNAME'
LANGUAGE C IMMUTABLE STRICT PARALLEL SAFE;

Explanation: SQL definition from the 'contrib' PostgreSQL contrib extension.


Question: PostgreSQL regression test 'constraints': Write the SELECT query (example 113).

Explanation: Regression test for Constraints in PostgreSQL core test suite.

SELECT count(*) FROM (SELECT * FROM COPY_TBL) AS _sub;


Question: Show a query using PostgreSQL contrib extension 'btree_gin' (example 18).

SELECT * FROM test_date WHERE i<='2004-10-26'::timestamptz ORDER BY i;

Explanation: Example query from the 'btree_gin' extension test/demo.


Question: Show a query using PostgreSQL contrib extension 'postgres_fdw' (example 1042).

SELECT t1.a,t2.b,t2.c FROM fprt1 t1 LEFT JOIN (SELECT * FROM fprt2 WHERE a < 10) t2 ON (t1.a = t2.b and t1.b = t2.a) WHERE t1.a < 10 ORDER BY 1,2,3;

Explanation: Example query from the 'postgres_fdw' extension test/demo.


Question: Write the DML statement from PostgreSQL regression test 'time' (example 5).

INSERT INTO TIME_TBL VALUES ('11:59 EDT');

Explanation: DML from PostgreSQL core regression test for Time.