Question: Write the DDL statement from PostgreSQL regression test 'update' (example 214).

CREATE TABLE list_parted (
	a text,
	b int
) PARTITION BY list (a);

Explanation: DDL from PostgreSQL core regression test for Update.


Question: pgTAP test for Hastap (assertion 40).

SELECT * FROM check_test(
    hasnt_table( '__SDFSDFD__', 'lol'::name ),
    true,
    'hasnt_table(non-existent schema, tab)',
    'Table "__SDFSDFD__".lol should not exist',
    ''
);

Explanation: SQL assertion from pgTAP test suite for Hastap.


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

SELECT COUNT(id) FROM xmltest, query WHERE xmlexists(expr PASSING BY REF data);

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

SELECT count(*) FROM (SELECT COUNT(id) FROM xmltest, query WHERE xmlexists(expr PASSING BY REF data)) AS _sub;


Question: PostgreSQL regression test 'float4': Write the SELECT query (example 35).

SELECT '          -INFINiTY   '::float4;

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

SELECT count(*) FROM (SELECT '          -INFINiTY   '::float4) AS _sub;


Question: Write the DML statement from PostgreSQL regression test 'incremental_sort' (example 124).

insert into prt_tbl select i%200, i from generate_series(1,1000)i;

Explanation: DML from PostgreSQL core regression test for Incremental Sort.


Question: PostgreSQL regression test 'privileges': Write the SELECT query (example 152).

SELECT * FROM atest2 WHERE ( col1 IN ( SELECT b FROM atest1 ) );

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

SELECT count(*) FROM (SELECT * FROM atest2 WHERE ( col1 IN ( SELECT b FROM atest1 ) )) AS _sub;


Question: PL/pgSQL test: Plpgsql Domain (example 31).

SELECT * FROM test_argresult_array_domain(ARRAY[0, 100]::ordered_pair_domain);

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


Question: PostgreSQL regression test 'foreign_key': Write the SELECT query (example 505).

select conname from pg_constraint where conrelid = 'fktable2'::regclass order by conname;

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

SELECT count(*) FROM (select conname from pg_constraint where conrelid = 'fktable2'::regclass order by conname) AS _sub;


Question: PL/pgSQL test: Pltcl Setup (example 4).

create function tcl_argisnull(text) returns bool as '
    argisnull 1
' language pltcl;

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


Question: Write the DML statement from PostgreSQL regression test 'sequence' (example 38).

INSERT INTO serialTest2 (f1, f6)
  VALUES ('bogus', -9223372036854775809);

Explanation: DML from PostgreSQL core regression test for Sequence.


Question: pgTAP test for Resultset (assertion 93).

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

Explanation: SQL assertion from pgTAP test suite for Resultset.


Question: PostgreSQL regression test 'horology': Write the SELECT query (example 364).

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

SELECT count(*) FROM (SELECT to_date('-100000000', 'CC')) AS _sub;


Question: Write the DDL statement from PostgreSQL regression test 'sequence' (example 4).

CREATE SEQUENCE sequence_testx INCREMENT BY -1 START 10;

Explanation: DDL from PostgreSQL core regression test for Sequence.


Question: Write the DML statement from PostgreSQL regression test 'create_misc' (example 19).

INSERT INTO d_star (class, a, b, c)
   VALUES ('d', 8, 'stumble'::text, 'hi koko'::name);

Explanation: DML from PostgreSQL core regression test for Create Misc.


Question: PostgreSQL regression test 'errors': Write the SELECT query (example 10).

select null from pg_database group by grouping sets (()) for update;

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

SELECT count(*) FROM (select null from pg_database group by grouping sets (()) for update) AS _sub;


Question: pgTAP test for Aretap (assertion 108).

SELECT * FROM check_test(
    languages_are( array_append(___mylangs(''), 'plomgwtf'), 'whatever' ),
    false,
    'languages_are(languages, desc) missing',
    'whatever',
    '    Missing languages:
        plomgwtf'
);

Explanation: SQL assertion from pgTAP test suite for Aretap.


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

create function simple1.simpletarget(int) returns int language plpgsql
as $$begin return $1; end$$;

create function simpletarget(int) returns int language plpgsql
as $$begin return $1 + 100; end$$;

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


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

SELECT attname, most_common_vals FROM pg_stats
  WHERE tablename = 'current_check'
  ORDER BY 1;

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

SELECT count(*) FROM (SELECT attname, most_common_vals FROM pg_stats
  WHERE tablename = 'current_check'
  ORDER BY 1) AS _sub;


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

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

SELECT count(*) FROM (select array_fill('juhu'::text, array[3,3])) AS _sub;


Question: Write the DML statement from PostgreSQL regression test 'timestamptz' (example 38).

INSERT INTO TIMESTAMPTZ_TBL VALUES ('1997-02-10 17:32:01-08');

Explanation: DML from PostgreSQL core regression test for Timestamptz.


Question: Show a query using PostgreSQL contrib extension 'ltree' (example 195).

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


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

begin
	new.description = 'updated in trigger';

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


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

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


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

SELECT JSON_QUERY(jsonb 'null', '$ts' PASSING timestamptz '2018-02-21 12:34:56 +10' AS ts RETURNING json);

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

SELECT count(*) FROM (SELECT JSON_QUERY(jsonb 'null', '$ts' PASSING timestamptz '2018-02-21 12:34:56 +10' AS ts RETURNING json)) AS _sub;


Question: pgTAP test for Functap (assertion 275).

SELECT * FROM check_test(
    isnt_window( 'pg_catalog', 'dense_rank', '{}'::name[] ),
    false,
    'isnt_window(schema, win, noargs)',
    'Function pg_catalog.dense_rank() should not be a window function',
    ''
);

Explanation: SQL assertion from pgTAP test suite for Functap.


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

CREATE TABLE parted_uniq_tbl_2 PARTITION OF parted_uniq_tbl FOR VALUES FROM (20) TO (30);

Explanation: DDL from PostgreSQL core regression test for Constraints.


Question: pgTAP test for Aretap (assertion 122).

SELECT * FROM check_test(
    rules_are( 'public', 'fou', ARRAY['ins_me', 'upd_me'] ),
    true,
    'rules_are(schema, table, rules)',
    'Relation public.fou should have the correct rules',
    ''
);


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

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


Question: PostgreSQL regression test 'subselect': Write the SELECT query (example 9).

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

SELECT count(*) FROM (SELECT ((SELECT 2) UNION SELECT 2)) AS _sub;


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

-- Create the operator class
CREATE OPERATOR CLASS gist_time_ops
DEFAULT FOR TYPE time USING gist
AS
	OPERATOR	1	<  ,
	OPERATOR	2	<= ,
	OPERATOR	3	=  ,
	OPERATOR	4	>= ,
	OPERATOR	5	>  ,
	OPERATOR	6	<> ,
	OPERATOR	15	<-> FOR ORDER BY pg_catalog.interval_ops ,
	FUNCTION	1	gbt_time_consistent (internal, time, int2, oid, internal),
	FUNCTION	2	gbt_time_union (internal, internal),
	FUNCTION	3	gbt_time_compress (internal),
	FUNCTION	4	gbt_decompress (internal),
	FUNCTION	5	gbt_time_penalty (internal, internal, internal),
	FUNCTION	6	gbt_time_picksplit (internal, internal),
	FUNCTION	7	gbt_time_same (gbtreekey16, gbtreekey16, internal),
	FUNCTION	8	gbt_time_distance (internal, time, int2, oid, internal),
	FUNCTION	9	gbt_time_fetch (internal),
	FUNCTION	11	gbt_time_sortsupport (internal),
	FUNCTION	12 ("any", "any") gist_translate_cmptype_btree (int),
	STORAGE		gbtreekey16;

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


Question: Write the DDL statement from PostgreSQL regression test 'without_overlaps' (example 392).

CREATE TABLE temporal_rng2 (
  id1 int4range,
  id2 int4range,
  valid_at daterange,
  CONSTRAINT temporal_rng2_pk PRIMARY KEY (id1, id2, valid_at WITHOUT OVERLAPS)
);

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


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

SELECT ts_rank_cd(' a:1 s:2B d g'::tsvector, 'a & s');

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

SELECT count(*) FROM (SELECT ts_rank_cd(' a:1 s:2B d g'::tsvector, 'a & s')) AS _sub;


Question: PostgreSQL regression test 'stats': Write the SELECT query (example 248).

SELECT wal_bytes > :wal_bytes_before FROM pg_stat_wal;

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

SELECT count(*) FROM (SELECT wal_bytes > :wal_bytes_before FROM pg_stat_wal) AS _sub;


Question: PostgreSQL regression test 'polymorphism': Write the SELECT query (example 204).

select formarray(1.1, variadic array[1.2,55.5]);

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

SELECT count(*) FROM (select formarray(1.1, variadic array[1.2,55.5])) AS _sub;


Question: Write the DDL statement from PostgreSQL regression test 'indexing' (example 459).

create table pk51 partition of pk5 for values from (4000) to (4500);

Explanation: DDL from PostgreSQL core regression test for Indexing.


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

