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

SELECT * FROM pg_input_error_info('[{"attributes" : [1, {"a": 1}], "ndistinct" : 1}]', 'pg_ndistinct');

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

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


Question: Write the DDL statement from PostgreSQL regression test 'create_type' (example 65).

CREATE TYPE myvarchar (
    input = myvarcharin,
    output = myvarcharout,
    alignment = integer,
    storage = main
);

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


Question: Write the DML statement from PostgreSQL regression test 'collate.windows.win1252' (example 52).

Explanation: DML from PostgreSQL core regression test for Collate.Windows.Win1252.


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

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

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


Question: pgTAP test for Index (assertion 47).

Explanation: SQL assertion from pgTAP test suite for Index.


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

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


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

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

SELECT count(*) FROM (select '$ ? (@.a < -1)'::jsonpath) AS _sub;


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

create index parted_isvalid_idx on parted_isvalid_tab ((a/b));

Explanation: DDL from PostgreSQL core regression test for Indexing.


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

SELECT * FROM pg_input_error_info('1234', 'cidr');

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

SELECT count(*) FROM (SELECT * FROM pg_input_error_info('1234', 'cidr')) AS _sub;


Question: pgTAP test for Usergroup (assertion 34).

SELECT * FROM check_test(
    is_member_of('meanies', current_user ),
    true,
    'is_member_of(meanies, current_user)',
    'Should have members of role meanies',
    ''
);

Explanation: SQL assertion from pgTAP test suite for Usergroup.


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

$$ language plpgsql;

select stacked_diagnostics_test();

-- fail, cannot use stacked diagnostics statement outside handler
create or replace function stacked_diagnostics_test() returns void as $$
declare _detail text;

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


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

CREATE TYPE tablefunc_crosstab_4 AS
(
	row_name TEXT,
	category_1 TEXT,
	category_2 TEXT,
	category_3 TEXT,
	category_4 TEXT
);


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

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


Question: PostgreSQL regression test 'create_function_sql': Write the SELECT query (example 83).

SELECT double_append(array_append(ARRAY[q1], q2), q3)
  FROM (VALUES(1,2,3), (4,5,6)) v(q1,q2,q3);

Explanation: Regression test for Create Function Sql in PostgreSQL core test suite.

SELECT count(*) FROM (SELECT double_append(array_append(ARRAY[q1], q2), q3)
  FROM (VALUES(1,2,3), (4,5,6)) v(q1,q2,q3)) AS _sub;


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

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


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

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

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


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

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


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

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


Question: PostgreSQL Rules: show example 53.

INSERT INTO shoelace_log SELECT s.sl_name, s.sl_avail + shoelace_arrive.arr_quant, current_user, current_timestamp FROM shoelace_arrive shoelace_arrive, shoelace_data shoelace_data, shoelace_data s WHERE s.sl_name = shoelace_arrive.arr_name AND shoelace_data.sl_name = s.sl_name AND s.sl_avail + shoelace_arrive.arr_quant <> s.sl_avail; UPDATE shoelace_data SET sl_avail = shoelace_data.sl_avail + shoelace_arrive.arr_quant FROM shoelace_arrive shoelace_arrive, shoelace_data shoelace_data, shoelace_data s WHERE s.sl_name = shoelace_arrive.sl_name AND shoelace_data.sl_name = s.sl_name;

Explanation: Example from PostgreSQL documentation on Rules.


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

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

SELECT count(*) FROM (SELECT 'infinity'::float8) AS _sub;


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

UPDATE  temporal_mltrng3
SET     id = '[1,2)',
        valid_at = NULL
WHERE   id IS NULL AND valid_at @> '2020-06-01'::date;

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


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

SELECT * FROM nummultirange_test WHERE nmr > '{[-1000.0, -1000.0]}';

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

SELECT count(*) FROM (SELECT * FROM nummultirange_test WHERE nmr > '{[-1000.0, -1000.0]}') AS _sub;


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

CREATE FUNCTION regexp_split_to_array( citext, citext, text ) RETURNS TEXT[] AS $$
    SELECT pg_catalog.regexp_split_to_array( $1::pg_catalog.text, $2::pg_catalog.text, CASE WHEN pg_catalog.strpos($3, 'c') = 0 THEN  $3 || 'i' ELSE $3 END );
$$ LANGUAGE SQL IMMUTABLE STRICT PARALLEL SAFE;

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


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

select websearch_to_tsquery('simple', 'fat or(rat');

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

SELECT count(*) FROM (select websearch_to_tsquery('simple', 'fat or(rat')) AS _sub;


Question: Write the DML statement from PostgreSQL regression test 'test_setup' (example 26).

INSERT INTO VARCHAR_TBL (f1) VALUES
  ('a'),
  ('ab'),
  ('abcd'),
  ('abcd    ');

Explanation: DML from PostgreSQL core regression test for Test Setup.


Question: pgTAP test for Functap (assertion 76).

SELECT * FROM check_test(
    function_lang_is( 'yay', 'sql' ),
    true,
    'function_lang_is(func, sql)',
    'Function yay() should be written in sql',
    ''
);

Explanation: SQL assertion from pgTAP test suite for Functap.


Question: Write the DDL statement from PostgreSQL regression test 'select_parallel' (example 77).

create table bmscantest (a int, t text);

Explanation: DDL from PostgreSQL core regression test for Select Parallel.


Question: PostgreSQL Textsearch: show example 59.

SELECT alias, description, token FROM ts_debug('http://example.com/stuff/index.html'); alias | description | token ----------+---------------+------------------------------ protocol | Protocol head | http:// url | URL | example.com/stuff/index.html host | Host | example.com url_path | URL path | /stuff/index.html;

Explanation: Example from PostgreSQL documentation on Textsearch.


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

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


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

INSERT INTO itest2 OVERRIDING SYSTEM VALUE VALUES (20, 'xyz');

Explanation: DML from PostgreSQL core regression test for Identity.


Question: Show a SQL definition from the pg_partman project (test-time-daily, item 11).

CREATE TABLE partman_test.time_taptest_table
    (col1 int
        , col2 text default 'stuff'
        , col3 timestamptz NOT NULL DEFAULT now()
        , CONSTRAINT fk_test FOREIGN KEY (col2) REFERENCES partman_test.fk_test_reference(col2) )
    PARTITION BY RANGE (col3);

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


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

INSERT INTO salespeople VALUES
  (1,  'Poirot'),
  (10, 'May'),
  (19, 'Ivanov'),
  (20, 'Smirnoff'),
  (30, 'Ford');

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


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

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

SELECT count(*) FROM (SELECT time without time zone 'T04') AS _sub;


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

CREATE TABLE sales_feb2022 PARTITION OF sales_range FOR VALUES FROM ('2022-02-01') TO ('2022-03-01');

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


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

SELECT f1 - date 'epoch' AS "Days From Epoch" FROM DATE_TBL;

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

SELECT count(*) FROM (SELECT f1 - date 'epoch' AS "Days From Epoch" FROM DATE_TBL) AS _sub;


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

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

SELECT count(*) FROM (SELECT 1 LIMIT generate_series(1,3)) AS _sub;


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

select websearch_to_tsquery('english', 'My brand "new -smartphone"');

SELECT count(*) FROM (select websearch_to_tsquery('english', 'My brand "new -smartphone"')) AS _sub;


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

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

SELECT count(*) FROM (SELECT pg_input_is_valid('garbage', 'interval')) AS _sub;


Question: PostgreSQL Indices: show example 14.

CREATE INDEX access_log_client_ip_ix ON access_log (client_ip) WHERE NOT (client_ip > inet '192.168.100.0' AND client_ip < inet '192.168.100.255');

Explanation: Example from PostgreSQL documentation on Indices.


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

CREATE TABLE hash_name_heap (
	seqno 		int4,
	random 		name
);

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


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

INSERT INTO num_exp_sub VALUES (8,3,'74876.69');

Explanation: DML from PostgreSQL core regression test for Numeric.


Question: Show a SQL definition from the timescaledb project (multi_transaction_index, item 22).

CREATE INDEX a_hypertable_index_with_a_very_very_long_name_that_truncates_2 ON index_test (time DESC, temp ASC) WITH (timescaledb.transaction_per_chunk);

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


Question: PostgreSQL regression test 'sqljson': Write the SELECT query (example 210).

SELECT JSON_SERIALIZE('123' RETURNING sqljson_char2);

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

SELECT count(*) FROM (SELECT JSON_SERIALIZE('123' RETURNING sqljson_char2)) AS _sub;


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

ALTER EXTENSION pgtap ADD FUNCTION add_result ( bool, bool, text, text, text );

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


Question: Show a SQL definition from the timescaledb project (drop_extension, item 11).

-- Test that calling twice generates proper error
\set ON_ERROR_STOP 0
CREATE EXTENSION timescaledb;


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

INSERT INTO num_input_test(n1) VALUES ('.000_000_000_123e1_0');


Question: PostgreSQL regression test 'sqljson': Write the SELECT query (example 160).

SELECT JSON_OBJECTAGG(k: v WITH UNIQUE KEYS RETURNING jsonb)
FROM (VALUES (1, 1), (1, NULL), (2, 2)) foo(k, v);

SELECT count(*) FROM (SELECT JSON_OBJECTAGG(k: v WITH UNIQUE KEYS RETURNING jsonb)
FROM (VALUES (1, 1), (1, NULL), (2, 2)) foo(k, v)) AS _sub;


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

-- Set this variable to avoid using a hard-coded path each time query
-- results are compared
\set QUERY_RESULT_TEST_EQUAL_RELPATH 'include/query_result_test_equal.sql'

CREATE OR REPLACE FUNCTION dimension_get_time(
    hypertable_id INT
)
    RETURNS _timescaledb_catalog.dimension LANGUAGE SQL STABLE AS