DROP FUNCTION IF EXISTS test_function_exists(int, text, int[]);

Explanation: PL/pgSQL object from PostgreSQL core test for Drop If Exists.


Question: pgTAP test for Ownership (assertion 59).

SELECT * FROM check_test(
    view_owner_is('public', '__not__someview', current_user, 'mumble'),
	false,
    'view_owner_is(sch, non-view, user)',
    'mumble',
    '    View public.__not__someview does not exist'
);

Explanation: SQL assertion from pgTAP test suite for Ownership.


Question: Show a SQL definition from the zombodb project (_mappings, item 6).

CREATE TABLE zdb.type_mappings
(
    type_name  regtype               NOT NULL PRIMARY KEY,
    definition jsonb   DEFAULT NULL,
    is_default boolean DEFAULT false NOT NULL,
    funcid     regproc DEFAULT null
);

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


Question: PostgreSQL regression test 'truncate': Write the SELECT query (example 151).

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

SELECT count(*) FROM (select tp_ins_data()) AS _sub;


Question: Write the DML statement from PostgreSQL regression test 'numeric' (example 204).

INSERT INTO num_exp_add VALUES (4,8,'7874342.4119');

Explanation: DML from PostgreSQL core regression test for Numeric.


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

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


Question: pgTAP test for Hastap (assertion 207).

SELECT * FROM check_test(
  has_leftop( '+', 'text', 'inte', 'desc' ),
  false,
  'has_leftop( name, right, result, desc ) fail',
  'desc',
  ''
);

Explanation: SQL assertion from pgTAP test suite for Hastap.


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

SELECT setweight('a:1,3A asd:1C w:5,6,12B,13A zxc:81,222A,567'::tsvector, 'c');

SELECT count(*) FROM (SELECT setweight('a:1,3A asd:1C w:5,6,12B,13A zxc:81,222A,567'::tsvector, 'c')) AS _sub;


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

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: Write the DDL statement from PostgreSQL regression test 'partition_merge' (example 118).

CREATE TABLE sales_apr2022_10_20 PARTITION OF sales_apr2022 FOR VALUES FROM ('2022-04-10') TO ('2022-04-20');

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


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

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


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

/* contrib/btree_gin/btree_gin--1.0.sql */

-- complain if script is sourced in psql, rather than via CREATE EXTENSION
\echo Use "CREATE EXTENSION btree_gin" to load this file. \quit

CREATE FUNCTION gin_btree_consistent(internal, int2, anyelement, int4, internal, internal)
RETURNS bool
AS 'MODULE_PATHNAME'
LANGUAGE C STRICT IMMUTABLE;


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

ALTER EXTENSION pgtap ADD FUNCTION _ckeys ( NAME, CHAR );

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


Question: PostgreSQL regression test 'stats': Write the SELECT query (example 381).

SELECT sum(evictions) + sum(reuses) + sum(extends) + sum(fsyncs) + sum(reads) + sum(writes) + sum(writebacks) + sum(hits) AS my_io_stats_post_reset
  FROM pg_stat_get_backend_io(pg_backend_pid()) \gset
-- pg_stat_reset_shared() did not reset backend IO stats
SELECT :my_io_stats_pre_reset <= :my_io_stats_post_reset;

SELECT count(*) FROM (SELECT sum(evictions) + sum(reuses) + sum(extends) + sum(fsyncs) + sum(reads) + sum(writes) + sum(writebacks) + sum(hits) AS my_io_stats_post_reset
  FROM pg_stat_get_backend_io(pg_backend_pid()) \gset
-- pg_stat_reset_shared() did not reset backend IO stats
SELECT :my_io_stats_pre_reset <= :my_io_stats_post_reset) AS _sub;


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

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

SELECT count(*) FROM (SELECT (-12345678901234567)::money) AS _sub;


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

CREATE TABLE notnull_tbl4_cld () INHERITS (notnull_tbl4);

Explanation: DDL from PostgreSQL core regression test for Constraints.


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

SELECT * FROM pg_input_error_info('[{"attributes" : [2,3], "ndistinct" : 4, "ndistinct" : 4}]', 'pg_ndistinct');

Explanation: Regression test for Pg Ndistinct in PostgreSQL core test suite.

SELECT count(*) FROM (SELECT * FROM pg_input_error_info('[{"attributes" : [2,3], "ndistinct" : 4, "ndistinct" : 4}]', 'pg_ndistinct')) AS _sub;


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

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

SELECT count(*) FROM (select unnest('11 22 33'::oidvector)) AS _sub;


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

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


Question: PostgreSQL Plpgsql: show example 48.

DECLARE curs1 refcursor; curs2 CURSOR FOR SELECT * FROM tenk1; curs3 CURSOR (key integer) FOR SELECT * FROM tenk1 WHERE unique1 = key;

Explanation: Example from PostgreSQL documentation on Plpgsql.


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

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


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

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


Question: pgTAP test for Index (assertion 109).

SELECT * FROM check_test(
    is_indexed( 'public', 'sometab'::name, 'myint'::name ),
    false,
    'is_indexed( schema, table, column ) fail',
    'Should have an index on public.sometab(myint)',
    ''
);

Explanation: SQL assertion from pgTAP test suite for Index.


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

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

SELECT count(*) FROM (select jsonb_path_query('[]', '$.number()')) AS _sub;


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

/* contrib/ltree/ltree--1.1.sql */

-- complain if script is sourced in psql, rather than via CREATE EXTENSION
\echo Use "CREATE EXTENSION ltree" to load this file. \quit

CREATE FUNCTION ltree_in(cstring)
RETURNS ltree
AS 'MODULE_PATHNAME'
LANGUAGE C STRICT IMMUTABLE PARALLEL SAFE;

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


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

CREATE STATISTICS mcv_lists_stats_3 ON (mod(c,5)) FROM mcv_lists;

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


Question: Write the DML statement from PostgreSQL regression test 'numeric' (example 361).

INSERT INTO num_exp_sub VALUES (8,7,'83103366');

Explanation: DML from PostgreSQL core regression test for Numeric.


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

SELECT test_json ->> 'field4' FROM test_jsonb WHERE json_type = 'object';

SELECT count(*) FROM (SELECT test_json ->> 'field4' FROM test_jsonb WHERE json_type = 'object') AS _sub;


Question: Show a query using PostgreSQL contrib extension 'intarray' (example 66).


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

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


Question: PostgreSQL Ddl: show example 2.

CREATE TABLE products ( product_no integer, name text, price numeric );

Explanation: Example from PostgreSQL documentation on Ddl.


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

SELECT xmlroot(xml '<foo/>', version no value, standalone yes);

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

SELECT count(*) FROM (SELECT xmlroot(xml '<foo/>', version no value, standalone yes)) AS _sub;


Question: Write the DDL statement from PostgreSQL regression test 'psql' (example 214).

create table child_20_30 partition of parent_tab
  for values from (20) to (30);

Explanation: DDL from PostgreSQL core regression test for Psql.


Question: pgTAP test for Enumtap (assertion 31).

SELECT * FROM check_test(
    enums_are( 'public', ARRAY['freddy'], 'whatever' ),
    false,
    'enums_are(schema, enums, desc) fail',
    'whatever',
    '    Extra types:
        bug_status
    Missing types:
        freddy'
);

Explanation: SQL assertion from pgTAP test suite for Enumtap.


Question: Write the DDL statement from PostgreSQL regression test 'create_table' (example 139).

CREATE TABLE fail_part PARTITION OF hash_parted FOR VALUES WITH (MODULUS 150, REMAINDER 3);

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


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

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

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


Question: Write the DDL statement from PostgreSQL regression test 'brin_bloom' (example 62).

CREATE INDEX brin_summarize_bloom_idx ON brin_summarize_bloom USING brin (value) WITH (pages_per_range=2);

Explanation: DDL from PostgreSQL core regression test for Brin Bloom.


Question: Write the DDL statement from PostgreSQL regression test 'numeric_big' (example 16).

CREATE TABLE num_exp_sqrt (id int4, expected numeric(1000,800));

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


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

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


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

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


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

INSERT INTO gtest_varlena (a) VALUES('01234567890123456789');

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


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

SELECT interval '1 2:03:04.5678' hour to second(2);

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

SELECT count(*) FROM (SELECT interval '1 2:03:04.5678' hour to second(2)) AS _sub;


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

CREATE FUNCTION isngt(ismn13, ismn)
	RETURNS boolean
	AS 'int8gt'
	LANGUAGE 'internal'
	IMMUTABLE STRICT
	PARALLEL SAFE;


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

select sum(c) from gstest2
  group by grouping sets(grouping sets((a, (b))))
  order by 1 desc;

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

SELECT count(*) FROM (select sum(c) from gstest2
  group by grouping sets(grouping sets((a, (b))))
  order by 1 desc) AS _sub;


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

-- error functions
-- we run these with extra_float_digits = -1, to get consistently rounded
-- results on all platforms.
SET extra_float_digits = -1;

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


Question: PostgreSQL Textsearch: show example 40.

SELECT plainto_tsquery('english', 'The Fat Rats'); plainto_tsquery ----------------- 'fat' & 'rat';

Explanation: Example from PostgreSQL documentation on Textsearch.


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

SELECT jsonb_object_agg_unique_strict(i, null) OVER (ORDER BY i)
  FROM generate_series(1, 10) g(i);

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

SELECT count(*) FROM (SELECT jsonb_object_agg_unique_strict(i, null) OVER (ORDER BY i)
  FROM generate_series(1, 10) g(i)) AS _sub;


Question: PostgreSQL regression test 'float4': Write the SELECT query (example 84).

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

SELECT count(*) FROM (SELECT float4send('887745e-11'::float4)) AS _sub;


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

Explanation: DML from PostgreSQL core regression test for Float4.


Question: Show an example of PostgreSQL CREATE PUBLICATION (example 5).

CREATE PUBLICATION production_publication FOR TABLE users, departments, TABLES IN SCHEMA production;

Explanation: PostgreSQL CREATE PUBLICATION command.


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

INSERT INTO rls_test_src VALUES (1, 'src a');

Explanation: DML from PostgreSQL core regression test for Rowsecurity.


Question: pgTAP test for Pktap (assertion 33).

SELECT * FROM check_test(
    col_is_pk( 'argh', ARRAY['id', 'name'], 'id + name should be a pk' ),
    true,
    'col_is_pk( table, column[], description )',
    'id + name should be a pk',
    ''
);

Explanation: SQL assertion from pgTAP test suite for Pktap.


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


Question: Write the DDL statement from PostgreSQL regression test 'triggers' (example 158).

create function trigger_nothing() returns trigger
  language plpgsql as $$ begin end; $$;
create trigger failed instead of update on parted_trig
  for each row execute procedure trigger_nothing();
create trigger failed after update on parted_trig
  referencing old table as old_table
  for each row execute procedure trigger_nothing();
drop table parted_trig;

--
-- Verify trigger creation for partitioned tables, and drop behavior
--
create table trigpart (a int, b int) partition by range (a);
create table trigpart1 partition of trigpart for values from (0) to (1000);
create trigger trg1 after insert on trigpart for each row execute procedure trigger_nothing();
create table trigpart2 partition of trigpart for values from (1000) to (2000);
create table trigpart3 (like trigpart);
alter table trigpart attach partition trigpart3 for values from (2000) to (3000);
create table trigpart4 partition of trigpart for values from (3000) to (4000) partition by range (a);
create table trigpart41 partition of trigpart4 for values from (3000) to (3500);
create table trigpart42 (like trigpart);
alter table trigpart4 attach partition trigpart42 for values from (3500) to (4000);
select tgrelid::regclass, tgname, tgfoid::regproc from pg_trigger
  where tgrelid::regclass::text like 'trigpart%' order by tgrelid::regclass::text;
drop trigger trg1 on trigpart1;	-- fail
drop trigger trg1 on trigpart2;	-- fail
drop trigger trg1 on trigpart3;	-- fail
drop table trigpart2;			-- ok, trigger should be gone in that partition
select tgrelid::regclass, tgname, tgfoid::regproc from pg_trigger
  where tgrelid::regclass::text like 'trigpart%' order by tgrelid::regclass::text;
drop trigger trg1 on trigpart;		-- ok, all gone
select tgrelid::regclass, tgname, tgfoid::regproc from pg_trigger
  where tgrelid::regclass::text like 'trigpart%' order by tgrelid::regclass::text;

-- check detach behavior
create trigger trg1 after insert on trigpart for each row execute procedure trigger_nothing();
\d trigpart3
alter table trigpart detach partition trigpart3;
drop trigger trg1 on trigpart3; -- fail due to "does not exist"
alter table trigpart detach partition trigpart4;
drop trigger trg1 on trigpart41; -- fail due to "does not exist"
drop table trigpart4;
alter table trigpart attach partition trigpart3 for values from (2000) to (3000);
alter table trigpart detach partition trigpart3;
alter table trigpart attach partition trigpart3 for values from (2000) to (3000);
drop table trigpart3;

select tgrelid::regclass::text, tgname, tgfoid::regproc, tgenabled, tgisinternal from pg_trigger
  where tgname ~ '^trg1' order by 1;
create table trigpart3 (like trigpart);
create trigger trg1 after insert on trigpart3 for each row execute procedure trigger_nothing();
\d trigpart3
alter table trigpart attach partition trigpart3 FOR VALUES FROM (2000) to (3000); -- fail
drop table trigpart3;

-- check display of unrelated triggers
create trigger samename after delete on trigpart execute function trigger_nothing();
create trigger samename after delete on trigpart1 execute function trigger_nothing();
\d trigpart1

drop table trigpart;
drop function trigger_nothing();

--
-- Verify that triggers are fired for partitioned tables
--
create table parted_stmt_trig (a int) partition by list (a);
create table parted_stmt_trig1 partition of parted_stmt_trig for values in (1);
create table parted_stmt_trig2 partition of parted_stmt_trig for values in (2);

create table parted2_stmt_trig (a int) partition by list (a);
create table parted2_stmt_trig1 partition of parted2_stmt_trig for values in (1);
create table parted2_stmt_trig2 partition of parted2_stmt_trig for values in (2);

create or replace function trigger_notice() returns trigger as $$
  begin
    raise notice 'trigger % on % % % for %', TG_NAME, TG_TABLE_NAME, TG_WHEN, TG_OP, TG_LEVEL;

Explanation: DDL from PostgreSQL core regression test for Triggers.


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

INSERT INTO timetzcmp (r_id,a) SELECT  2,count(*) FROM timetztmp WHERE a <= '07:46:45 GMT+3';

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


Question: pgTAP test for Functap (assertion 107).

Explanation: SQL assertion from pgTAP test suite for Functap.


Question: PostgreSQL Textsearch: show example 7.

SELECT title FROM pgweb WHERE to_tsvector('english', body) @@ to_tsquery('english', 'friend');


Question: Write the DDL statement from PostgreSQL regression test 'foreign_data' (example 7).

Explanation: DDL from PostgreSQL core regression test for Foreign Data.


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

SELECT jsonb_build_array('a', NULL); -- ok
SELECT jsonb_build_array(VARIADIC NULL::text[]); -- ok
SELECT jsonb_build_array(VARIADIC '{}'::text[]); -- ok
SELECT jsonb_build_array(VARIADIC '{a,b,c}'::text[]); -- ok
SELECT jsonb_build_array(VARIADIC ARRAY['a', NULL]::text[]); -- ok
SELECT jsonb_build_array(VARIADIC '{1,2,3,4}'::text[]); -- ok
SELECT jsonb_build_array(VARIADIC '{1,2,3,4}'::int[]); -- ok
SELECT jsonb_build_array(VARIADIC '{{1,4},{2,5},{3,6}}'::int[][]); -- ok

SELECT jsonb_build_object('a',1,'b',1.2,'c',true,'d',null,'e',json '{"x": 3, "y": [1,2,3]}');

SELECT count(*) FROM (SELECT jsonb_build_array('a', NULL); -- ok
SELECT jsonb_build_array(VARIADIC NULL::text[]); -- ok
SELECT jsonb_build_array(VARIADIC '{}'::text[]); -- ok
SELECT jsonb_build_array(VARIADIC '{a,b,c}'::text[]); -- ok
SELECT jsonb_build_array(VARIADIC ARRAY['a', NULL]::text[]); -- ok
SELECT jsonb_build_array(VARIADIC '{1,2,3,4}'::text[]); -- ok
SELECT jsonb_build_array(VARIADIC '{1,2,3,4}'::int[]); -- ok
SELECT jsonb_build_array(VARIADIC '{{1,4},{2,5},{3,6}}'::int[][]); -- ok

SELECT jsonb_build_object('a',1,'b',1.2,'c',true,'d',null,'e',json '{"x": 3, "y": [1,2,3]}')) AS _sub;


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

INSERT INTO replication_example(somedata, text) VALUES (1, 5);

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


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

CREATE FUNCTION postgres_fdw_disconnect (text)
RETURNS bool
AS 'MODULE_PATHNAME'
LANGUAGE C STRICT PARALLEL RESTRICTED;

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


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

CREATE TABLE prt_p2 PARTITION OF prt FOR VALUES FROM (10) TO (20);

Explanation: DDL from PostgreSQL core regression test for Memoize.


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

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


Question: PL/pgSQL test: Plpython Types (example 42).

CREATE FUNCTION test_type_conversion_float8(x float8) RETURNS float8 AS $$
plpy.info(x, type(x))
return x
$$ LANGUAGE plpython3u;

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


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

CREATE FUNCTION spi_prepared_plan_test_nested(a text) RETURNS text
	AS
'if "myplan" not in SD:
	q = "SELECT spi_prepared_plan_test_one(''%s'') as count" % a
	SD["myplan"] = plpy.prepare(q)
try:
	rv = plpy.execute(SD["myplan"])
	if len(rv):
		return rv[0]["count"]
except Exception as ex:
	plpy.error(str(ex))
return None
'
	LANGUAGE plpython3u;

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


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