$BODY$
    SELECT *
    FROM _timescaledb_catalog.dimension d
    WHERE d.hypertable_id = dimension_get_time.hypertable_id AND
          d.interval_length IS NOT NULL
$BODY$;


Question: PostgreSQL regression test 'type_sanity': Write the SELECT query (example 66).

SELECT r.rngtypid, r.rngsubtype, p.proname
FROM pg_range r JOIN pg_proc p ON p.oid = r.rngmltconstruct1 JOIN pg_type t ON r.rngmultitypid = t.oid
WHERE p.pronargs != 1
    OR p.proargtypes[0] != r.rngtypid
    OR p.prorettype != r.rngmultitypid
    OR p.proname != t.typname OR p.prosrc != 'multirange_constructor1';

Explanation: Regression test for Type Sanity in PostgreSQL core test suite.

SELECT count(*) FROM (SELECT r.rngtypid, r.rngsubtype, p.proname
FROM pg_range r JOIN pg_proc p ON p.oid = r.rngmltconstruct1 JOIN pg_type t ON r.rngmultitypid = t.oid
WHERE p.pronargs != 1
    OR p.proargtypes[0] != r.rngtypid
    OR p.prorettype != r.rngmultitypid
    OR p.proname != t.typname OR p.prosrc != 'multirange_constructor1') AS _sub;


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

Explanation: DDL from PostgreSQL core regression test for Memoize.


Question: PostgreSQL regression test 'tablesample': Write the SELECT query (example 42).

SELECT id FROM test_tablesample TABLESAMPLE SYSTEM (50) REPEATABLE (NULL);

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

SELECT count(*) FROM (SELECT id FROM test_tablesample TABLESAMPLE SYSTEM (50) REPEATABLE (NULL)) AS _sub;


Question: Write the DML statement from PostgreSQL regression test 'tablesample' (example 48).

INSERT INTO test_tablesample_v1 VALUES(1);

Explanation: DML from PostgreSQL core regression test for Tablesample.


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

select q1, float8(count(*)) / (select count(*) from int8_tbl)
from int8_tbl group by q1 order by q1;

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

SELECT count(*) FROM (select q1, float8(count(*)) / (select count(*) from int8_tbl)
from int8_tbl group by q1 order by q1) AS _sub;


Question: Show a SQL definition from the citus project (multi_alter_table_add_constraints, item 50).

-- Check "UNIQUE CONSTRAINT" with append table
CREATE TABLE unique_test_table_append(id int, name varchar(20));

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


Question: pgTAP test for Functap (assertion 187).

-- test diagnostics
SELECT * FROM check_test(
    is_normal_function( 'nonesuch', '{}'::name[], 'whatever' ),
    false,
    'is_normal_function(nofunc, noargs, desc)',
    'whatever',
    '    Function nonesuch() does not exist'
);

Explanation: SQL assertion from pgTAP test suite for Functap.


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

SELECT * FROM JSON_TABLE(jsonb'"1.23"', 'strict $.a' COLUMNS (js2 int PATH '$'));

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

SELECT count(*) FROM (SELECT * FROM JSON_TABLE(jsonb'"1.23"', 'strict $.a' COLUMNS (js2 int PATH '$'))) AS _sub;


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

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

SELECT count(*) FROM (select dfunc(10, 20)) AS _sub;


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

SELECT * FROM textrange_test WHERE 'e'::text <@ tr;

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

SELECT count(*) FROM (SELECT * FROM textrange_test WHERE 'e'::text <@ tr) AS _sub;


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

select row(1, 2)::testtype1 <> row(1)::testtype5;

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

SELECT count(*) FROM (select row(1, 2)::testtype1 <> row(1)::testtype5) AS _sub;


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

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

SELECT count(*) FROM (SELECT m * 2::float8 FROM money_data) AS _sub;


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

CREATE TABLE dropped_objects (
	object_type text,
	schema_name text,
	object_name text,
	object_identity text,
	address_names text[],
	address_args text[],
	is_temporary bool,
	original bool,
	normal bool
);

Explanation: DDL from PostgreSQL core regression test for Event Trigger.


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

SELECT substr('alphabet'::citext, 3)       = 'phabet' AS t;

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


Question: PostgreSQL regression test 'indexing': Write the SELECT query (example 3).

select relhassubclass from pg_class where relname = 'idxpart_idx';

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

SELECT count(*) FROM (select relhassubclass from pg_class where relname = 'idxpart_idx') AS _sub;


Question: Show an example of PostgreSQL UPDATE (example 1).

UPDATE films SET kind = 'Dramatic' WHERE kind = 'Drama';

Explanation: PostgreSQL UPDATE command.


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

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

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


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

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

SELECT count(*) FROM (SELECT float8_combine('{0,0,0}'::float8[], '{2,180,200}'::float8[])) AS _sub;


Question: PostgreSQL Textsearch: show example 12.

CREATE INDEX pgweb_idx ON pgweb USING GIN (to_tsvector('english', title || ' ' || body));

Explanation: Example from PostgreSQL documentation on Textsearch.


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

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

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


Question: Show a query using PostgreSQL contrib extension 'pg_stat_statements' (example 85).

SELECT WHERE 1 IN (1::int::bigint::int, 2::int::bigint::int);

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


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

CREATE INDEX tenk2_unique1 ON tenk2 USING btree(unique1 int4_ops);

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


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

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


Question: PostgreSQL regression test 'sqljson': Write the SELECT query (example 77).

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

SELECT count(*) FROM (SELECT JSON_OBJECT(1::text: 2)) AS _sub;


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

-- has_materialized_view( schema, materialized_view, description )
CREATE OR REPLACE FUNCTION has_materialized_view ( NAME, NAME, TEXT )
RETURNS TEXT AS $$
    SELECT ok( _rexists( 'm', $1, $2 ), $3 );
$$ LANGUAGE SQL;

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


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

-- create separate functional dependencies
CREATE STATISTICS functional_dependencies_multi_1 (dependencies) ON a, b FROM functional_dependencies_multi;

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


Question: Write the DDL statement from PostgreSQL regression test 'create_table_like' (example 93).

CREATE TABLE ctlt12_storage (LIKE ctlt1 INCLUDING STORAGE, LIKE ctlt2 INCLUDING STORAGE);

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


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

select jsonb_path_query('"10-03-2017 12:34 -05:20"', '$.datetime("dd-mm-yyyy HH24:MI TZH:TZM")');

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

SELECT count(*) FROM (select jsonb_path_query('"10-03-2017 12:34 -05:20"', '$.datetime("dd-mm-yyyy HH24:MI TZH:TZM")')) AS _sub;


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

CREATE OR REPLACE FUNCTION _get_rel_owner ( NAME, NAME )
RETURNS NAME AS $$
    SELECT pg_catalog.pg_get_userbyid(c.relowner)
      FROM pg_catalog.pg_class c
      JOIN pg_catalog.pg_namespace n ON n.oid = c.relnamespace
     WHERE n.nspname = $1
       AND c.relname = $2
$$ 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 'multirangetypes' (example 69).

CREATE INDEX nummultirange_test_btree ON nummultirange_test(nmr);

Explanation: DDL from PostgreSQL core regression test for Multirangetypes.


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

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


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

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


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

insert into parted values (1, 1, 'uno uno v6');

Explanation: DML from PostgreSQL core regression test for Triggers.


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

SELECT * FROM test_date WHERE i>'infinity'::timestamptz ORDER BY i;

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


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

select a,b from test_table where (a,b) > ('a','a') order by a,b;

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

SELECT count(*) FROM (select a,b from test_table where (a,b) > ('a','a') order by a,b) AS _sub;


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

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


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

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


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

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


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

SELECT nummultirange(numrange(1,2), numrange(7,8)) && nummultirange(numrange(3,4));

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

SELECT count(*) FROM (SELECT nummultirange(numrange(1,2), numrange(7,8)) && nummultirange(numrange(3,4))) AS _sub;


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

SELECT count(*) FROM test_tsvector WHERE a @@ 'wr' AND a @@ '!qh';

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

SELECT count(*) FROM (SELECT count(*) FROM test_tsvector WHERE a @@ 'wr' AND a @@ '!qh') AS _sub;


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

SELECT count(*) FROM (select jsonb_path_query('1', '$.date()')) AS _sub;


Question: Write the DML statement from PostgreSQL regression test 'merge' (example 371).

INSERT INTO pa_target SELECT id, id * 100, 'initial' FROM generate_series(1,15,2) AS id;

Explanation: DML from PostgreSQL core regression test for Merge.


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

SELECT a FROM base_tbl WHERE (a, random() > 0) IN (SELECT a, random() > 0 FROM foreign_tbl);

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


Question: PostgreSQL regression test 'xmlmap': Write the SELECT query (example 8).

SELECT table_to_xml('testxmlschema.test1', false, false, '');

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

SELECT count(*) FROM (SELECT table_to_xml('testxmlschema.test1', false, false, '')) AS _sub;


Question: PostgreSQL regression test 'limit': Write the SELECT query (example 6).

SELECT ''::text AS eleven, unique1, unique2, stringu1
		FROM onek WHERE unique1 < 50
		ORDER BY unique1 DESC LIMIT 20 OFFSET 39;

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

SELECT count(*) FROM (SELECT ''::text AS eleven, unique1, unique2, stringu1
		FROM onek WHERE unique1 < 50
		ORDER BY unique1 DESC LIMIT 20 OFFSET 39) AS _sub;


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

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

SELECT count(*) FROM (SELECT has_server_privilege('s8', 'USAGE')) AS _sub;


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

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

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


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

select percentile_disc(array[[null,1,0.5],[0.75,0.25,null]]) within group (order by thousand)
from tenk1;

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

SELECT count(*) FROM (select percentile_disc(array[[null,1,0.5],[0.75,0.25,null]]) within group (order by thousand)
from tenk1) AS _sub;


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

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

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


Question: Show an example of PostgreSQL CREATE CAST (example 1).

Explanation: PostgreSQL CREATE CAST command.


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

SELECT '0 .. 1'::seg << '1'::seg AS bool;

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


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

select numrange(3,6) >> nummultirange(numrange(3,4));

SELECT count(*) FROM (select numrange(3,6) >> nummultirange(numrange(3,4))) AS _sub;


Question: Show an example of PostgreSQL CREATE SCHEMA (example 1).

Explanation: PostgreSQL CREATE SCHEMA command.


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

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

SELECT count(*) FROM (select '["a","b","c"]'::jsonb - 0) AS _sub;


Question: pgTAP test for Proctap (assertion 65).

SELECT * FROM check_test(
    is_procedure( 'argpubfunc', 'whatever' ),
    false,
    'is_procedure(func, desc)',
    'whatever',
    ''
);

Explanation: SQL assertion from pgTAP test suite for Proctap.


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

$ createuser -h eden -p 5000 -S -D -R -e joe CREATE ROLE joe NOSUPERUSER NOCREATEDB NOCREATEROLE INHERIT LOGIN;

Explanation: PostgreSQL CREATEUSER command.


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

SELECT time with time zone '040506.07+08';

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

SELECT count(*) FROM (SELECT time with time zone '040506.07+08') AS _sub;


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

ALTER EXTENSION pgtap ADD FUNCTION todo_start ();

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


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

select * from arr_tbl where f1 > '{1,2,3}' and f1 <= '{1,5,3}';

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

SELECT count(*) FROM (select * from arr_tbl where f1 > '{1,2,3}' and f1 <= '{1,5,3}') AS _sub;


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

CREATE POLICY d1 ON dependent FOR ALL
    TO PUBLIC
    USING (x = (SELECT d.x FROM dependee d WHERE d.y = y));

Explanation: DDL from PostgreSQL core regression test for Rowsecurity.


Question: PostgreSQL regression test 'plpgsql': Write the SELECT query (example 615).

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

SELECT count(*) FROM (select * from conflict_test()) AS _sub;


Question: PL/pgSQL test: Plperl Transaction (example 17).

-- commit inside cursor loop
CREATE TABLE test2 (x int);

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


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

SELECT * FROM check_estimated_rows('SELECT COUNT(*) FROM ndistinct GROUP BY a, b, (2*c)');

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

SELECT count(*) FROM (SELECT * FROM check_estimated_rows('SELECT COUNT(*) FROM ndistinct GROUP BY a, b, (2*c)')) AS _sub;


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

SELECT '2014-10-26 01:00:01'::timestamp AT TIME ZONE 'Europe/Moscow';

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

SELECT count(*) FROM (SELECT '2014-10-26 01:00:01'::timestamp AT TIME ZONE 'Europe/Moscow') AS _sub;


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

create table child_35_40 partition of child_30_40
   for values from (35) to (40);

Explanation: DDL from PostgreSQL core regression test for Psql.


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

create table mc2p5 partition of mc2p for values from (2, maxvalue) to (maxvalue, maxvalue);

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


Question: PL/pgSQL test: Plpython Subtransaction (example 30).

CREATE FUNCTION subtransaction_exit_subtransaction_in_with() RETURNS void
AS $$
try:
    with plpy.subtransaction() as s:
        s.__exit__(None, None, None)
except ValueError as e:
    raise ValueError(e)
$$ LANGUAGE plpython3u;

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


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

INSERT INTO pub_testpart1.child_parent2 values(1);

Explanation: DML from PostgreSQL core regression test for Publication.


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

select range_intersect_agg(nmr) from (values ('{}'::nummultirange)) t(nmr);

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

SELECT count(*) FROM (select range_intersect_agg(nmr) from (values ('{}'::nummultirange)) t(nmr)) AS _sub;


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

SELECT * FROM ft1 ORDER BY c3, c1 OFFSET 100 LIMIT 10;

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


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

INSERT INTO transition_table_status (level, node_no, status)
  SELECT 1, level1_no, 0 FROM transition_table_level1;

Explanation: DML from PostgreSQL core regression test for Plpgsql.


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

CREATE OPERATOR #># (
       LEFTARG = hstore,
       RIGHTARG = hstore,
       PROCEDURE = hstore_gt,
       COMMUTATOR = #<#,
       NEGATOR = #<=#,
       RESTRICT = scalargtsel,
       JOIN = scalargtjoinsel
);

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


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

SELECT d AS date, i AS interval,
       eval(format('date %L + interval %L', d, i)) AS plus,
       eval(format('date %L - interval %L', d, i)) AS minus
FROM (VALUES (date '-infinity'),
             (date '1995-08-06'),
             (date 'infinity')) AS t1(d),
     (VALUES (interval '-infinity'),
             (interval 'infinity')) AS t2(i);

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

SELECT count(*) FROM (SELECT d AS date, i AS interval,
       eval(format('date %L + interval %L', d, i)) AS plus,
       eval(format('date %L - interval %L', d, i)) AS minus
FROM (VALUES (date '-infinity'),
             (date '1995-08-06'),
             (date 'infinity')) AS t1(d),
     (VALUES (interval '-infinity'),
             (interval 'infinity')) AS t2(i)) AS _sub;


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

-- domain_type_is( schema, domain, type, description )
CREATE OR REPLACE FUNCTION domain_type_is( NAME, TEXT, TEXT, TEXT )
RETURNS TEXT AS $$
DECLARE
    actual_type TEXT := _get_dtype($1, $2, false);
BEGIN
    IF actual_type IS NULL THEN
        RETURN fail( $4 ) || E'\n' || diag (
            '   Domain ' || quote_ident($1) || '.' || $2
            || ' does not exist'
        );
    END IF;

    RETURN is( actual_type, _typename($3), $4 );
END;
$$ LANGUAGE plpgsql;

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


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

CREATE INDEX tbl_idx ON tbl (c1, (c1+0)) INCLUDE (c2);

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


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

/* contrib/pageinspect/pageinspect--1.5--1.6.sql */

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

--
-- HASH functions
--

--
-- hash_page_type()
--
CREATE FUNCTION hash_page_type(IN page bytea)
RETURNS text
AS 'MODULE_PATHNAME', 'hash_page_type'
LANGUAGE C STRICT PARALLEL SAFE;


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

-- Test subtransaction successfully committed

CREATE FUNCTION subtransaction_ctx_success() RETURNS void
AS $$
    spi_exec "INSERT INTO subtransaction_tbl VALUES(1)"
    subtransaction {
        spi_exec "INSERT INTO subtransaction_tbl VALUES(2)"
    }
$$ LANGUAGE pltcl;

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


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

SELECT COUNT(*)
FROM pg_foreign_table
WHERE ftrelid = 'table30'::regclass
AND ftoptions @> array['batch_size=40'];


Question: Show an example of PostgreSQL ALTER OPERATOR (example 2).

ALTER OPERATOR && (int[], int[]) SET (RESTRICT = _int_contsel, JOIN = _int_contjoinsel);

Explanation: PostgreSQL ALTER OPERATOR command.


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

SELECT * FROM shoelace_obsolete ORDER BY sl_len_cm;

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

SELECT count(*) FROM (SELECT * FROM shoelace_obsolete ORDER BY sl_len_cm) AS _sub;


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

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


Question: PostgreSQL regression test 'random': Write the SELECT query (example 41).

SELECT random_normal(mean => 1, stddev => 0.1) r FROM generate_series(1, 10);

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

SELECT count(*) FROM (SELECT random_normal(mean => 1, stddev => 0.1) r FROM generate_series(1, 10)) AS _sub;


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

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

SELECT count(*) FROM (select '["c"]' || '["a", "b"]'::jsonb) AS _sub;


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

SELECT rtrim('trimxxxx'::citext, 'x'::citext) = 'trim' AS t;

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


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

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


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

INSERT INTO TIMESTAMP_TBL VALUES ('Feb-10-1997 17:32:01 PST');

Explanation: DML from PostgreSQL core regression test for Timestamp.


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

SELECT t1.c1, t2.c1 FROM ft1 t1 CROSS JOIN ft2 t2 ORDER BY t1.c1, t2.c1 OFFSET 100 LIMIT 10;


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

SELECT dealloc FROM pg_stat_statements_info;

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


Question: Write the DML statement from PostgreSQL regression test 'rowtypes' (example 152).

UPDATE price
    SET active = true, price = input_prices.price
    FROM unnest(ARRAY[(10, 123.00), (11, 99.99)]::price_input[]) input_prices
    WHERE price_key_from_table(price.*) = price_key_from_input(input_prices.*);

Explanation: DML from PostgreSQL core regression test for Rowtypes.


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

insert into rtest_comp values ('p2', 'm', 3.0);

Explanation: DML from PostgreSQL core regression test for Rules.


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

ALTER EXTENSION pgtap ADD FUNCTION tables_are ( NAME[] );

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


Question: PostgreSQL regression test 'tsdicts': Write the SELECT query (example 55).

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

SELECT count(*) FROM (SELECT ts_lexize('hunspell_num', 'bookings')) AS _sub;


Question: pgTAP test for Fktap (assertion 53).

SELECT * FROM check_test(
    fk_ok( 'fk', ARRAY['pk_id'], 'pk', ARRAY['id'] ),
    true,
    'fk_ok array noschema desc',
    'fk(pk_id) should reference pk(id)'
);

Explanation: SQL assertion from pgTAP test suite for Fktap.


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

CREATE SEQUENCE sequence_test11 AS smallint;

Explanation: DDL from PostgreSQL core regression test for Sequence.


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