select * from jsonb_to_recordset('[{"a":1,"b":"foo","d":false},{"a":2,"b":"bar","c":true}]')
    as x(a int, b text, c boolean);

SELECT count(*) FROM (select * from jsonb_to_recordset('[{"a":1,"b":"foo","d":false},{"a":2,"b":"bar","c":true}]')
    as x(a int, b text, c boolean)) AS _sub;


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

SELECT regexp_substr('abcabcabc', 'a.c', 2);

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

SELECT count(*) FROM (SELECT regexp_substr('abcabcabc', 'a.c', 2)) AS _sub;


Question: PostgreSQL regression test 'rules': Write the SELECT query (example 317).

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

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


Question: Write the DDL statement from PostgreSQL regression test 'create_table' (example 100).

CREATE TABLE part_bogus_expr_fail PARTITION OF list_parted FOR VALUES IN ((1+1) collate "POSIX");

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


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

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

SELECT count(*) FROM (SELECT to_number('CLXC', 'RN')) AS _sub;


Question: PostgreSQL regression test 'subselect': Write the SELECT query (example 252).

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

SELECT count(*) FROM (select nextval('ts1')) AS _sub;


Question: Write the DML statement from PostgreSQL regression test 'numeric' (example 169).

Explanation: DML from PostgreSQL core regression test for Numeric.


Question: Write the DDL statement from PostgreSQL regression test 'indexing' (example 315).

create table idxpart (a int4range, b int4range) partition by range (a);

Explanation: DDL from PostgreSQL core regression test for Indexing.


Question: Write the DML statement from PostgreSQL regression test 'numeric' (example 192).

INSERT INTO num_exp_add VALUES (4,5,'7815858.450391');


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

SELECT xpath(NULL, NULL) IS NULL FROM xmltest;

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

SELECT count(*) FROM (SELECT xpath(NULL, NULL) IS NULL FROM xmltest) AS _sub;


Question: Write the DML statement from PostgreSQL regression test 'aggregates' (example 181).

insert into minmaxtest values(11), (12);

Explanation: DML from PostgreSQL core regression test for Aggregates.


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

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


Question: PostgreSQL Textsearch: show example 6.

SELECT phraseto_tsquery('cats ate rats'); phraseto_tsquery ------------------------------- 'cat' <-> 'ate' <-> 'rat' SELECT phraseto_tsquery('the cats ate the rats'); phraseto_tsquery ------------------------------- 'cat' <-> 'ate' <2> 'rat';

Explanation: Example from PostgreSQL documentation on Textsearch.


Question: pgTAP test for Aretap (assertion 11).

CREATE VIEW public.vou AS SELECT * FROM fou;

Explanation: SQL assertion from pgTAP test suite for Aretap.


Question: Write the DDL statement from PostgreSQL regression test 'indexing' (example 520).

create table parted_replica_tab_1 partition of parted_replica_tab
  for values from (1) to (10) partition by range (id);


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

INSERT INTO itestv11 VALUES (10, 'xyz');

Explanation: DML from PostgreSQL core regression test for Identity.


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

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


Question: Write the DDL statement from PostgreSQL regression test 'foreign_data' (example 20).

CREATE FOREIGN DATA WRAPPER foo OPTIONS (testing '1');

Explanation: DDL from PostgreSQL core regression test for Foreign Data.


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

SELECT COUNT(id) FROM xmltest WHERE xmlexists('/menu/beer' PASSING BY REF data BY REF);

SELECT count(*) FROM (SELECT COUNT(id) FROM xmltest WHERE xmlexists('/menu/beer' PASSING BY REF data BY REF)) AS _sub;


Question: PL/pgSQL test: Plpython Populate (example 9).

INSERT INTO entry (accession, txid) VALUES ('A00002', '1') ;

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


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

CREATE FUNCTION seg_lower(seg)
RETURNS float4
AS 'MODULE_PATHNAME'
LANGUAGE C STRICT IMMUTABLE PARALLEL SAFE;

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


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

ALTER EXTENSION pgtap ADD FUNCTION _definer ( NAME, NAME[] );

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


Question: PostgreSQL regression test 'stats_import': Write the SELECT query (example 232).

SELECT replace(e.n_distinct,   '}, ', E'},\n') AS n_distinct,
       replace(e.dependencies, '}, ', E'},\n') AS dependencies,
       replace(e.most_common_vals::text, '},', E'},\n ') AS mcvs,
       e.most_common_val_nulls,
       e.most_common_freqs, e.most_common_base_freqs
FROM pg_stats_ext AS e
WHERE e.statistics_schemaname = 'stats_import' AND
    e.statistics_name = 'test_mr_stat' AND
    e.inherited = false
\gx

-- Test the ability of pg_restore_extended_stats() to import all of the
-- statistic values from an extended statistic object that has been
-- populated via a regular ANALYZE.  This checks after the statistics
-- kinds supported by pg_restore_extended_stats().
--
-- Note: Keep this test at the bottom of the file, so as the amount of
-- statistics data handled is maximized.
ANALYZE stats_import.test;

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

SELECT count(*) FROM (SELECT replace(e.n_distinct,   '}, ', E'},\n') AS n_distinct,
       replace(e.dependencies, '}, ', E'},\n') AS dependencies,
       replace(e.most_common_vals::text, '},', E'},\n ') AS mcvs,
       e.most_common_val_nulls,
       e.most_common_freqs, e.most_common_base_freqs
FROM pg_stats_ext AS e
WHERE e.statistics_schemaname = 'stats_import' AND
    e.statistics_name = 'test_mr_stat' AND
    e.inherited = false
\gx

-- Test the ability of pg_restore_extended_stats() to import all of the
-- statistic values from an extended statistic object that has been
-- populated via a regular ANALYZE.  This checks after the statistics
-- kinds supported by pg_restore_extended_stats().
--
-- Note: Keep this test at the bottom of the file, so as the amount of
-- statistics data handled is maximized.
ANALYZE stats_import.test) AS _sub;


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

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


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

Explanation: DML from PostgreSQL core regression test for Vacuum.


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

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


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

insert into nulltest values ('a', 'b', 'c', 'd', 'a');

Explanation: DML from PostgreSQL core regression test for Domain.


Question: Write the DML statement from PostgreSQL regression test 'interval' (example 21).

INSERT INTO INTERVAL_TBL (f1) VALUES ('6 years');

Explanation: DML from PostgreSQL core regression test for Interval.


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

INSERT INTO temporal_rng3 (id, valid_at) VALUES ('[1,2)', daterange('2018-03-03', '2018-04-04'));

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


Question: Show a SQL definition from the zombodb project (zombodb--3000.2.4--3000.2.5, item 2).

CREATE FUNCTION zdb.schema_version() RETURNS text LANGUAGE sql AS $$
SELECT '3000.2.5 (4704c7982040b2dd33d97334d3d4743082549630)'
$$;

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


Question: PostgreSQL regression test 'window': Write the SELECT query (example 54).

SELECT sum(unique1) over (rows between 2 preceding and 2 following),
	unique1, four
FROM tenk1 WHERE unique1 < 10;

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

SELECT count(*) FROM (SELECT sum(unique1) over (rows between 2 preceding and 2 following),
	unique1, four
FROM tenk1 WHERE unique1 < 10) AS _sub;


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

insert into copytest values(E'esc\\ape',E'a\\r\\\r\\\n\\nb',4);

Explanation: DML from PostgreSQL core regression test for Copy.


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

SELECT * FROM bt_page_items(get_raw_page('test1_a_idx', 1));

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


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

-- create statistics on expressions
CREATE STATISTICS func_deps_stat (dependencies) ON (a * 2), upper(b), (c + 1) FROM functional_dependencies;

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


Question: PostgreSQL regression test 'horology': Write the SELECT query (example 24).

SELECT timestamp with time zone 'J2452271 04:05:06+08';

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

SELECT count(*) FROM (SELECT timestamp with time zone 'J2452271 04:05:06+08') AS _sub;


Question: pgTAP test for Pgtap--1.3.0--1.3.1 (assertion 14).

-- has_pk( schema, table )
CREATE OR REPLACE FUNCTION has_pk ( NAME, NAME )
RETURNS TEXT AS $$
    SELECT has_pk( $1, $2, 'Table ' || quote_ident($1) || '.' || quote_ident($2) || ' should have a primary key' );
$$ LANGUAGE sql;

Explanation: SQL assertion from pgTAP test suite for Pgtap--1.3.0--1.3.1.


Question: PostgreSQL regression test 'alter_table': Write the SELECT query (example 649).

SELECT coninhcount, conislocal FROM pg_constraint WHERE conrelid = 'part_3_4'::regclass AND conname = 'check_a';

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

SELECT count(*) FROM (SELECT coninhcount, conislocal FROM pg_constraint WHERE conrelid = 'part_3_4'::regclass AND conname = 'check_a') AS _sub;


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

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

SELECT count(*) FROM (SELECT * FROM INT8_TBL WHERE 123 > q1) AS _sub;


Question: Write the DDL statement from PostgreSQL regression test 'partition_prune' (example 46).

create table rlp5_default partition of rlp5 default;

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