EXECUTE format('create or replace function zdb.geography_to_json(%I.geography, typmod integer DEFAULT -1) returns json parallel safe immutable strict language sql as $$
          select zdb.geometry_to_json($1::%I.geometry, $2);
          $$;',
      geojson_namespace, geojson_namespace);

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


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

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


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

insert into rule_and_refint_t3 values (1, 11, 13, 'row7');


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

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


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

INSERT INTO TIMESTAMPTZ_TBL VALUES ('1997-01-02 03:04:05');

Explanation: DML from PostgreSQL core regression test for Timestamptz.


Question: Write the DDL statement from PostgreSQL regression test 'transactions' (example 47).

Explanation: DDL from PostgreSQL core regression test for Transactions.


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

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

SELECT count(*) FROM (select '[4,5)'::restrictedrange @> 7) AS _sub;


Question: pgTAP test for Coltap (assertion 7).

CREATE OR REPLACE FUNCTION fakeout( eok boolean, name text )
RETURNS SETOF TEXT AS $$
DECLARE
    descr text := coalesce( name || ' ', 'Test ' ) || 'should ';
BEGIN
    RETURN NEXT pass(descr || CASE eok WHEN true then 'pass' ELSE 'fail' END);
    RETURN NEXT pass(descr || 'have the proper description');
    RETURN NEXT pass(descr || 'have the proper diagnostics');
    RETURN;
END;
$$ LANGUAGE PLPGSQL;

Explanation: SQL assertion from pgTAP test suite for Coltap.


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

CREATE OPERATOR <@ (
        LEFTARG = ltree,
	RIGHTARG = _ltree,
	PROCEDURE = _ltree_r_isparent,
        COMMUTATOR = '@>',
        RESTRICT = contsel,
	JOIN = contjoinsel
);

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


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

CREATE TABLE fail_part PARTITION OF list_parted FOR VALUES WITH (MODULUS 10, REMAINDER 1);

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


Question: PL/pgSQL test: Plpgsql Transaction (example 120).

END
$$;

SELECT * FROM test2;

-- another snapshot handling case: argument expressions of a CALL need
-- to be evaluated with an up-to-date snapshot
CREATE FUNCTION report_count() RETURNS int
STABLE LANGUAGE sql
AS $$ SELECT COUNT(*) FROM test2 $$;

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


Question: pgTAP test for Coltap (assertion 37).

SELECT * FROM check_test(
    col_type_is( 'public', 'sometab', 'stuff', 'hidden'::name, 'stuff' ),
    true,
    'col_type_is( sch, tab, stuff, sch, type, desc )',
    'Column public.sometab.stuff should be type hidden.stuff',
    ''
);


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

SELECT ia FROM jsonb_populate_record(NULL::jsbrec, '{"ia": 123}') q;

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

SELECT count(*) FROM (SELECT ia FROM jsonb_populate_record(NULL::jsbrec, '{"ia": 123}') q) AS _sub;


Question: PostgreSQL Typeconv: show example 22.

SELECT substr(1234, 3); ERROR: function substr(integer, integer) does not exist DETAIL: No function of that name accepts the given argument types. HINT: You might need to add explicit type casts.;

Explanation: Example from PostgreSQL documentation on Typeconv.


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

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

SELECT count(*) FROM (select jsonb_path_query('[1,2,3,{"b": [3,4,5]}]', 'lax $.*')) AS _sub;


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

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

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

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


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

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


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

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

SELECT count(*) FROM (select regexp_matches('abc', 'a(?<=a)b*(?<=b)c*')) AS _sub;


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

select sum(null::int8) from generate_series(1,3);

SELECT count(*) FROM (select sum(null::int8) from generate_series(1,3)) AS _sub;


Question: Show a SQL definition from the pg_partman project (pg_partman--1.4.5--1.5.0, item 9).

/*
 * Drop constraints managed by pg_partman
 */
CREATE FUNCTION drop_constraints(p_parent_table text, p_child_table text, p_debug boolean DEFAULT false) RETURNS void
    LANGUAGE plpgsql
    AS $$
DECLARE

v_col                           text;
v_constraint_cols               text[];
v_existing_constraint_name      text;
v_exists                        boolean := FALSE;
v_job_id                        bigint;
v_jobmon_schema                 text;
v_old_search_path               text;
v_sql                           text;
v_step_id                       bigint;

BEGIN

SELECT constraint_cols INTO v_constraint_cols FROM @extschema@.part_config WHERE parent_table = p_parent_table;

IF v_constraint_cols IS NULL THEN
    RAISE EXCEPTION 'Given parent table (%) not set up for constraint management (constraint_cols is NULL)', p_parent_table;
END IF;

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

IF v_jobmon_schema IS NOT NULL THEN
    v_job_id := add_job('PARTMAN DROP CONSTRAINT: '||p_parent_table);
    v_step_id := add_step(v_job_id, 'Entering constraint drop loop');
    PERFORM update_step(v_step_id, 'OK', 'Done');
END IF;

FOREACH v_col IN ARRAY v_constraint_cols
LOOP

    SELECT c.conname
    INTO v_existing_constraint_name
    FROM pg_catalog.pg_constraint c
        JOIN pg_catalog.pg_attribute a ON c.conrelid = a.attrelid
    WHERE conrelid = p_child_table::regclass
        AND c.conname LIKE 'partmanconstr_%'
        AND c.contype = 'c'
        AND a.attname = v_col
        AND ARRAY[a.attnum] <@ c.conkey
        AND a.attisdropped = false;

    IF v_existing_constraint_name IS NOT NULL THEN
        v_exists := TRUE;
        IF v_jobmon_schema IS NOT NULL THEN
            v_step_id := add_step(v_job_id, 'Dropping constraint on column: '||v_col);
        END IF;
        v_sql := 'ALTER TABLE '||p_child_table||' DROP CONSTRAINT '||v_existing_constraint_name;
        IF p_debug THEN
            RAISE NOTICE 'Constraint drop query: %', v_sql;
        END IF;
        EXECUTE v_sql;
        IF v_jobmon_schema IS NOT NULL THEN
            PERFORM update_step(v_step_id, 'OK', 'Drop constraint query: '||v_sql);
        END IF;
    END IF;

END LOOP;

IF v_jobmon_schema IS NOT NULL AND v_exists IS FALSE THEN
    v_step_id := add_step(v_job_id, 'No constraints found to drop on child table: '||p_child_table);
    PERFORM update_step(v_step_id, 'OK', 'Done');
END IF;

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