Question: pgTAP test for Pgtap--1.3.0--1.3.1 (assertion 4).

-- col_type_is( schema, table, column, schema, type )
CREATE OR REPLACE FUNCTION col_type_is ( NAME, NAME, NAME, NAME, TEXT )
RETURNS TEXT AS $$
    SELECT col_type_is( $1, $2, $3, $4, $5, 'Column ' || quote_ident($1) || '.' || quote_ident($2)
        || '.' || quote_ident($3) || ' should be type ' || quote_ident($4) || '.' || $5);
$$ LANGUAGE SQL;


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

CREATE TYPE cube (
	INTERNALLENGTH = variable,
	INPUT = cube_in,
	OUTPUT = cube_out,
	ALIGNMENT = double
);

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


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

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


Question: PostgreSQL regression test 'with': Write the SELECT query (example 204).

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

SELECT count(*) FROM (SELECT * from id_alw1) AS _sub;


Question: Show a SQL definition from the timescaledb project (telemetry, item 5).

CREATE OR REPLACE FUNCTION _timescaledb_internal.test_telemetry_main_conn(text, text)
RETURNS BOOLEAN AS :MODULE_PATHNAME, 'ts_test_telemetry_main_conn' LANGUAGE C IMMUTABLE PARALLEL SAFE;

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


Question: pgTAP test for Pgtap--0.94.0--0.95.0 (assertion 22).

-- hasnt_materialized_view( materialized_view )
CREATE OR REPLACE FUNCTION hasnt_materialized_view ( NAME )
RETURNS TEXT AS $$
    SELECT hasnt_materialized_view( $1, 'Materialized view ' || quote_ident($1) || ' should not exist' );
$$ LANGUAGE SQL;

Explanation: SQL assertion from pgTAP test suite for Pgtap--0.94.0--0.95.0.


Question: Write the DDL statement from PostgreSQL regression test 'partition_join' (example 115).

CREATE TABLE prt2_m_p1 PARTITION OF prt2_m FOR VALUES FROM (0, 0) TO (250, 250);

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


Question: Show a SQL definition from the zombodb project (_postgis-support, item 4).

-- casting functions
    EXECUTE format('create or replace function zdb.geometry_to_json(%I.geometry, typmod integer DEFAULT -1) returns json parallel safe immutable strict language sql as $$
          SELECT CASE WHEN %I.postgis_typmod_type($2) = ''Point'' THEN
                    zdb.point_to_json(%I.st_transform($1, 4326)::point)::json
                 ELSE
                    %I.st_asgeojson(%I.st_transform($1, 4326))::json
                 END
          $$;',
      geojson_namespace, geojson_namespace, geojson_namespace, geojson_namespace, geojson_namespace);


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

CREATE FUNCTION gin_extract_query_char("char", internal, int2, internal, internal)
RETURNS internal
AS 'MODULE_PATHNAME'
LANGUAGE C STRICT IMMUTABLE;


Question: Show a query using PostgreSQL contrib extension 'earthdistance' (example 32).

SELECT cube_ll_coord(ll_to_earth(-90,180),1)::numeric(20,5),
 cube_ll_coord(ll_to_earth(-90,180),2)::numeric(20,5),
 cube_ll_coord(ll_to_earth(-90,180),3)::numeric(20,5);

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


Question: PostgreSQL regression test 'union': Write the SELECT query (example 24).

SELECT f1 AS three FROM VARCHAR_TBL
UNION
SELECT CAST(f1 AS varchar) FROM CHAR_TBL
ORDER BY 1;

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

SELECT count(*) FROM (SELECT f1 AS three FROM VARCHAR_TBL
UNION
SELECT CAST(f1 AS varchar) FROM CHAR_TBL
ORDER BY 1) AS _sub;


Question: Write the DML statement from PostgreSQL regression test 'timestamptz' (example 86).

INSERT INTO TIMESTAMPTZ_TBL VALUES ('Feb 11 17:32:01 1997');

Explanation: DML from PostgreSQL core regression test for Timestamptz.


Question: pgTAP test for Throwtap (assertion 1).

\unset ECHO
\i test/setup.sql

SELECT plan(97);

Explanation: SQL assertion from pgTAP test suite for Throwtap.


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

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


Question: Write the DDL statement from PostgreSQL regression test 'stats_import' (example 25).

CREATE INDEX part_parent_i ON stats_import.part_parent(i);

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


Question: Write the DDL statement from PostgreSQL regression test 'indexing' (example 251).

create index on idxpart2 (a) where b > 1000;

Explanation: DDL from PostgreSQL core regression test for Indexing.


Question: PostgreSQL regression test 'advisory_lock': Write the SELECT query (example 12).

SELECT
	pg_advisory_lock(1), pg_advisory_lock_shared(2),
	pg_advisory_lock(1, 1), pg_advisory_lock_shared(2, 2);

Explanation: Regression test for Advisory Lock in PostgreSQL core test suite.

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


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

-- Now the same test with plpgsql (since it depends on SPI which is different)
create or replace function max_xacttest() returns smallint language plpgsql as
'begin return max(a) from xacttest; end' stable;

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


Question: Show a SQL definition from the pgaudit project (pgaudit--18.0, item 1).

\echo Use "CREATE EXTENSION pgaudit" to load this file.\quit

CREATE FUNCTION pgaudit_ddl_command_end()
	RETURNS event_trigger
	SECURITY DEFINER
	SET search_path = pg_catalog, pg_temp
	LANGUAGE C
	AS 'MODULE_PATHNAME', 'pgaudit_ddl_command_end';

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


Question: Show an example of PostgreSQL INSERT (example 9).

WITH upd AS ( UPDATE employees SET sales_count = sales_count + 1 WHERE id = (SELECT sales_person FROM accounts WHERE name = 'Acme Corporation') RETURNING * ) INSERT INTO employees_log SELECT *, current_timestamp FROM upd;

Explanation: PostgreSQL INSERT command.


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

INSERT INTO spill_test SELECT 'serialize-subbig--1:'||g.i FROM generate_series(1, 5000) g(i);

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


Question: Write the DML statement from PostgreSQL regression test 'numeric' (example 220).

Explanation: DML from PostgreSQL core regression test for Numeric.


Question: PostgreSQL regression test 'text': Write the SELECT query (example 37).

select format('INSERT INTO %I VALUES(%L,%L)', 'mytab', NULL, 'Hello');

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

SELECT count(*) FROM (select format('INSERT INTO %I VALUES(%L,%L)', 'mytab', NULL, 'Hello')) AS _sub;


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

CREATE TEMP TABLE parted_b1 partition of parted_b for values from (0) to (10);

Explanation: DDL from PostgreSQL core regression test for Join.


Question: PostgreSQL regression test 'rangetypes': Write the SELECT query (example 13).

select ' ( " a " " a ", " z " " z " )  '::textrange;

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

SELECT count(*) FROM (select ' ( " a " " a ", " z " " z " )  '::textrange) AS _sub;


Question: PL/pgSQL test: Plpgsql Domain (example 23).

SELECT * FROM test_argresult_nnint(null, 20);

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


Question: pgTAP test for Coltap (assertion 90).

-- Make sure that it works when the default is a reserved SQL expression.
CREATE OR REPLACE FUNCTION ckreserve() RETURNS SETOF TEXT LANGUAGE PLPGSQL AS $$
DECLARE
    funcs text[] := '{CURRENT_CATALOG,CURRENT_ROLE,CURRENT_SCHEMA,CURRENT_USER,SESSION_USER,USER,CURRENT_DATE,CURRENT_TIME,CURRENT_TIMESTAMP,LOCALTIME,LOCALTIMESTAMP}';
    cols  TEXT[] := '{ccat,crole,csch,cuser,suser,auser,cdate,ctime,ctstz,ltime,ltstz}';
    exp   TEXT[] := funcs;
    tap           record;
    last_index    INTEGER;
BEGIN
    last_index := array_upper(funcs, 1);
    IF pg_version_num() < 100000 THEN
       -- Prior to PostgreSQL 10, these were functions rendered with paretheses or as casts.
       exp := ARRAY['current_database()','"current_user"()','"current_schema"()','"current_user"()','"session_user"()','"current_user"()','(''now''::text)::date','(''now''::text)::time with time zone','now()','(''now''::text)::time without time zone','(''now''::text)::timestamp without time zone'];
    END IF;

    FOR i IN 1..last_index LOOP
        FOR tap IN SELECT * FROM check_test(
            col_default_is( 'sometab', cols[i], exp[i], 'Test ' || funcs[i] ),
            true,
            'col_default_is( tab, col, ' || funcs[i] || ' )',
            'Test ' || funcs[i],
            ''
        ) AS b LOOP RETURN NEXT tap.b; END LOOP;
    END LOOP;
END;
$$;

Explanation: SQL assertion from pgTAP test suite for Coltap.


Question: PL/pgSQL test: Plpython Record (example 19).

SELECT * FROM test_table_record_as('list', 'one', null, false);

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


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

SELECT JSON_QUERY(jsonb '123', '$' RETURNING queryfuncs_char2_chk ERROR ON ERROR);

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

SELECT count(*) FROM (SELECT JSON_QUERY(jsonb '123', '$' RETURNING queryfuncs_char2_chk ERROR ON ERROR)) AS _sub;


Question: Write the DDL statement from PostgreSQL regression test 'partition_prune' (example 223).

create table rp2 partition of rp for values from (2) to (maxvalue);

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


Question: Write the DML statement from PostgreSQL regression test 'insert' (example 9).

insert into inserttest (col1, col2, col3) values (1, 2);

Explanation: DML from PostgreSQL core regression test for Insert.


Question: Show a SQL definition from the timescaledb project (compat, item 23).

CREATE OR REPLACE FUNCTION _timescaledb_internal.get_partition_hash(val anyelement) RETURNS integer LANGUAGE PLPGSQL AS $$
BEGIN
  IF current_setting('timescaledb.enable_deprecation_warnings', true)::bool THEN
    RAISE WARNING 'function _timescaledb_internal.get_partition_hash(anyelement) is deprecated and has been moved to _timescaledb_functions schema. this compatibility function will be removed in a future version.';
  END IF;
  RETURN _timescaledb_functions.get_partition_hash($1);
END$$
SET search_path TO pg_catalog,pg_temp;

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


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

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


Question: Show a query using PostgreSQL contrib extension 'ltree' (example 149).

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


Question: Write the DDL statement from PostgreSQL regression test 'create_view' (example 75).

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


Question: PostgreSQL regression test 'vacuum': Write the SELECT query (example 15).

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

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


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

CREATE TABLE part3 PARTITION OF pa_target FOR VALUES IN (3,8,9)
  WITH (autovacuum_enabled=off);

Explanation: DDL from PostgreSQL core regression test for Merge.


Question: pgTAP test for Index (assertion 16).

SELECT * FROM check_test(
    has_index( 'public', 'sometab', 'idx_hey', 'numb'::name ),
    true,
    'has_index() single column no desc',
    'Index idx_hey should exist',
    ''
);

Explanation: SQL assertion from pgTAP test suite for Index.


Question: PostgreSQL Rules: show example 51.

UPDATE shoelace_data SET sl_name = s.sl_name, sl_avail = s.sl_avail + shoelace_arrive.arr_quant, sl_color = s.sl_color, sl_len = s.sl_len, sl_unit = s.sl_unit FROM shoelace_arrive shoelace_arrive, shoelace_ok shoelace_ok, shoelace_ok old, shoelace_ok new, shoelace shoelace, shoelace old, shoelace new, shoelace_data shoelace_data, shoelace old, shoelace new, shoelace_data s, unit u WHERE s.sl_name = shoelace_arrive.arr_name AND shoelace_data.sl_name = s.sl_name;

Explanation: Example from PostgreSQL documentation on Rules.


Question: PostgreSQL regression test 'regproc': Write the SELECT query (example 108).

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

SELECT count(*) FROM (SELECT to_regnamespace('foo.bar')) AS _sub;


Question: Show a SQL definition from the pg_partman project (test-time-mixed-case, item 9).

CREATE TABLE "Partman_Test"."FK_Test_Reference" ("Col2" text unique not null);

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


Question: Write the DDL statement from PostgreSQL regression test 'create_am' (example 132).

CREATE FOREIGN DATA WRAPPER fdw_heap2 VALIDATOR postgresql_fdw_validator;

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


Question: Write the DDL statement from PostgreSQL regression test 'jsonb' (example 265).

CREATE DOMAIN jsb_int_not_null  AS int     NOT NULL;

Explanation: DDL from PostgreSQL core regression test for Jsonb.


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

CREATE TABLE shoelace_log (
        sl_name    char(10),      -- shoelace changed
        sl_avail   integer,       -- new available value
        log_who    name,          -- who did it
        log_when   timestamp      -- when
    );

Explanation: DDL from PostgreSQL core regression test for Rules.


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

CREATE OPERATOR ~ (
    PROCEDURE = texticregexeq,
    LEFTARG   = citext,
    RIGHTARG  = text,
    NEGATOR   = !~,
    RESTRICT  = icregexeqsel,
    JOIN      = icregexeqjoinsel
);

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


Question: Show a query using PostgreSQL contrib extension 'tablefunc' (example 73).

SELECT * FROM connectby('connectby_int', 'keyid', 'parent_keyid', '2', 0) AS t(keyid int, parent_keyid text, level int);

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


Question: pgTAP test for Index (assertion 77).


Question: Show a query using PostgreSQL contrib extension 'ltree' (example 30).


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

SELECT regexp_replace('Thomas'::citext, '.[MN]A.'::citext, 'M', 'c') = 'Thomas' AS t;

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


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

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

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


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

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 timescaledb project (compat, item 31).

CREATE OR REPLACE FUNCTION _timescaledb_internal.policy_retention_check(config jsonb) RETURNS void LANGUAGE PLPGSQL AS $$
BEGIN
  IF current_setting('timescaledb.enable_deprecation_warnings', true)::bool THEN
    RAISE WARNING 'function _timescaledb_internal.policy_retention_check(jsonb) is deprecated and has been moved to _timescaledb_functions schema. this compatibility function will be removed in a future version.';
  END IF;
  PERFORM _timescaledb_functions.policy_retention_check($1);
END$$
SET search_path TO pg_catalog,pg_temp;

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


Question: Write the DML statement from PostgreSQL regression test 'tuplesort' (example 4).

Explanation: DML from PostgreSQL core regression test for Tuplesort.


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

$$ language plpgsql;

select forc01();

select * from forc_test;

drop function forc01();

-- it's okay to re-use a cursor variable name, even when bound

do $$
declare cnt int := 0;

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


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

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

SELECT count(*) FROM (SELECT nextval('sequence_test'::text)) AS _sub;


Question: Write the DML statement from PostgreSQL regression test 'foreign_key' (example 869).

Explanation: DML from PostgreSQL core regression test for Foreign Key.


Question: PostgreSQL regression test 'portals': Write the SELECT query (example 161).

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

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


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

INSERT INTO rem1 values(2, 'insert') RETURNING f2;

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


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

CREATE POLICY p1 ON rls_tbl_force USING (c1 = 5) WITH CHECK (c1 < 5);

Explanation: DDL from PostgreSQL core regression test for Rowsecurity.


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

SELECT * FROM nummultirange_test WHERE nmr > '{}';

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

SELECT count(*) FROM (SELECT * FROM nummultirange_test WHERE nmr > '{}') AS _sub;


Question: Write the DDL statement from PostgreSQL regression test 'triggers' (example 183).

create trigger parted_trig_odd after insert on parted_irreg for each row
  when (bark(new.b) AND new.a % 2 = 1) execute procedure trigger_notice_ab();

Explanation: DDL from PostgreSQL core regression test for Triggers.


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

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

SELECT count(*) FROM (SELECT lgamma(float8 '1000')) AS _sub;


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

CREATE TABLE prt_p1 PARTITION OF prt FOR VALUES FROM (0) TO (10);

Explanation: DDL from PostgreSQL core regression test for Memoize.


Question: PostgreSQL regression test 'jsonpath': Write the SELECT query (example 33).

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

SELECT count(*) FROM (select '$.g ? (@ == 1)'::jsonpath) AS _sub;


Question: Write the DDL statement from PostgreSQL regression test 'partition_join' (example 160).

CREATE TABLE pht1_e_p2 PARTITION OF pht1_e FOR VALUES WITH (MODULUS 3, REMAINDER 1);

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


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

SELECT table_name, is_updatable, is_insertable_into,
       is_trigger_updatable, is_trigger_deletable,
       is_trigger_insertable_into
  FROM information_schema.views
 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_updatable, is_insertable_into,
       is_trigger_updatable, is_trigger_deletable,
       is_trigger_insertable_into
  FROM information_schema.views
 WHERE table_name LIKE 'rw_view%'
 ORDER BY table_name) AS _sub;


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

INSERT INTO spill_test SELECT 'serialize-subbig-subsmall--2:'||g.i FROM generate_series(5001, 5001) g(i);

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


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

INSERT INTO DEFAULTEXPR_TBL (i2) VALUES (-4);

Explanation: DML from PostgreSQL core regression test for Constraints.


Question: PostgreSQL Advanced: show example 2.

CREATE TABLE cities ( name varchar(80) PRIMARY KEY, location point ); CREATE TABLE weather ( city varchar(80) REFERENCES cities (name), temp_lo int, temp_hi int, prcp real, date date );

Explanation: Example from PostgreSQL documentation on Advanced.


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

SELECT 'tx logical msg' FROM pg_logical_emit_message(true, 'test', 'tx logical msg');


Question: pgTAP test for Coltap (assertion 33).

-- Try interval second.
SELECT * FROM check_test(
    col_type_is( 'public', 'sometab', 'isecd', 'pg_catalog', 'interval second(0)', 'isecd is interval second(0)' ),
    true,
    'col_type_is( sch, tab, intsec, sch, type, desc )',
    'isecd is interval second(0)',
    ''
);

Explanation: SQL assertion from pgTAP test suite for Coltap.


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

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