EXCEPTION
    WHEN OTHERS THEN
        IF v_jobmon_schema IS NOT NULL THEN
            IF v_job_id IS NULL THEN
                EXECUTE 'SELECT '||v_jobmon_schema||'.add_job(''PARTMAN DROP CONSTRAINT: '||p_parent_table||')' INTO v_job_id;
                EXECUTE 'SELECT '||v_jobmon_schema||'.add_step('||v_job_id||', ''Partition constraint maintenance for table '||p_parent_table||' failed'')' INTO v_step_id;
            ELSIF v_step_id IS NULL THEN
                EXECUTE 'SELECT '||v_jobmon_schema||'.add_step('||v_job_id||', ''EXCEPTION before first step logged'')' INTO v_step_id;
            END IF;
            EXECUTE 'SELECT '||v_jobmon_schema||'.update_step('||v_step_id||', ''CRITICAL'', ''ERROR: '||coalesce(SQLERRM,'unknown')||''')';
            EXECUTE 'SELECT '||v_jobmon_schema||'.fail_job('||v_job_id||')';
        END IF;
        RAISE EXCEPTION '%', SQLERRM;
END
$$;

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


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

SELECT c~>1, c FROM test_cube ORDER BY c~>1 LIMIT 15; -- ascending by left bound
SELECT c~>2, c FROM test_cube ORDER BY c~>2 LIMIT 15; -- ascending by right bound
SELECT c~>3, c FROM test_cube ORDER BY c~>3 LIMIT 15; -- ascending by lower bound
SELECT c~>4, c FROM test_cube ORDER BY c~>4 LIMIT 15; -- ascending by upper bound
SELECT c~>(-1), c FROM test_cube ORDER BY c~>(-1) LIMIT 15; -- descending by left bound
SELECT c~>(-2), c FROM test_cube ORDER BY c~>(-2) LIMIT 15; -- descending by right bound
SELECT c~>(-3), c FROM test_cube ORDER BY c~>(-3) LIMIT 15; -- descending by lower bound
SELECT c~>(-4), c FROM test_cube ORDER BY c~>(-4) LIMIT 15; -- descending by upper bound
RESET enable_indexscan;

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


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

CREATE OPERATOR ^@ (
        LEFTARG = _ltree,
	RIGHTARG = ltxtquery,
	PROCEDURE = _ltxtq_exec,
        COMMUTATOR = '^@',
        RESTRICT = contsel,
	JOIN = contjoinsel
);


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

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

SELECT count(*) FROM (SELECT brin_summarize_range('brin_summarize_idx', 2)) AS _sub;


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

CREATE UNIQUE INDEX ON regress_constr_partitioned (a);

Explanation: DDL from PostgreSQL core regression test for Constraints.


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

SELECT INTERVAL '+02:00' AS "Two hours";

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

SELECT count(*) FROM (SELECT INTERVAL '+02:00' AS "Two hours") AS _sub;


Question: pgTAP test for Resultset (assertion 319).

Explanation: SQL assertion from pgTAP test suite for Resultset.


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

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


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

ALTER EXTENSION pgtap ADD FUNCTION results_eq( refcursor, TEXT );

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


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

Explanation: DDL from PostgreSQL core regression test for Update.


Question: pgTAP test for Functap (assertion 382).

SELECT * FROM check_test(
    volatility_is( 'someproc'::name, 'volatile' ),
    true,
    'function_volatility(proc, volatile)',
    'Function someproc() should be VOLATILE',
    ''
);

Explanation: SQL assertion from pgTAP test suite for Functap.


Question: Write the DDL statement from PostgreSQL regression test 'rangetypes' (example 304).

create index test_range_elem_idx on test_range_elem (i);

Explanation: DDL from PostgreSQL core regression test for Rangetypes.


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

create table utr2 (a int check (a in (2)), b text);


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

select f1,g from int4_tbl a cross join (select f1 as g) ss;

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

SELECT count(*) FROM (select f1,g from int4_tbl a cross join (select f1 as g) ss) AS _sub;


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

SELECT count(*) FROM (select jsonb_path_query('[null,1,true,"a",[],{}]', '$[*].type()')) AS _sub;


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

SELECT 'xyz' !~ '[[:upper:]]' COLLATE PG_UNICODE_FAST;

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

SELECT count(*) FROM (SELECT 'xyz' !~ '[[:upper:]]' COLLATE PG_UNICODE_FAST) AS _sub;


Question: Write the DDL statement from PostgreSQL regression test 'event_trigger' (example 30).

CREATE EVENT TRIGGER regress_event_trigger_report_dropped ON sql_drop
    EXECUTE PROCEDURE event_trigger_report_dropped();

Explanation: DDL from PostgreSQL core regression test for Event Trigger.


Question: Show a SQL definition from the timescaledb project (triggers, item 11).

CREATE TRIGGER _0_test_trigger_delete
    BEFORE delete ON hyper
    FOR EACH ROW EXECUTE FUNCTION test_trigger();

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


Question: Write the DDL statement from PostgreSQL regression test 'plpgsql' (example 618).

create or replace function conflict_test() returns setof int8_tbl as $$
#variable_conflict use_column
declare r record;
  q1 bigint := 42;
begin
  for r in select q1,q2 from int8_tbl loop
    return next r;
  end loop;
end;
$$ language plpgsql;

Explanation: DDL from PostgreSQL core regression test for Plpgsql.


Question: Show a SQL definition from the citus project (merge_repartition1, item 22).

CREATE OR REPLACE FUNCTION setup_data() RETURNS VOID SET search_path TO merge_repartition1_schema AS $$
    INSERT INTO pg_source SELECT i, i+1, 1 FROM generate_series(1, 10000) i;
    INSERT INTO pg_target SELECT i, 1 FROM generate_series(5001, 10000) i;
    INSERT INTO citus_source SELECT i, i+1, 1 FROM generate_series(1, 10000) i;
    INSERT INTO citus_target SELECT i, 1 FROM generate_series(5001, 10000) i;
$$
LANGUAGE SQL;

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


Question: Write the DML statement from PostgreSQL regression test 'partition_merge' (example 84).

INSERT INTO salespeople10_20 VALUES (19, 'Ivanov');

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


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

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

SELECT count(*) FROM (select jsonb_path_query('1234', '$.string().type()')) AS _sub;


Question: PostgreSQL regression test 'bit': Write the SELECT query (example 45).

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

SELECT count(*) FROM (select B'0010' # B'011101') AS _sub;


Question: pgTAP test for Resultset (assertion 115).

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


Question: pgTAP test for Proctap (assertion 2).

Explanation: SQL assertion from pgTAP test suite for Proctap.


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

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

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


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

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


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

alter function non_strict(text) returns null on null input;

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


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

INSERT INTO result_tbl
(SELECT a, b, 'AAA' || c FROM async_p1 ORDER BY a LIMIT 10)
UNION
(SELECT a, b, 'AAA' || c FROM async_p2 WHERE b < 10);

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


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

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


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

create function polyf(x anycompatiblemultirange, y anycompatiblearray) returns anycompatiblemultirange as $$
  select x
$$ language sql;

Explanation: DDL from PostgreSQL core regression test for Polymorphism.


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

select * from jsonb_to_record('{"ia": [[1], 2]}') as x(ia _int4);

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


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

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


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

/* contrib/dict_xsyn/dict_xsyn--1.0.sql */

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

CREATE FUNCTION dxsyn_init(internal)
        RETURNS internal
        AS 'MODULE_PATHNAME'
        LANGUAGE C STRICT;


Question: Write the DDL statement from PostgreSQL regression test 'aggregates' (example 442).

create aggregate my_avg_init2(int4)
(
   stype = avg_state,
   sfunc = avg_transfn,
   finalfunc = avg_finalfn,
   initcond = '(4,0)'
);

Explanation: DDL from PostgreSQL core regression test for Aggregates.


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

create view bpchar_view as
  select
    f1, f1::character(14) as f114, f1::bpchar as f1n,
    f2, f2::character(14) as f214, f2::bpchar as f2n
  from bpchar_tbl;

Explanation: DDL from PostgreSQL core regression test for Expressions.


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

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

SELECT count(*) FROM (SELECT timestamp with time zone '12.27.2001 04:05:06.789-08') AS _sub;


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

SELECT JSON_ARRAYAGG(JSON_ARRAY(i, i + 1 RETURNING text) FORMAT JSON)
FROM generate_series(1, 5) i;

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

SELECT count(*) FROM (SELECT JSON_ARRAYAGG(JSON_ARRAY(i, i + 1 RETURNING text) FORMAT JSON)
FROM generate_series(1, 5) i) AS _sub;


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

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

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


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

CREATE FUNCTION is_valid(ean13)
	RETURNS boolean
	AS 'MODULE_PATHNAME'
	LANGUAGE C
	IMMUTABLE STRICT
	PARALLEL SAFE;


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

create operator family my_op_family using btree;

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


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

select foo1.join_key as foo1_id, foo3.join_key AS foo3_id, bug_field from
  (values (0),(1)) foo1(join_key)
left join
  (select join_key, bug_field from
    (select ss1.join_key, ss1.bug_field from
      (select f1 as join_key, 666 as bug_field from int4_tbl i1) ss1
    ) foo2
   left join
    (select unique2 as join_key from tenk1 i2) ss2
   using (join_key)
  ) foo3
using (join_key);

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

SELECT count(*) FROM (select foo1.join_key as foo1_id, foo3.join_key AS foo3_id, bug_field from
  (values (0),(1)) foo1(join_key)
left join
  (select join_key, bug_field from
    (select ss1.join_key, ss1.bug_field from
      (select f1 as join_key, 666 as bug_field from int4_tbl i1) ss1
    ) foo2
   left join
    (select unique2 as join_key from tenk1 i2) ss2
   using (join_key)
  ) foo3
using (join_key)) AS _sub;


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

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

SELECT count(*) FROM (select cardinality(array[1,2,3])) AS _sub;


Question: Show a SQL definition from the citus project (citus_local_table_triggers, item 50).

CREATE TRIGGER error_for_5_trigger
    BEFORE UPDATE OF value ON citus_local_table
    FOR EACH ROW EXECUTE FUNCTION error_for_5();

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


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

SELECT sum(unique1) over (order by four range between 2::int8 preceding and 6::int2 following exclude group),
	unique1, four
FROM tenk1 WHERE unique1 < 10;

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

SELECT count(*) FROM (SELECT sum(unique1) over (order by four range between 2::int8 preceding and 6::int2 following exclude group),
	unique1, four
FROM tenk1 WHERE unique1 < 10) AS _sub;


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

SELECT * FROM verify_heapam('test_partition',
							startblock := NULL,
							endblock := NULL);

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


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

SELECT t1.a, t1.c, t2.b, t2.c FROM prt1_e t1, prt2_e t2 WHERE (t1.a + t1.b)/2 = (t2.b + t2.a)/2 AND t1.c = 0 ORDER BY t1.a, t2.b;

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

SELECT count(*) FROM (SELECT t1.a, t1.c, t2.b, t2.c FROM prt1_e t1, prt2_e t2 WHERE (t1.a + t1.b)/2 = (t2.b + t2.a)/2 AND t1.c = 0 ORDER BY t1.a, t2.b) AS _sub;


Question: pgTAP test for Resultset (assertion 203).

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

Explanation: SQL assertion from pgTAP test suite for Resultset.


Question: PostgreSQL regression test 'create_view': Write the SELECT query (example 263).

Explanation: Regression test for Create View in PostgreSQL core test suite.

SELECT count(*) FROM (select pg_get_viewdef('tt17v', true)) AS _sub;


Question: pgTAP test for Functap (assertion 144).

SELECT * FROM check_test(
    isnt_definer( 'public'::name, 'someproc'::name ),
    true,
    'isnt_definer(sch, proc)',
    'Function public.someproc() should not be security definer',
    ''
);

Explanation: SQL assertion from pgTAP test suite for Functap.


Question: PL/pgSQL test: Plperl Trigger (example 17).

DROP TRIGGER show_trigger_data_trig_after ON trigger_test_generated;

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


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

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


Question: Write the DML statement from PostgreSQL regression test 'rangefuncs' (example 3).

Explanation: DML from PostgreSQL core regression test for Rangefuncs.


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

create function tcl_int4_avg(int4[]) returns int4 as '
    set state [split $1 "{,}"]
    if {[lindex $state 2] == 0} { return_null }
    return [expr {[lindex $state 1] / [lindex $state 2]}]
' language pltcl;

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


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

-- Check for index amhandler functions with the wrong signature

SELECT a1.oid, a1.amname, p1.oid, p1.proname
FROM pg_am AS a1, pg_proc AS p1
WHERE p1.oid = a1.amhandler AND a1.amtype = 'i' AND
    (p1.prorettype != 'index_am_handler'::regtype
     OR p1.proretset
     OR p1.pronargs != 1
     OR p1.proargtypes[0] != 'internal'::regtype);

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


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

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

SELECT count(*) FROM (SELECT xml_is_well_formed('<foo><bar>baz</foo>')) AS _sub;


Question: PostgreSQL regression test 'tsrf': Write the SELECT query (example 65).

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

SELECT count(*) FROM (SELECT |@|ARRAY[1,2,3]) AS _sub;


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

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

SELECT count(*) FROM (select jsonb_path_query('"12:34:56.789"', '$.time(2.0)')) AS _sub;


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

SELECT * FROM check_estimated_rows('SELECT * FROM expr_stats WHERE a = 0 AND (2*a) = 0 AND (3*b) = 0');

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

SELECT count(*) FROM (SELECT * FROM check_estimated_rows('SELECT * FROM expr_stats WHERE a = 0 AND (2*a) = 0 AND (3*b) = 0')) AS _sub;


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

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


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

CREATE PUBLICATION pub FOR TABLES IN SCHEMA sch2 WITH (PUBLISH_VIA_PARTITION_ROOT=0);

Explanation: DDL from PostgreSQL core regression test for Publication.


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

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


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

select *, c is null as c_is_null
from jsonb_to_recordset('[{"a":1, "b":{"c":16, "d":2}, "x":8}]'::jsonb)
    as t(a int, b jsonb, c text, x int);

SELECT count(*) FROM (select *, c is null as c_is_null
from jsonb_to_recordset('[{"a":1, "b":{"c":16, "d":2}, "x":8}]'::jsonb)
    as t(a int, b jsonb, c text, x int)) AS _sub;


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

INSERT INTO d_star (class, a, b)
   VALUES ('d', 11, 'fumble'::text);

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


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

select tcl_cdomain_arg(row('tkey', 42, 'ref2')::T_comp1);

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


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

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


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

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

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


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

insert into rtest_nothn1 values (50, 'want this');

Explanation: DML from PostgreSQL core regression test for Rules.


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

create function dfunc(a text DEFAULT 'Hello', b text DEFAULT 'World') returns text as $$
  select $1 || ', ' || $2;
$$ language sql;

Explanation: DDL from PostgreSQL core regression test for Polymorphism.


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

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

SELECT count(*) FROM (SELECT a FROM arrtest) AS _sub;


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

SELECT count(*) FROM ltreetest WHERE t >  '12.3';


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

UPDATE unique_tbl SET i = 4 WHERE i = 2;

Explanation: DML from PostgreSQL core regression test for Constraints.


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

-- Convenience view to list all hypertables
CREATE OR REPLACE VIEW timescaledb_information.hypertables AS
WITH
  hypertable_info AS (
    SELECT hypertable_id, schema_name, table_name,
           num_dimensions, compression_state, column_name,
           column_type, interval_length,
           (compression_state = 1) AS compression_enabled,
           row_number() OVER (PARTITION BY hypertable_id ORDER BY di.id) AS dimension_num
      FROM _timescaledb_catalog.hypertable ht
      JOIN _timescaledb_catalog.dimension di ON ht.id = di.hypertable_id
  )
SELECT
  ht.schema_name AS hypertable_schema,
  ht.table_name AS hypertable_name,
  t.tableowner AS owner,
  ht.num_dimensions,
  (
    SELECT count(1)
    FROM _timescaledb_catalog.chunk ch
    WHERE ch.hypertable_id = ht.hypertable_id
      AND ch.osm_chunk IS FALSE
  ) AS num_chunks,
  ht.compression_enabled,
  srchtbs.tablespace_list AS tablespaces,
  ht.column_name AS primary_dimension,
  ht.column_type AS primary_dimension_type
FROM hypertable_info ht
JOIN pg_tables t ON ht.table_name = t.tablename AND ht.schema_name = t.schemaname
LEFT JOIN _timescaledb_catalog.continuous_agg ca ON ca.mat_hypertable_id = ht.hypertable_id
LEFT JOIN (
    SELECT hypertable_id,
      array_agg(tablespace_name ORDER BY id) AS tablespace_list
    FROM _timescaledb_catalog.tablespace
    GROUP BY hypertable_id) srchtbs ON ht.hypertable_id = srchtbs.hypertable_id
WHERE ht.compression_state != 2 --> no internal compression tables
  AND ca.mat_hypertable_id IS NULL
  AND ht.interval_length IS NOT NULL
  AND ht.dimension_num = 1;

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


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

SELECT jsonb_path_match('"a"', '$', silent => false);

SELECT count(*) FROM (SELECT jsonb_path_match('"a"', '$', silent => false)) AS _sub;


Question: PostgreSQL regression test 'numerology': Write the SELECT query (example 82).

SELECT f1 AS two, max(f3) AS max_float, min(f3) as min_float
  FROM TEMP_GROUP
  GROUP BY f1
  ORDER BY two, max_float, min_float;

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

SELECT count(*) FROM (SELECT f1 AS two, max(f3) AS max_float, min(f3) as min_float
  FROM TEMP_GROUP
  GROUP BY f1
  ORDER BY two, max_float, min_float) AS _sub;


Question: pgTAP test for Resultset (assertion 158).

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

Explanation: SQL assertion from pgTAP test suite for Resultset.


Question: Write the DDL statement from PostgreSQL regression test 'create_schema' (example 17).

CREATE SCHEMA regress_schema_1 AUTHORIZATION CURRENT_ROLE
  CREATE TRIGGER schema_trig BEFORE INSERT ON schema_not_existing.tab
  EXECUTE FUNCTION schema_trig.no_func();

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


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

insert into fktable(ftest1, ftest2) values (3, 1);

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


Question: pgTAP test for Hastap (assertion 193).

SELECT * FROM check_test(
  hasnt_operator( 'integer', 'pg_catalog', '<=', 'text', 'boolean', 'desc' ),
  true,
  'hasnt_operator( left, schema, name, right, result, desc )',
  'desc',
  ''
);

Explanation: SQL assertion from pgTAP test suite for Hastap.


Question: PostgreSQL regression test 'partition_prune': Write the SELECT query (example 181).

select * from iboolpart where a is not false;

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

SELECT count(*) FROM (select * from iboolpart where a is not false) AS _sub;


Question: PostgreSQL regression test 'partition_prune': Write the SELECT query (example 136).

select * from boolpart where a is true or a is not true;

SELECT count(*) FROM (select * from boolpart where a is true or a is not true) AS _sub;


Question: PostgreSQL regression test 'identity': Write the SELECT query (example 72).

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

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


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

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

SELECT count(*) FROM (select interval '-2147483648 months -2147483648 days -9223372036854775808 microseconds ago') AS _sub;


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

SELECT count(*) FROM (select '{null,n\ull,"null"}'::text[]) AS _sub;


Question: pgTAP test for Valueset (assertion 307).

SELECT * FROM check_test(
    bag_eq(
        'justnames',
        ARRAY['Andrew', 'Anna', 'Anthony', 'Antonio', 'Angelina', 'Andrea', 'Angel', 'Anna' ]
    ),
    false,
    'bag_eq(prepared, dupe array) fail',
    '',
    '    Missing records:
        (Anna)'
);

Explanation: SQL assertion from pgTAP test suite for Valueset.


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

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


Question: PostgreSQL regression test 'index_including': Write the SELECT query (example 5).

SELECT pg_get_indexdef(i.indexrelid)
FROM pg_index i JOIN pg_class c ON i.indexrelid = c.oid
WHERE i.indrelid = 'tbl_include_reg'::regclass ORDER BY c.relname;

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

SELECT count(*) FROM (SELECT pg_get_indexdef(i.indexrelid)
FROM pg_index i JOIN pg_class c ON i.indexrelid = c.oid
WHERE i.indrelid = 'tbl_include_reg'::regclass ORDER BY c.relname) AS _sub;


Question: PL/pgSQL test: Plpython Setof (example 4).

CREATE FUNCTION test_setof_as_tuple(count integer, content text) RETURNS SETOF text AS $$
t = ()
for i in range(count):
	t += ( content, )
return t
$$ LANGUAGE plpython3u;

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


Question: PostgreSQL regression test 'create_index': Write the SELECT query (example 131).

SELECT * FROM array_index_op_test WHERE i @> '{32,17}' ORDER BY seqno;

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

SELECT count(*) FROM (SELECT * FROM array_index_op_test WHERE i @> '{32,17}' ORDER BY seqno) AS _sub;


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

create trigger brtrigpartcon1trig before insert on brtrigpartcon1 for each row execute procedure brtrigpartcon1trigf();

Explanation: DDL from PostgreSQL core regression test for Insert.


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

insert into test8(f1, f8) values (x'7f00007f'::int, 0);

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


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

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


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

/* contrib/pg_visibility/pg_visibility--1.1.sql */

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

-- Show visibility map information.
CREATE FUNCTION pg_visibility_map(regclass, blkno bigint,
								  all_visible OUT boolean,
								  all_frozen OUT boolean)
RETURNS record
AS 'MODULE_PATHNAME', 'pg_visibility_map'
LANGUAGE C STRICT;

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


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

create table part_gg2_1 partition of part_gg2 for values from (1) to (5);


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

INSERT INTO caster (citext)        VALUES ('12.42'::float4);


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

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


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

/*
 * Create the trigger function for the parent table of a time-based partition set
 */
CREATE OR REPLACE FUNCTION create_function_time(p_parent_table text, p_job_id bigint DEFAULT NULL) RETURNS void
    LANGUAGE plpgsql SECURITY DEFINER
    AS $$
DECLARE

ex_context                      text;
ex_detail                       text;
ex_hint                         text;
ex_message                      text;
v_control                       text;
v_count                         int;
v_current_partition_name        text;
v_current_partition_timestamp   timestamptz;
v_datetime_string               text;
v_epoch                         boolean;
v_final_partition_timestamp     timestamptz;
v_function_name                 text;
v_job_id                        bigint;
v_jobmon                        boolean;
v_jobmon_schema                 text;
v_new_search_path               text := '@extschema@,pg_temp';
v_old_search_path               text;
v_new_length                    int;
v_next_partition_name           text;
v_next_partition_timestamp      timestamptz;
v_parent_schema                 text;
v_parent_tablename              text;
v_partition_interval            interval;
v_prev_partition_name           text;
v_prev_partition_timestamp      timestamptz;
v_step_id                       bigint;
v_trig_func                     text;
v_optimize_trigger              int;
v_trigger_exception_handling    boolean;
v_trigger_return_null           boolean;
v_type                          text;
v_upsert                        text;

BEGIN

SELECT partition_type
    , partition_interval::interval
    , epoch
    , control
    , optimize_trigger
    , datetime_string
    , jobmon
    , trigger_exception_handling
    , upsert
    , trigger_return_null
INTO v_type
    , v_partition_interval
    , v_epoch
    , v_control
    , v_optimize_trigger
    , v_datetime_string
    , v_jobmon
    , v_trigger_exception_handling
    , v_upsert
    , v_trigger_return_null
FROM @extschema@.part_config
WHERE parent_table = p_parent_table
AND (partition_type = 'time' OR partition_type = 'time-custom');

IF NOT FOUND THEN
    RAISE EXCEPTION 'ERROR: no config found for %', p_parent_table;
END IF;

SELECT current_setting('search_path') INTO v_old_search_path;
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'::name AND e.extnamespace = n.oid;
    IF v_jobmon_schema IS NOT NULL THEN
        v_new_search_path := '@extschema@,'||v_jobmon_schema||',pg_temp';
    END IF;
END IF;
EXECUTE format('SELECT set_config(%L, %L, %L)', 'search_path', v_new_search_path, 'false');

IF v_jobmon_schema IS NOT NULL THEN
    IF p_job_id IS NULL THEN
        v_job_id := add_job(format('PARTMAN CREATE FUNCTION: %s', p_parent_table));
    ELSE
        v_job_id = p_job_id;
    END IF;
    v_step_id := add_step(v_job_id, format('Creating partition function for table %s', p_parent_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)::name
AND tablename = split_part(p_parent_table, '.', 2)::name;

v_function_name := @extschema@.check_name_length(v_parent_tablename, '_part_trig_func', FALSE);

IF v_type = 'time' THEN
    v_trig_func := format('CREATE OR REPLACE FUNCTION %I.%I() RETURNS trigger LANGUAGE plpgsql AS $t$
            DECLARE
            v_count                 int;
            v_partition_name        text;
            v_partition_timestamp   timestamptz;
        BEGIN
        IF TG_OP = ''INSERT'' THEN
            '
    , v_parent_schema
    , v_function_name);

    IF v_epoch = false THEN
        CASE
            WHEN v_partition_interval = '15 mins' THEN
                v_trig_func := v_trig_func||format('v_partition_timestamp := date_trunc(''hour'', NEW.%I) +
                    ''15min''::interval * floor(date_part(''minute'', NEW.%I) / 15.0);' , v_control , v_control);
                v_current_partition_timestamp := date_trunc('hour', CURRENT_TIMESTAMP) +
                    '15min'::interval * floor(date_part('minute', CURRENT_TIMESTAMP) / 15.0);
            WHEN v_partition_interval = '30 mins' THEN
                v_trig_func := v_trig_func||format('v_partition_timestamp := date_trunc(''hour'', NEW.%I) +
                    ''30min''::interval * floor(date_part(''minute'', NEW.%I) / 30.0);' , v_control , v_control);
                v_current_partition_timestamp := date_trunc('hour', CURRENT_TIMESTAMP) +
                    '30min'::interval * floor(date_part('minute', CURRENT_TIMESTAMP) / 30.0);
            WHEN v_partition_interval = '1 hour' THEN
                v_trig_func := v_trig_func||format('v_partition_timestamp := date_trunc(''hour'', NEW.%I);', v_control);
                v_current_partition_timestamp := date_trunc('hour', CURRENT_TIMESTAMP);
             WHEN v_partition_interval = '1 day' THEN
                v_trig_func := v_trig_func||format('v_partition_timestamp := date_trunc(''day'', NEW.%I);', v_control);
                v_current_partition_timestamp := date_trunc('day', CURRENT_TIMESTAMP);
            WHEN v_partition_interval = '1 week' THEN
                v_trig_func := v_trig_func||format('v_partition_timestamp := date_trunc(''week'', NEW.%I);', v_control);
                v_current_partition_timestamp := date_trunc('week', CURRENT_TIMESTAMP);
            WHEN v_partition_interval = '1 month' THEN
                v_trig_func := v_trig_func||format('v_partition_timestamp := date_trunc(''month'', NEW.%I);', v_control);
                v_current_partition_timestamp := date_trunc('month', CURRENT_TIMESTAMP);
            WHEN v_partition_interval = '3 months' THEN
                v_trig_func := v_trig_func||format('v_partition_timestamp := date_trunc(''quarter'', NEW.%I);', v_control);
                v_current_partition_timestamp := date_trunc('quarter', CURRENT_TIMESTAMP);
            WHEN v_partition_interval = '1 year' THEN
                v_trig_func := v_trig_func||format('v_partition_timestamp := date_trunc(''year'', NEW.%I);', v_control);
                v_current_partition_timestamp := date_trunc('year', CURRENT_TIMESTAMP);
        END CASE;
    ELSE -- epoch is true
        CASE
            WHEN v_partition_interval = '15 mins' THEN
                v_trig_func := v_trig_func||format('v_partition_timestamp := date_trunc(''hour'', to_timestamp(NEW.%I)) +
                    ''15min''::interval * floor(date_part(''minute'', NEW.%I) / 15.0);' , v_control , v_control);
                v_current_partition_timestamp := date_trunc('hour', CURRENT_TIMESTAMP) +
                    '15min'::interval * floor(date_part('minute', CURRENT_TIMESTAMP) / 15.0);
            WHEN v_partition_interval = '30 mins' THEN
                v_trig_func := v_trig_func||format('v_partition_timestamp := date_trunc(''hour'', to_timestamp(NEW.%I)) +
                    ''30min''::interval * floor(date_part(''minute'', NEW.%I) / 30.0);' , v_control , v_control);
                v_current_partition_timestamp := date_trunc('hour', CURRENT_TIMESTAMP) +
                    '30min'::interval * floor(date_part('minute', CURRENT_TIMESTAMP) / 30.0);
            WHEN v_partition_interval = '1 hour' THEN
                v_trig_func := v_trig_func||format('v_partition_timestamp := date_trunc(''hour'', to_timestamp(NEW.%I));', v_control);
                v_current_partition_timestamp := date_trunc('hour', CURRENT_TIMESTAMP);
             WHEN v_partition_interval = '1 day' THEN
                v_trig_func := v_trig_func||format('v_partition_timestamp := date_trunc(''day'', to_timestamp(NEW.%I));', v_control);
                v_current_partition_timestamp := date_trunc('day', CURRENT_TIMESTAMP);
            WHEN v_partition_interval = '1 week' THEN
                v_trig_func := v_trig_func||format('v_partition_timestamp := date_trunc(''week'', to_timestamp(NEW.%I));', v_control);
                v_current_partition_timestamp := date_trunc('week', CURRENT_TIMESTAMP);
            WHEN v_partition_interval = '1 month' THEN
                v_trig_func := v_trig_func||format('v_partition_timestamp := date_trunc(''month'', to_timestamp(NEW.%I));', v_control);
                v_current_partition_timestamp := date_trunc('month', CURRENT_TIMESTAMP);
            WHEN v_partition_interval = '3 months' THEN
                v_trig_func := v_trig_func||format('v_partition_timestamp := date_trunc(''quarter'', to_timestamp(NEW.%I));', v_control);
                v_current_partition_timestamp := date_trunc('quarter', CURRENT_TIMESTAMP);
            WHEN v_partition_interval = '1 year' THEN
                v_trig_func := v_trig_func||format('v_partition_timestamp := date_trunc(''year'', to_timestamp(NEW.%I));', v_control);
                v_current_partition_timestamp := date_trunc('year', CURRENT_TIMESTAMP);
        END CASE;
    END IF;

    v_current_partition_name := @extschema@.check_name_length(v_parent_tablename, to_char(v_current_partition_timestamp, v_datetime_string), TRUE);
    v_next_partition_timestamp := v_current_partition_timestamp + v_partition_interval::interval;

    IF v_epoch = false THEN
        v_trig_func := v_trig_func ||format('
            IF NEW.%I >= %L AND NEW.%I < %L THEN '
                , v_control
                , v_current_partition_timestamp
                , v_control
                , v_next_partition_timestamp);
    ELSE
        v_trig_func := v_trig_func ||format('
            IF to_timestamp(NEW.%I) >= %L AND to_timestamp(NEW.%I) < %L THEN '
                , v_control
                , v_current_partition_timestamp
                , v_control
                , v_next_partition_timestamp);
    END IF;
        SELECT count(*) INTO v_count FROM pg_catalog.pg_tables WHERE schemaname = v_parent_schema::name AND tablename = v_current_partition_name::name;
        IF v_count > 0 THEN
            v_trig_func := v_trig_func || format('
                INSERT INTO %I.%I VALUES (NEW.*) %s; ', v_parent_schema, v_current_partition_name, v_upsert);
        ELSE
            v_trig_func := v_trig_func || '
                -- Child table for current values does not exist in this partition set, so write to parent
                RETURN NEW;';
        END IF;
    FOR i IN 1..v_optimize_trigger LOOP
        v_prev_partition_timestamp := v_current_partition_timestamp - (v_partition_interval::interval * i);
        v_next_partition_timestamp := v_current_partition_timestamp + (v_partition_interval::interval * i);
        v_final_partition_timestamp := v_next_partition_timestamp + (v_partition_interval::interval);
        v_prev_partition_name := @extschema@.check_name_length(v_parent_tablename, to_char(v_prev_partition_timestamp, v_datetime_string), TRUE);
        v_next_partition_name := @extschema@.check_name_length(v_parent_tablename, to_char(v_next_partition_timestamp, v_datetime_string), TRUE);

        -- Check that child table exist before making a rule to insert to them.
        -- Handles optimize_trigger being larger than premake (to go back in time further) and edge case of changing optimize_trigger immediately after running create_parent().
        SELECT count(*) INTO v_count FROM pg_catalog.pg_tables WHERE schemaname = v_parent_schema::name AND tablename = v_prev_partition_name::name;
        IF v_count > 0 THEN
            IF v_epoch = false THEN
                v_trig_func := v_trig_func ||format('
            ELSIF NEW.%I >= %L AND NEW.%I < %L THEN
                INSERT INTO %I.%I VALUES (NEW.*) %s;'
                    , v_control
                    , v_prev_partition_timestamp
                    , v_control
                    , v_prev_partition_timestamp + v_partition_interval::interval
                    , v_parent_schema
                    , v_prev_partition_name
                    , v_upsert);
            ELSE
                v_trig_func := v_trig_func ||format('
            ELSIF to_timestamp(NEW.%I) >= %L AND to_timestamp(NEW.%I) < %L THEN
                INSERT INTO %I.%I VALUES (NEW.*) %s;'
                    , v_control
                    , v_prev_partition_timestamp
                    , v_control
                    , v_prev_partition_timestamp + v_partition_interval::interval
                    , v_parent_schema
                    , v_prev_partition_name
                    , v_upsert);
            END IF;
        END IF;
        SELECT count(*) INTO v_count FROM pg_catalog.pg_tables WHERE schemaname = v_parent_schema::name AND tablename = v_next_partition_name::name;
        IF v_count > 0 THEN
            IF v_epoch = false THEN
                v_trig_func := v_trig_func ||format('
            ELSIF NEW.%I >= %L AND NEW.%I < %L THEN
                INSERT INTO %I.%I VALUES (NEW.*) %s;'
                    , v_control
                    , v_next_partition_timestamp
                    , v_control
                    , v_final_partition_timestamp
                    , v_parent_schema
                    , v_next_partition_name
                    , v_upsert);
            ELSE
                v_trig_func := v_trig_func ||format('
            ELSIF to_timestamp(NEW.%I) >= %L AND to_timestamp(NEW.%I) < %L THEN
                INSERT INTO %I.%I VALUES (NEW.*) %s;'
                    , v_control
                    , v_next_partition_timestamp
                    , v_control
                    , v_final_partition_timestamp
                    , v_parent_schema
                    , v_next_partition_name
                    , v_upsert);
            END IF;
        END IF;

    END LOOP;

    v_trig_func := v_trig_func||format('
            ELSE
                v_partition_name := @extschema@.check_name_length(%L, to_char(v_partition_timestamp, %L), TRUE);
                SELECT count(*) INTO v_count FROM pg_catalog.pg_tables WHERE schemaname = %L::name AND tablename = v_partition_name::name;
                IF v_count > 0 THEN
                    EXECUTE format(''INSERT INTO %%I.%%I VALUES($1.*) %s'', %L, v_partition_name) USING NEW;
                ELSE
                    RETURN NEW;
                END IF;
            END IF;'
            , v_parent_tablename
            , v_datetime_string
            , v_parent_schema
            , v_upsert
            , v_parent_schema);

    v_trig_func := v_trig_func ||'
        END IF;';

    IF v_trigger_return_null IS TRUE THEN
        v_trig_func := v_trig_func ||'
        RETURN NULL;';
    ELSE
        v_trig_func := v_trig_func ||'
        RETURN NEW;';
    END IF;

    IF v_trigger_exception_handling THEN
        v_trig_func := v_trig_func ||'
        EXCEPTION WHEN OTHERS THEN
            RAISE WARNING ''pg_partman insert into child table failed, row inserted into parent (%.%). ERROR: %'', TG_TABLE_SCHEMA, TG_TABLE_NAME, COALESCE(SQLERRM, ''unknown'');
            RETURN NEW;';
    END IF;
    v_trig_func := v_trig_func ||'
        END $t$;';

    EXECUTE v_trig_func;

    IF v_jobmon_schema IS NOT NULL THEN
        PERFORM update_step(v_step_id, 'OK', format('Added function for current time interval: %s to %s'
                                                        , v_current_partition_timestamp
                                                        , v_final_partition_timestamp-'1sec'::interval));
    END IF;

ELSIF v_type = 'time-custom' THEN

    v_trig_func := format('CREATE OR REPLACE FUNCTION %I.%I() RETURNS trigger LANGUAGE plpgsql AS $t$
        DECLARE
            v_child_schemaname  text;
            v_child_table       text;
            v_child_tablename   text;
            v_upsert            text;
        BEGIN
            '
        , v_parent_schema
        , v_function_name);

    IF v_epoch = false THEN
        v_trig_func := v_trig_func || format('

        SELECT c.child_table, p.upsert INTO v_child_table, v_upsert
        FROM @extschema@.custom_time_partitions c
        JOIN @extschema@.part_config p ON c.parent_table = p.parent_table
        WHERE c.partition_range @> NEW.%I
        AND c.parent_table = %L;'
        , v_control
        , v_parent_schema||'.'||v_parent_tablename);

    ELSE -- epoch true
        v_trig_func := v_trig_func || format('

        SELECT c.child_table, p.upsert INTO v_child_table, v_upsert
        FROM @extschema@.custom_time_partitions c
        JOIN @extschema@.part_config p ON c.parent_table = p.parent_table
        WHERE c.partition_range @> to_timestamp(NEW.%I)
        AND c.parent_table = %L;'
        , v_control
        , v_parent_schema||'.'||v_parent_tablename);

    END IF;

    v_trig_func := v_trig_func || '

        SELECT schemaname, tablename INTO v_child_schemaname, v_child_tablename
        FROM pg_catalog.pg_tables
        WHERE schemaname = split_part(v_child_table, ''.'', 1)::name
        AND tablename = split_part(v_child_table, ''.'', 2)::name;
        IF v_child_schemaname IS NOT NULL AND v_child_tablename IS NOT NULL THEN
            EXECUTE format(''INSERT INTO %I.%I VALUES ($1.*) %s'', v_child_schemaname, v_child_tablename, v_upsert) USING NEW;
        ELSE
            RETURN NEW;
        END IF;';

    IF v_trigger_return_null IS TRUE THEN
        v_trig_func := v_trig_func ||'
        RETURN NULL;';
    ELSE
        v_trig_func := v_trig_func ||'
        RETURN NEW;';
    END IF;

    IF v_trigger_exception_handling THEN
        v_trig_func := v_trig_func ||'
        EXCEPTION WHEN OTHERS THEN
            RAISE WARNING ''pg_partman insert into child table failed, row inserted into parent (%.%). ERROR: %'', TG_TABLE_SCHEMA, TG_TABLE_NAME, COALESCE(SQLERRM, ''unknown'');
            RETURN NEW;';
    END IF;
    v_trig_func := v_trig_func ||'
        END $t$;';

    EXECUTE v_trig_func;

    IF v_jobmon_schema IS NOT NULL THEN
        PERFORM update_step(v_step_id, 'OK', format('Added function for custom time table: %s', p_parent_table));
    END IF;

ELSE
    RAISE EXCEPTION 'ERROR: Invalid time partitioning type given: %', v_type;
END IF;

IF v_jobmon_schema IS NOT NULL THEN
    PERFORM close_job(v_job_id);
END IF;

EXECUTE format('SELECT set_config(%L, %L, %L)', 'search_path', v_old_search_path, 'false');

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 FUNCTION: %s'')', v_jobmon_schema, p_parent_table) INTO v_job_id;
                EXECUTE format('SELECT %I.add_step(%s, ''Partition function maintenance for table %s failed'')', 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 regression test 'incremental_sort': Write the SELECT query (example 17).

select * from (select * from t order by a) s order by a, b limit 33;

Explanation: Regression test for Incremental Sort in PostgreSQL core test suite.

SELECT count(*) FROM (select * from (select * from t order by a) s order by a, b limit 33) AS _sub;


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

create table ab_a1_b3 partition of ab_a1 for values in (3);

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


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

-- fdw_privs_are ( fdw, user, privileges[] )
CREATE OR REPLACE FUNCTION fdw_privs_are ( NAME, NAME, NAME[] )
RETURNS TEXT AS $$
    SELECT fdw_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 FDW ' || quote_ident($1)
    );
$$ LANGUAGE SQL;

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


Question: PostgreSQL Json: show example 16.

SELECT jdoc->'guid', jdoc->'name' FROM api WHERE jdoc @@ '$.tags[*] == "qui"';

Explanation: Example from PostgreSQL documentation on Json.


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

Explanation: DDL from PostgreSQL core regression test for Indexing.


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

DELETE FROM transition_table_level2
  WHERE level2_no BETWEEN 301 AND 305;

Explanation: DML from PostgreSQL core regression test for Plpgsql.


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

CREATE POLICY p2 ON s2 USING (x in (select a from s1 where b like '%22%'));

Explanation: DDL from PostgreSQL core regression test for Rowsecurity.


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

create temp table p2 partition of p for values from (10) to (20);

Explanation: DDL from PostgreSQL core regression test for Join.


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

CREATE USER MAPPING FOR public SERVER s10 OPTIONS (user 'secret');

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


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

SELECT count(*) FROM testjsonb WHERE j = '{"pos":98, "line":371, "node":"CBA", "indexed":true}';

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

SELECT count(*) FROM (SELECT count(*) FROM testjsonb WHERE j = '{"pos":98, "line":371, "node":"CBA", "indexed":true}') AS _sub;


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

CREATE UNIQUE INDEX num_exp_div_idx ON num_exp_div (id1, id2);

Explanation: DDL from PostgreSQL core regression test for Numeric.