Question: pgTAP test for Pgtap--0.92.0--0.93.0 (assertion 29).

-- index_owner_is ( schema, table, index, user, description )
CREATE OR REPLACE FUNCTION index_owner_is ( NAME, NAME, NAME, NAME, TEXT )
RETURNS TEXT AS $$
DECLARE
    owner NAME := _get_index_owner($1, $2, $3);
BEGIN
    -- Make sure the index exists.
    IF owner IS NULL THEN
        RETURN ok(FALSE, $5) || E'\n' || diag(
            E'    Index ' || quote_ident($3) || ' ON '
            || quote_ident($1) || '.' || quote_ident($2) || ' not found'
        );
    END IF;

    RETURN is(owner, $4, $5);
END;
$$ LANGUAGE plpgsql;

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


Question: PostgreSQL regression test 'horology': Write the SELECT query (example 249).

SELECT to_timestamp('My birthday-> Year: 1976, Month: May, Day: 16',
                    '"My birthday-> Year:" YYYY, "Month:" FMMonth, "Day:" DD');

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

SELECT count(*) FROM (SELECT to_timestamp('My birthday-> Year: 1976, Month: May, Day: 16',
                    '"My birthday-> Year:" YYYY, "Month:" FMMonth, "Day:" DD')) AS _sub;


Question: Write the DDL statement from PostgreSQL regression test 'indexing' (example 327).

create table idxpart (a int4range, b int4range, c int4range) partition by range (a);

Explanation: DDL from PostgreSQL core regression test for Indexing.


Question: PostgreSQL regression test 'indirect_toast': Write the SELECT query (example 13).

SELECT substring(indtoasttest::text, 1, 200) FROM indtoasttest;

Explanation: Regression test for Indirect Toast in PostgreSQL core test suite.

SELECT count(*) FROM (SELECT substring(indtoasttest::text, 1, 200) FROM indtoasttest) AS _sub;


Question: PostgreSQL regression test 'boolean': Write the SELECT query (example 40).

SELECT '    true   '::text::boolean AS true,
       '     FALSE'::text::boolean AS false;

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

SELECT count(*) FROM (SELECT '    true   '::text::boolean AS true,
       '     FALSE'::text::boolean AS false) AS _sub;


Question: Write the DDL statement from PostgreSQL regression test 'partition_prune' (example 301).

create table ab_a3_b3 partition of ab_a3 for values in (3);

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


Question: Show a SQL definition from the pg_partman project (pg_partman--2.2.3--2.3.0, item 13).

/*
 * Apply foreign keys that exist on the given parent to the given child table
 */
CREATE OR REPLACE FUNCTION 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_old_search_path   text;
v_parent_schema     text;
v_parent_tablename  text;
v_ref_schema        text;
v_ref_table         text;
v_row               record;
v_schemaname        text;
v_sql               text;
v_step_id           bigint;
v_tablename         text;

BEGIN

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;
        EXECUTE format('SELECT set_config(%L, %L, %L)', 'search_path', '@extschema@,'||v_jobmon_schema, 'false');
    END IF;
END IF;

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;

SELECT schemaname, tablename INTO v_parent_schema, v_parent_tablename
FROM pg_catalog.pg_tables
WHERE schemaname = split_part(p_parent_table, '.', 1)
AND tablename = split_part(p_parent_table, '.', 2);

SELECT schemaname, tablename INTO v_schemaname, v_tablename
FROM pg_catalog.pg_tables
WHERE schemaname = split_part(p_child_table, '.', 1)
AND tablename = split_part(p_child_table, '.', 2);

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: pgTAP test for Hastap (assertion 153).

Explanation: SQL assertion from pgTAP test suite for Hastap.


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

SELECT * FROM INTERVAL_TBL
   WHERE INTERVAL_TBL.f1 >= interval '@ 1 month';

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

SELECT count(*) FROM (SELECT * FROM INTERVAL_TBL
   WHERE INTERVAL_TBL.f1 >= interval '@ 1 month') AS _sub;


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

CREATE INDEX ON test_jsonb_mutability (JSON_QUERY(js, '$[1, 0 to $.a ? (@.datetime() == $x)]' PASSING '12:34'::time AS x));

Explanation: DDL from PostgreSQL core regression test for Sqljson Queryfuncs.


Question: pgTAP test for Hastap (assertion 6).

CREATE TYPE public.sometype AS (
    id    INT,
    name  TEXT
);


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

-- directory path and dlsuffix are passed to us in environment variables
\getenv libdir PG_LIBDIR
\getenv dlsuffix PG_DLSUFFIX

\set regresslib :libdir '/regress' :dlsuffix

--
-- Test the "old style" approach of making the I/O functions first,
-- with no explicit shell type creation.
--
CREATE FUNCTION widget_in(cstring)
   RETURNS widget
   AS :'regresslib'
   LANGUAGE C STRICT IMMUTABLE;

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


Question: pgTAP test for Hastap (assertion 247).

SELECT * FROM check_test(
  hasnt_opclass( 'int4_ops', 'whatever' ),
  false,
  'hasnt_opclass( name, desc )',
  'whatever',
  ''
);


Question: Show a SQL definition from the timescaledb project (util_time, item 2).

-- Return the minimum for the type. For time types, it will be the
-- Unix timestamp in microseconds.
CREATE OR REPLACE FUNCTION _timescaledb_functions.get_internal_time_max(REGTYPE) RETURNS BIGINT
AS '@MODULE_PATHNAME@', 'ts_get_internal_time_max' LANGUAGE C IMMUTABLE STRICT PARALLEL SAFE;

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


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

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


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

CREATE VIEW mvtest_tvvmv AS SELECT * FROM mvtest_tvvm;

Explanation: DDL from PostgreSQL core regression test for Matview.


Question: Show a SQL definition from the pg_partman project (test-time-maintenance-order, item 7).

CREATE TABLE partman_test.time_taptest_table3
    (col1 int
        , col2 text default 'stuff'
        , col3 timestamptz NOT NULL DEFAULT now())
    PARTITION BY RANGE (col3);


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

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

SELECT count(*) FROM (select jsonb_path_query('"1.23aaa"', '$.integer()')) AS _sub;


Question: Write the DML statement from PostgreSQL regression test 'foreign_key' (example 130).

INSERT INTO PKTABLE VALUES (2, 4, 5, 'test4');

Explanation: DML from PostgreSQL core regression test for Foreign Key.


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

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

SELECT count(*) FROM (SELECT date '01 08 99') AS _sub;


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

INSERT INTO tru_ptable (SELECT x FROM generate_series(11,20) x);

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


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

SELECT relname, b.* FROM ONLY b, pg_class where b.tableoid = pg_class.oid;

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

SELECT count(*) FROM (SELECT relname, b.* FROM ONLY b, pg_class where b.tableoid = pg_class.oid) AS _sub;


Question: Write the DDL statement from PostgreSQL regression test 'copy2' (example 142).

CREATE FUNCTION truncate_in_subxact() RETURNS VOID AS
$$
BEGIN
	TRUNCATE vistest;
EXCEPTION
  WHEN OTHERS THEN
	INSERT INTO vistest VALUES ('subxact failure');
END;
$$ language plpgsql;

Explanation: DDL from PostgreSQL core regression test for Copy2.


Question: Write the DDL statement from PostgreSQL regression test 'polymorphism' (example 105).

CREATE AGGREGATE myaggn02b(*) (SFUNC = stfnp, STYPE = anyarray,
  INITCOND = '{}');

Explanation: DDL from PostgreSQL core regression test for Polymorphism.


Question: PL/pgSQL test: Plpython Void (example 2).

-- illegal: can't return non-None value in void-returning func
CREATE FUNCTION test_void_func2() RETURNS void AS $$
return 10
$$ LANGUAGE plpython3u;

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


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

SELECT '2011-03-27 02:59:59'::timestamp AT TIME ZONE 'MSK';

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

SELECT count(*) FROM (SELECT '2011-03-27 02:59:59'::timestamp AT TIME ZONE 'MSK') AS _sub;


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

UPDATE alter_table_under_transition_tables
  SET id = id;

Explanation: DML from PostgreSQL core regression test for Plpgsql.


Question: Show a SQL definition from the zombodb project (zombodb--3000.0.6--3000.0.7, item 2).

CREATE FUNCTION zdb.schema_version() RETURNS text LANGUAGE sql AS $$
SELECT '3000.0.7 (90d8c41590be5fb35c99f5da14c1b134b0c863b9)'
$$;

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


Question: Show a query using PostgreSQL contrib extension 'ltree' (example 130).

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


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

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


Question: pgTAP test for Resultset (assertion 199).

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

Explanation: SQL assertion from pgTAP test suite for Resultset.


Question: pgTAP test for Pgtap--0.94.0--0.95.0 (assertion 19).

-- has_materialized_view( materialized_view )
CREATE OR REPLACE FUNCTION has_materialized_view ( NAME )
RETURNS TEXT AS $$
    SELECT has_materialized_view( $1, 'Materialized view ' || quote_ident($1) || ' should exist' );
$$ LANGUAGE SQL;

Explanation: SQL assertion from pgTAP test suite for Pgtap--0.94.0--0.95.0.


Question: Write the DML statement from PostgreSQL regression test 'temp' (example 14).

Explanation: DML from PostgreSQL core regression test for Temp.


Question: PostgreSQL regression test 'float4': Write the SELECT query (example 30).

SELECT * FROM pg_input_error_info('1e400', 'float4');

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

SELECT count(*) FROM (SELECT * FROM pg_input_error_info('1e400', 'float4')) AS _sub;


Question: Write the DML statement from PostgreSQL regression test 'bit' (example 50).

INSERT INTO BIT_SHIFT_TABLE SELECT b>>4 FROM BIT_SHIFT_TABLE;

Explanation: DML from PostgreSQL core regression test for Bit.


Question: PL/pgSQL test: Plpython Types (example 96).

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


Question: PostgreSQL Xfunc: show example 32.

CREATE OR REPLACE FUNCTION retcomposite(IN integer, IN integer, OUT f1 integer, OUT f2 integer, OUT f3 integer) RETURNS SETOF record AS ' filename ', 'retcomposite' LANGUAGE C IMMUTABLE STRICT;

Explanation: Example from PostgreSQL documentation on Xfunc.


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

SELECT replace('abcdefabcdef', 'cd'::citext, 'XX') = 'abXXefabXXef' AS t;

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


Question: PostgreSQL regression test 'union': Write the SELECT query (example 22).

SELECT f1 AS five FROM FLOAT8_TBL
  WHERE f1 BETWEEN -1e6 AND 1e6
UNION
SELECT f1 FROM INT4_TBL
  WHERE f1 BETWEEN 0 AND 1000000
ORDER BY 1;

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

SELECT count(*) FROM (SELECT f1 AS five FROM FLOAT8_TBL
  WHERE f1 BETWEEN -1e6 AND 1e6
UNION
SELECT f1 FROM INT4_TBL
  WHERE f1 BETWEEN 0 AND 1000000
ORDER BY 1) AS _sub;


Question: Write the DML statement from PostgreSQL regression test 'timestamptz' (example 102).

INSERT INTO TIMESTAMPTZ_TBL VALUES ('Feb 29 17:32:01 1996');

Explanation: DML from PostgreSQL core regression test for Timestamptz.


Question: PostgreSQL regression test 'matview': Write the SELECT query (example 110).

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

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


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

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


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

CREATE FUNCTION gbt_date_distance(internal,date,int2,oid,internal)
RETURNS float8
AS 'MODULE_PATHNAME'
LANGUAGE C IMMUTABLE STRICT PARALLEL SAFE;

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


Question: pgTAP test for Resultset (assertion 447).

PREPARE annames_ord AS SELECT id, name FROM annames ORDER BY id;


Question: Write the DML statement from PostgreSQL regression test 'numeric' (example 793).

INSERT INTO num_input_test(n1) VALUES ('5 . 0');

Explanation: DML from PostgreSQL core regression test for Numeric.


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

INSERT INTO ataddindex(f1) VALUES ('foo'), ('a');

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


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

SELECT f1 AS open_path, polygon( pclose(f1)) AS polygon
   FROM PATH_TBL
   WHERE isopen(f1);

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

SELECT count(*) FROM (SELECT f1 AS open_path, polygon( pclose(f1)) AS polygon
   FROM PATH_TBL
   WHERE isopen(f1)) AS _sub;


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

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

SELECT count(*) FROM (select '$.boolean()'::jsonpath) AS _sub;


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

SELECT ts_delete('base:7 hidden:6 rebel:1 spaceship:2,33A,34B,35C,36D strike:3'::tsvector, ARRAY['spaceship','rebel']);

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

SELECT count(*) FROM (SELECT ts_delete('base:7 hidden:6 rebel:1 spaceship:2,33A,34B,35C,36D strike:3'::tsvector, ARRAY['spaceship','rebel'])) AS _sub;


Question: pgTAP test for Check (assertion 18).

Explanation: SQL assertion from pgTAP test suite for Check.


Question: PostgreSQL regression test 'regproc': Write the SELECT query (example 91).

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

SELECT count(*) FROM (SELECT to_regtype('int3')) AS _sub;


Question: Write the DDL statement from PostgreSQL regression test 'numeric_big' (example 19).

CREATE TABLE num_exp_power_10_ln (id int4, expected numeric(1000,800));

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


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

Explanation: DML from PostgreSQL core regression test for Uuid.


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

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


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

CREATE FUNCTION lt_q_regex(ltree,_lquery)
RETURNS bool
AS 'MODULE_PATHNAME'
LANGUAGE C STRICT IMMUTABLE PARALLEL SAFE;


Question: pgTAP test for Hastap (assertion 161).

SELECT * FROM check_test(
    hasnt_cast( 'integer', 'clue', 'desc' ),
    true,
    'hasnt_cast( src, targ, desc ) fail',
    'desc',
    ''
);

Explanation: SQL assertion from pgTAP test suite for Hastap.


Question: Show an example of PostgreSQL INSERT (example 3).

INSERT INTO films VALUES ('UA502', 'Bananas', 105, DEFAULT, 'Comedy', '82 minutes'); INSERT INTO films (code, title, did, date_prod, kind) VALUES ('T_601', 'Yojimbo', 106, DEFAULT, 'Drama');

Explanation: PostgreSQL INSERT command.


Question: pgTAP test for Pgtap--0.93.0--0.94.0 (assertion 3).

CREATE OR REPLACE FUNCTION _fprivs_are ( TEXT, NAME, NAME[], TEXT )
RETURNS TEXT AS $$
DECLARE
    grants TEXT[] := _get_func_privs($2, $1);
BEGIN
    IF grants[1] = 'undefined_function' THEN
        RETURN ok(FALSE, $4) || E'\n' || diag(
            '    Function ' || $1 || ' does not exist'
        );
    ELSIF grants[1] = 'undefined_role' THEN
        RETURN ok(FALSE, $4) || E'\n' || diag(
            '    Role ' || quote_ident($2) || ' does not exist'
        );
    END IF;
    RETURN _assets_are('privileges', grants, $3, $4);
END;
$$ LANGUAGE plpgsql;

Explanation: SQL assertion from pgTAP test suite for Pgtap--0.93.0--0.94.0.


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

CREATE PUBLICATION testpub_dups FOR TABLE testpub_rf_tbl1 WHERE (a = 1), testpub_rf_tbl1 WITH (publish = 'insert');

Explanation: DDL from PostgreSQL core regression test for Publication.


Question: PostgreSQL regression test 'stats': Write the SELECT query (example 301).

select a from stats_test_tab1 where a = 3;

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

SELECT count(*) FROM (select a from stats_test_tab1 where a = 3) AS _sub;


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

SELECT i AS interval, date_trunc('week', i)
    FROM INFINITE_INTERVAL_TBL
    WHERE NOT isfinite(i);

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

SELECT count(*) FROM (SELECT i AS interval, date_trunc('week', i)
    FROM INFINITE_INTERVAL_TBL
    WHERE NOT isfinite(i)) AS _sub;


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

SELECT ctid FROM tidrangescan WHERE '(1,7)' >= ctid AND ctid > '(1,4)';

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

SELECT count(*) FROM (SELECT ctid FROM tidrangescan WHERE '(1,7)' >= ctid AND ctid > '(1,4)') AS _sub;


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

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

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


Question: Show a SQL definition from the timescaledb project (create_hypertable, item 43).

-- Test add_dimension: can use interval types for TIMESTAMPTZ columns
CREATE TABLE dim_test_time(time TIMESTAMPTZ, time2 TIMESTAMPTZ, time3 BIGINT, temp float8, device int, location int);

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


Question: Write the DDL statement from PostgreSQL regression test 'triggers' (example 474).

create trigger iocdu_tt_parted_update_trig
  after update on iocdu_tt_parted referencing old table as old_table new table as new_table
  for each statement execute procedure dump_update();

Explanation: DDL from PostgreSQL core regression test for Triggers.


Question: PostgreSQL regression test 'collate': Write the SELECT query (example 59).

SELECT a, b FROM collate_test2 WHERE a < 4 INTERSECT SELECT a, b FROM collate_test2 WHERE a > 1 ORDER BY 2;

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

SELECT count(*) FROM (SELECT a, b FROM collate_test2 WHERE a < 4 INTERSECT SELECT a, b FROM collate_test2 WHERE a > 1 ORDER BY 2) AS _sub;


Question: PL/pgSQL test: Pltcl Subxact (example 10).

-- Test subtransaction rollback

CREATE FUNCTION subtransaction_ctx_test(what_error text = NULL) RETURNS void
AS $$
    spi_exec "INSERT INTO subtransaction_tbl VALUES (1)"
    subtransaction {
        spi_exec "INSERT INTO subtransaction_tbl VALUES (2)"
        if {$1 == "SPI"} {
            spi_exec "INSERT INTO subtransaction_tbl VALUES ('oops')"
        } elseif { $1 == "Tcl"} {
            elog ERROR "Tcl error"
        }
    }
$$ LANGUAGE pltcl;

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