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

/*
 * Check for consistent data in part_config_sub table. Was unable to get this working properly as either a constraint or trigger.
 * Would either delay raising an error until the next write (which I cannot predict) or disallow future edits to update a sub-partition set's configuration.
 * This is called by run_maintainance() and at least provides a consistent way to check that I know will run.
 * If anyone can get a working constraint/trigger, please help!
*/
CREATE FUNCTION @extschema@.check_subpart_sameconfig(p_parent_table text)
    RETURNS TABLE (sub_partition_type text
        , sub_control text
        , sub_partition_interval text
        , sub_constraint_cols text[]
        , sub_premake int
        , sub_inherit_fk boolean
        , sub_retention text
        , sub_retention_schema text
        , sub_retention_keep_table boolean
        , sub_retention_keep_index boolean
        , sub_use_run_maintenance boolean
        , sub_epoch boolean
        , sub_optimize_trigger int
        , sub_optimize_constraint int
        , sub_infinite_time_partitions boolean
        , sub_jobmon boolean
        , sub_trigger_exception_handling boolean
        , sub_upsert text
        , sub_trigger_return_null boolean)
    LANGUAGE sql STABLE SECURITY DEFINER
    SET search_path = @extschema@,pg_temp
AS $$

    WITH parent_info AS (
        SELECT c1.oid
        FROM pg_catalog.pg_class c1
        JOIN pg_catalog.pg_namespace n1 ON c1.relnamespace = n1.oid
        WHERE n1.nspname = split_part(p_parent_table, '.', 1)::name
        AND c1.relname = split_part(p_parent_table, '.', 2)::name
    )
    , child_tables AS (
        SELECT n.nspname||'.'||c.relname AS tablename
        FROM pg_catalog.pg_inherits h
        JOIN pg_catalog.pg_class c ON c.oid = h.inhrelid
        JOIN pg_catalog.pg_namespace n ON c.relnamespace = n.oid
        JOIN parent_info pi ON h.inhparent = pi.oid
    )
    -- Column order here must match the RETURNS TABLE definition
    SELECT DISTINCT a.sub_partition_type
        , a.sub_control
        , a.sub_partition_interval
        , a.sub_constraint_cols
        , a.sub_premake
        , a.sub_inherit_fk
        , a.sub_retention
        , a.sub_retention_schema
        , a.sub_retention_keep_table
        , a.sub_retention_keep_index
        , a.sub_use_run_maintenance
        , a.sub_epoch
        , a.sub_optimize_trigger
        , a.sub_optimize_constraint
        , a.sub_infinite_time_partitions
        , a.sub_jobmon
        , a.sub_trigger_exception_handling
        , a.sub_upsert
        , a.sub_trigger_return_null
    FROM @extschema@.part_config_sub a
    JOIN child_tables b on a.sub_parent = b.tablename;
$$;

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


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

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

SELECT count(*) FROM (select interval '-2562047788.01521550222 hours') AS _sub;


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

select to_tsvector('simple', 'x y q') @@ '(!x | !y) <-> y <-> q' AS "true";

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

SELECT count(*) FROM (select to_tsvector('simple', 'x y q') @@ '(!x | !y) <-> y <-> q' AS "true") AS _sub;


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

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

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


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

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

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


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

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

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


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

-- Nested subtransactions

CREATE FUNCTION subtransaction_nested_test(swallow boolean = 'f') RETURNS text
AS $$
spi_exec "INSERT INTO subtransaction_tbl VALUES (1)"
subtransaction {
    spi_exec "INSERT INTO subtransaction_tbl VALUES (2)"
    if [catch {
        subtransaction {
            spi_exec "INSERT INTO subtransaction_tbl VALUES (3)"
            spi_exec "error"
        }
    } errormsg] {
        if {$1 != "t"} {
            error $errormsg $::errorInfo $::errorCode
        }
        elog NOTICE "Swallowed $errormsg"
    }
}
return "ok"
$$ LANGUAGE pltcl;

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


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

INSERT INTO temporal_mltrng (id, valid_at) VALUES ('[1,2)', datemultirange(daterange('2005-01-01', '2006-01-01'))) ON CONFLICT ON CONSTRAINT temporal_mltrng_pk DO UPDATE SET id = EXCLUDED.id + '[2,3)';

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


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

SELECT js FROM jsonb_populate_record(NULL::jsbrec, '{"js": [123, "123", null, {"key": "value"}]}') q;

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

SELECT count(*) FROM (SELECT js FROM jsonb_populate_record(NULL::jsbrec, '{"js": [123, "123", null, {"key": "value"}]}') q) AS _sub;


Question: Show a SQL definition from the citus project (multi_partitioning, item 5).

--
-- Distributed Partitioned Table Creation Tests
--

-- 1-) Distributing partitioned table
-- create partitioned table
CREATE TABLE partitioning_test(id int, time date) PARTITION BY RANGE (time);

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


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

CREATE UNIQUE INDEX func_index_index on func_index_heap ((f1 || f2) text_ops);

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


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

SELECT to_json(a) AS a, JSON_OBJECTAGG(k : v ABSENT ON NULL WITH UNIQUE KEYS)
   OVER (ORDER BY k)
FROM (VALUES (1,1), (1,null), (2,2)) a(k,v);

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

SELECT count(*) FROM (SELECT to_json(a) AS a, JSON_OBJECTAGG(k : v ABSENT ON NULL WITH UNIQUE KEYS)
   OVER (ORDER BY k)
FROM (VALUES (1,1), (1,null), (2,2)) a(k,v)) AS _sub;


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

SELECT * FROM test_bpchar WHERE i='abc  ' ORDER BY i;

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


Question: pgTAP test for Functap (assertion 216).

/****************************************************************************/
-- Test is_aggregate() and isnt_aggregate().

-- is_aggregate ( NAME, NAME, NAME[], TEXT )
-- isnt_aggregate ( NAME, NAME, NAME[], TEXT )
SELECT * FROM check_test(
    is_aggregate( 'public', 'tap_accum', ARRAY[etype()], 'whatever' ),
    true,
    'is_aggregate(schema, func, arg, desc)',
    'whatever',
    ''
);

Explanation: SQL assertion from pgTAP test suite for Functap.


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

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


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

SELECT JSON_EXISTS(jsonb '{"a": 1, "b": 2}', '$.* ? (@ > $x && @ < $y)' PASSING 0 AS x, 1 AS y);

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

SELECT count(*) FROM (SELECT JSON_EXISTS(jsonb '{"a": 1, "b": 2}', '$.* ? (@ > $x && @ < $y)' PASSING 0 AS x, 1 AS y)) AS _sub;


Question: Show an example of PostgreSQL ALTER CONVERSION (example 1).

ALTER CONVERSION iso_8859_1_to_utf8 RENAME TO latin1_to_unicode;

Explanation: PostgreSQL ALTER CONVERSION command.


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

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

SELECT count(*) FROM (SELECT stddev_pop(3.0::float4), stddev_samp(4.0::float4)) AS _sub;


Question: Show a SQL definition from the citus project (multi_sql_function, item 4).

CREATE FUNCTION sql_test_no_2() RETURNS bigint AS '
	SELECT
		count(*)
	FROM
		orders, lineitem
	WHERE
		o_orderkey = l_orderkey;


Question: Write the DML statement from PostgreSQL regression test 'stats_rewrite' (example 32).

Explanation: DML from PostgreSQL core regression test for Stats Rewrite.


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

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


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

SELECT *
FROM
	(VALUES ('1'), ('"err"')) vals(js)
		LEFT OUTER JOIN
	JSON_TABLE(vals.js::jsonb, '$' COLUMNS (a int PATH '$' ERROR ON ERROR)) jt
		ON true;

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

SELECT count(*) FROM (SELECT *
FROM
	(VALUES ('1'), ('"err"')) vals(js)
		LEFT OUTER JOIN
	JSON_TABLE(vals.js::jsonb, '$' COLUMNS (a int PATH '$' ERROR ON ERROR)) jt
		ON true) AS _sub;


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

SELECT
	JSON_OBJECTAGG(i: i),
--	JSON_OBJECTAGG(i VALUE i),
--	JSON_OBJECTAGG(KEY i VALUE i),
	JSON_OBJECTAGG(i: i RETURNING jsonb)
FROM
	generate_series(1, 5) i;

SELECT count(*) FROM (SELECT
	JSON_OBJECTAGG(i: i),
--	JSON_OBJECTAGG(i VALUE i),
--	JSON_OBJECTAGG(KEY i VALUE i),
	JSON_OBJECTAGG(i: i RETURNING jsonb)
FROM
	generate_series(1, 5) i) AS _sub;


Question: PostgreSQL regression test 'pg_dependencies': Write the SELECT query (example 79).

SELECT '[{"attributes" : [2,3], "dependency": 4, "degree": 1.000, "degree": 1.000}]'::pg_dependencies;

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

SELECT count(*) FROM (SELECT '[{"attributes" : [2,3], "dependency": 4, "degree": 1.000, "degree": 1.000}]'::pg_dependencies) AS _sub;


Question: Write the DDL statement from PostgreSQL regression test 'create_role' (example 33).

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


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

SELECT c1.f1 AS circle, p1.f1 AS point, (p1.f1 <-> c1.f1) AS distance
   FROM CIRCLE_TBL c1, POINT_TBL p1
   WHERE (p1.f1 <-> c1.f1) > 0
   ORDER BY distance, area(c1.f1), p1.f1[0];

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

SELECT count(*) FROM (SELECT c1.f1 AS circle, p1.f1 AS point, (p1.f1 <-> c1.f1) AS distance
   FROM CIRCLE_TBL c1, POINT_TBL p1
   WHERE (p1.f1 <-> c1.f1) > 0
   ORDER BY distance, area(c1.f1), p1.f1[0]) AS _sub;


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

-- tablespace_privs_are ( tablespace, user, privileges[], description )
CREATE OR REPLACE FUNCTION tablespace_privs_are ( NAME, NAME, NAME[], TEXT )
RETURNS TEXT AS $$
DECLARE
    grants TEXT[] := _get_tablespaceprivs( $2, quote_ident($1) );
BEGIN
    IF grants[1] = 'undefined_tablespace' THEN
        RETURN ok(FALSE, $4) || E'\n' || diag(
            '    Tablespace ' || quote_ident($1) || ' does not exist'
        );
    ELSIF grants[1] = 'undefined_role' THEN
        RETURN ok(FALSE, $4) || E'\n' || diag(
            '    Role ' || quote_ident($2) || ' does not exist'
        );
    END IF;
    RETURN _assets_are('privileges', grants, $3, $4);
END;
$$ LANGUAGE plpgsql;

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


Question: Write the DML statement from PostgreSQL regression test 'update' (example 248).

UPDATE list_parted set b = c + a WHERE a = 2;

Explanation: DML from PostgreSQL core regression test for Update.


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

$$;

CALL ptest4c(NULL);

DROP PROCEDURE ptest4a, ptest4c;

-- named and default parameters

CREATE OR REPLACE PROCEDURE ptest5(a int, b text, c int default 100)
LANGUAGE SQL
AS $$
INSERT INTO cp_test VALUES(a, b);

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


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

SELECT * FROM check_estimated_rows('SELECT * FROM mcv_lists WHERE b = ''x'' OR d = ''x''');

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

SELECT count(*) FROM (SELECT * FROM check_estimated_rows('SELECT * FROM mcv_lists WHERE b = ''x'' OR d = ''x''')) AS _sub;


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

DROP TRIGGER parent_update_trig ON range_parted;

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


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

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


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

SELECT citext_pattern_cmp('a'::citext, 'B'::citext) < 0 AS true;

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


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

CREATE SEQUENCE sequence_testx AS smallint MINVALUE -100000;

Explanation: DDL from PostgreSQL core regression test for Sequence.


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

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

SELECT count(*) FROM (SELECT parse_ident(' aaa . ')) AS _sub;


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

SELECT 1 FROM postgres_fdw_disconnect('loopback2');

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


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

create view v1 as select * from tt2 natural join tt3;

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


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

Explanation: DDL from PostgreSQL core regression test for Domain.


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

create domain ddef5 numeric(8,2) NOT NULL DEFAULT '12.12';


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

$$ language plpgsql;

select compos();

-- ... but this does
create or replace function compos() returns compostype as $$
begin
  return (1, 'hello')::compostype;

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


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

DELETE FROM fk_notpartitioned_pk WHERE b = 142857;

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


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

SELECT JSON_QUERY('"a"', '$.a'  RETURNING int[] DEFAULT (SELECT '{1}')::oid[]::int[] ON ERROR);

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

SELECT count(*) FROM (SELECT JSON_QUERY('"a"', '$.a'  RETURNING int[] DEFAULT (SELECT '{1}')::oid[]::int[] ON ERROR)) AS _sub;


Question: PostgreSQL Xfunc: show example 21.

SELECT anyleast('abc'::text, 'ABC' COLLATE "C");

Explanation: Example from PostgreSQL documentation on Xfunc.


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

SELECT name, 'a' = name AS t      FROM try where name = 'a';


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

INSERT INTO measurement VALUES (1, '2006-03-27', 15, 40);

Explanation: DML from PostgreSQL core regression test for Merge.


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

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


Question: Write the DDL statement from PostgreSQL regression test 'foreign_key' (example 243).

CREATE TABLE FKTABLE (
  tid int, id int,
  fk_id_del_set_null int,
  fk_id_del_set_default int DEFAULT 0,
  FOREIGN KEY (tid, fk_id_del_set_null) REFERENCES PKTABLE ON DELETE SET NULL (fk_id_del_set_null),
  -- this tests handling of duplicate entries in SET DEFAULT column list
  FOREIGN KEY (tid, fk_id_del_set_default) REFERENCES PKTABLE ON DELETE SET DEFAULT (fk_id_del_set_default, fk_id_del_set_default)
);

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


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

Explanation: DML from PostgreSQL core regression test for Path.


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

\set ON_ERROR_STOP 1

-- Test with UNIQUE index on multiple columns instead of PRIMARY KEY constraint
CREATE TABLE upsert_test_unique(time timestamp, temp float, color text);

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


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

select jsonb_path_query('[null, 1, "a\b", "a\\b", "^a\\b$"]', 'lax $[*] ? (@ like_regex "^a\\B$" flag "q")');

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

SELECT count(*) FROM (select jsonb_path_query('[null, 1, "a\b", "a\\b", "^a\\b$"]', 'lax $[*] ? (@ like_regex "^a\\B$" flag "q")')) AS _sub;


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

ALTER EXTENSION pgtap ADD FUNCTION set_eq( TEXT, TEXT, TEXT );

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


Question: PL/pgSQL test: Plpgsql Call (example 52).

CREATE TRIGGER t1 BEFORE INSERT ON test1 EXECUTE PROCEDURE triggerfunc1();

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


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

select jsonb '{"a": 1, "b": [1, 2]}' @? 'lax $.keyvalue().key';

SELECT count(*) FROM (select jsonb '{"a": 1, "b": [1, 2]}' @? 'lax $.keyvalue().key') AS _sub;


Question: pgTAP test for Hastap (assertion 3).

CREATE TABLE public.sometab(
    id      INT NOT NULL PRIMARY KEY,
    name    TEXT DEFAULT '',
    numb    NUMERIC(10, 2),
    "myInt" NUMERIC(8)
);

Explanation: SQL assertion from pgTAP test suite for Hastap.


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

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

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


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

SELECT to_timestamp('2015-02-11 86000', 'YYYY-MM-DD SSSSS');  -- ok
SELECT to_timestamp('2015-02-11 86400', 'YYYY-MM-DD SSSSS');

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

SELECT count(*) FROM (SELECT to_timestamp('2015-02-11 86000', 'YYYY-MM-DD SSSSS');  -- ok
SELECT to_timestamp('2015-02-11 86400', 'YYYY-MM-DD SSSSS')) AS _sub;


Question: PostgreSQL Indices: show example 33.

SELECT target FROM tests WHERE subject = 'some-subject' AND success;

Explanation: Example from PostgreSQL documentation on Indices.


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

SELECT * FROM multiout_table_type_setof('str', 'f', 7);

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


Question: Write the DDL statement from PostgreSQL regression test 'updatable_views' (example 49).

CREATE VIEW rw_view1 AS
  SELECT *, 'Const' AS c, (SELECT concat('b: ', b)) AS d FROM base_tbl WHERE a>0;

Explanation: DDL from PostgreSQL core regression test for Updatable Views.


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

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


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

--
-- bt_metap()
--
CREATE FUNCTION bt_metap(IN relname text,
    OUT magic int4,
    OUT version int4,
    OUT root int4,
    OUT level int4,
    OUT fastroot int4,
    OUT fastlevel int4)
AS 'MODULE_PATHNAME', 'bt_metap'
LANGUAGE C STRICT PARALLEL SAFE;


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

CREATE OPERATOR @#@ (
   rightarg = int8,		-- prefix
   procedure = factorial
);

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


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

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

SELECT count(*) FROM (SELECT pg_stat_get_xact_function_calls(:stats_test_func2_oid)) AS _sub;


Question: PL/pgSQL test: Plpgsql Misc (example 2).

\sf test1
\sf test2

-- Test %TYPE and %ROWTYPE error cases
create table misc_table(f1 int);

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


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

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


Question: pgTAP test for Functap (assertion 364).

SELECT * FROM check_test(
    volatility_is( 'public', 'pet', '{}'::name[], 'stable', 'whatever' ),
    true,
    'function_volatility(schema, func, 0 args, stable, desc)',
    'whatever',
    ''
);

Explanation: SQL assertion from pgTAP test suite for Functap.


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

CREATE INDEX brinidx_bloom ON brintest_bloom USING brin (
	byteacol bytea_bloom_ops,
	charcol char_bloom_ops,
	namecol name_bloom_ops,
	int8col int8_bloom_ops,
	int2col int2_bloom_ops,
	int4col int4_bloom_ops,
	textcol text_bloom_ops,
	oidcol oid_bloom_ops,
	float4col float4_bloom_ops,
	float8col float8_bloom_ops,
	macaddrcol macaddr_bloom_ops,
	inetcol inet_bloom_ops,
	cidrcol inet_bloom_ops,
	bpcharcol bpchar_bloom_ops,
	datecol date_bloom_ops,
	timecol time_bloom_ops,
	timestampcol timestamp_bloom_ops,
	timestamptzcol timestamptz_bloom_ops,
	intervalcol interval_bloom_ops,
	timetzcol timetz_bloom_ops,
	numericcol numeric_bloom_ops,
	uuidcol uuid_bloom_ops,
	lsncol pg_lsn_bloom_ops
) with (pages_per_range = 1);

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


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

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

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


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

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

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


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

SELECT * FROM test_int8 WHERE i<=1::int8 ORDER BY i;

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


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

CREATE VIEW temporal3 AS SELECT * FROM t1 LEFT JOIN tt ON t1.num = tt.num2;

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


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

CREATE TABLE clstrpart3 PARTITION OF clstrpart DEFAULT PARTITION BY RANGE (a);

Explanation: DDL from PostgreSQL core regression test for Cluster.


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

SELECT '[{"attributes": [1,2], "dependency": 2, "degree": 1}]' ::pg_dependencies;

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

SELECT count(*) FROM (SELECT '[{"attributes": [1,2], "dependency": 2, "degree": 1}]' ::pg_dependencies) AS _sub;


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

create or replace trigger my_trig
  after insert on parted_trig_1
  for each row execute procedure funcB();  -- should fail
insert into parted_trig (a) values (50);

Explanation: DDL from PostgreSQL core regression test for Triggers.


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

$$ LANGUAGE plperl;

SELECT myfuncs();

-- make sure we can't return an array as a scalar
CREATE OR REPLACE FUNCTION text_arrayref() RETURNS text AS $$
	return ['array'];

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


Question: Show a SQL definition from the citus project (modification_correctness, item 3).

CREATE TABLE test(k int, a int, b int, c int unique, d int, e int);

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


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

CREATE TABLE stats_ext_tbl (id INT PRIMARY KEY GENERATED BY DEFAULT AS IDENTITY, col TEXT);

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


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

SELECT pg_get_object_address('event trigger', '{one,two}', '{}');

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

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


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

SELECT * FROM test_enum WHERE i<'g'::rainbow ORDER BY i;


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

select pct, count(unique1) from
  (values (0),(100)) v(pct),
  lateral (select * from tenk1 tablesample bernoulli (pct)) ss
  group by pct;

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

SELECT count(*) FROM (select pct, count(unique1) from
  (values (0),(100)) v(pct),
  lateral (select * from tenk1 tablesample bernoulli (pct)) ss
  group by pct) AS _sub;


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

SELECT * FROM ltreetest WHERE t ~ '23.*.2' order by t asc;

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


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

SELECT * FROM header_doesnt_match; -- ERROR

-- test multi-line header
\set filename :abs_srcdir '/data/multiline_header.csv'
CREATE FOREIGN TABLE multi_header (a int, b text) SERVER file_server
OPTIONS (format 'csv', filename :'filename', header '2');

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


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

select conname, contype, conrelid::regclass, conindid::regclass, conkey
  from pg_constraint where conrelid::regclass::text like 'idxpart%'
  order by conrelid::regclass::text, conname;

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

SELECT count(*) FROM (select conname, contype, conrelid::regclass, conindid::regclass, conkey
  from pg_constraint where conrelid::regclass::text like 'idxpart%'
  order by conrelid::regclass::text, conname) AS _sub;


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

select interval '2147483647 months 0.1 centuries';

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

SELECT count(*) FROM (select interval '2147483647 months 0.1 centuries') AS _sub;


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

create table fktable2 (d int, e int, foreign key (d, e) references pktable2);

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


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

insert into dcomptable (d1[1].r) values(11);

Explanation: DML from PostgreSQL core regression test for Domain.


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

CREATE FUNCTION fail_drop_table() RETURNS event_trigger AS $fdt$
    BEGIN
        RAISE 'illegal value';


Question: Write the DML statement from PostgreSQL regression test 'stats_ext' (example 511).

INSERT INTO mcv_lists (a, b, c, filler1)
     SELECT i, i, i, i FROM generate_series(1,1000) s(i);

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


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

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

SELECT count(*) FROM (select jsonb_path_query('{}', '$.time_tz()')) AS _sub;


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

select (fn).first, substr((fn).last, 1, 20), length((fn).last) from people;

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

SELECT count(*) FROM (select (fn).first, substr((fn).last, 1, 20), length((fn).last) from people) AS _sub;


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

select websearch_to_tsquery('english', 'pg_class pg"');

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

SELECT count(*) FROM (select websearch_to_tsquery('english', 'pg_class pg"')) AS _sub;


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

SELECT is_normalized('abc', 'def');  -- run-time error;

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

SELECT count(*) FROM (SELECT is_normalized('abc', 'def');  -- run-time error) AS _sub;


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

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


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

create rule rtest_nothn_r3 as on insert to rtest_nothn2
	where new.a >= 100 do instead
	insert into rtest_nothn3 values (new.a, new.b);

Explanation: DDL from PostgreSQL core regression test for Rules.


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

INSERT INTO new_measurement VALUES (2, '2006-02-10', 20, 20);

Explanation: DML from PostgreSQL core regression test for Merge.


Question: pgTAP test for Runjusttests (assertion 11).

CREATE OR REPLACE FUNCTION whatever."test ident"() RETURNS SETOF TEXT AS $$
BEGIN
    RETURN NEXT pass( 'ident' );
    RETURN NEXT pass( 'ident 2' );
END;
$$ LANGUAGE plpgsql;

Explanation: SQL assertion from pgTAP test suite for Runjusttests.


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

SELECT count(*) FROM timestamptztmp WHERE a  = '2018-12-18 10:59:54 GMT+4'::timestamptz;

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


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

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


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

INSERT INTO a_star (class, a) VALUES ('a', 1);

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


Question: Write the DDL statement from PostgreSQL regression test 'generated_virtual' (example 14).

CREATE TABLE gtest2 (a int, b text GENERATED ALWAYS AS (a || ' sec') VIRTUAL);

Explanation: DDL from PostgreSQL core regression test for Generated Virtual.


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

SELECT to_tsquery('english', '(s <-> (a <-> 1)) <-> 2');

SELECT count(*) FROM (SELECT to_tsquery('english', '(s <-> (a <-> 1)) <-> 2')) AS _sub;


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

UPDATE arrtest
  SET a[1:2] = '{16,25}'
  WHERE NOT a = '{}'::_int2;

Explanation: DML from PostgreSQL core regression test for Arrays.


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

INSERT INTO department VALUES (0, NULL, 'ROOT');

Explanation: DML from PostgreSQL core regression test for With.


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

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

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

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


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

select definition from pg_views where viewname='vw_ord';

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

SELECT count(*) FROM (select definition from pg_views where viewname='vw_ord') AS _sub;


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

Explanation: DML from PostgreSQL core regression test for Uuid.


Question: pgTAP test for Policy (assertion 52).

SELECT * FROM check_test(
    policy_cmd_is( 'public', 'passwd', 'daemon_insert'::NAME, 'delete' ),
    false,
    'policy_cmd_is(schema, table, policy, command) for INSERT should fail',
    'Policy daemon_insert for table public.passwd should apply to DELETE command',
    '        have: INSERT
        want: DELETE'
);

Explanation: SQL assertion from pgTAP test suite for Policy.


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

SELECT random('1979-02-08 +05'::timestamptz,'1979-02-08 +05'::timestamptz) AS random_timestamptz_empty_range;

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

SELECT count(*) FROM (SELECT random('1979-02-08 +05'::timestamptz,'1979-02-08 +05'::timestamptz) AS random_timestamptz_empty_range) AS _sub;


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

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

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


Question: Write the DML statement from PostgreSQL regression test 'stats' (example 20).

INSERT INTO trunc_stats_test1 DEFAULT VALUES;

Explanation: DML from PostgreSQL core regression test for Stats.


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

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

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

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


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

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

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


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

create statistics (ndistinct) on a, b from stts_t1;

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


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

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

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


Question: pgTAP test for Usergroup (assertion 20).

SELECT * FROM check_test(
    has_group('aoijaoisjfaoidfjaisjdfosjf', 'desc'),
    false,
    'has_group(nonexistent group, desc)',
    'desc',
    ''
);

Explanation: SQL assertion from pgTAP test suite for Usergroup.


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

SELECT test_mblen_func('pg_mblen_range', 'UTF8', truncated, 3)
FROM regress_encoding;

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

SELECT count(*) FROM (SELECT test_mblen_func('pg_mblen_range', 'UTF8', truncated, 3)
FROM regress_encoding) AS _sub;


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

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


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

Explanation: DDL from PostgreSQL core regression test for Equivclass.


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

-- explicit spec of return type is OK
CREATE OR REPLACE FUNCTION rngfunc(in f1 int, out f2 int) RETURNS int
AS 'select $1+1' LANGUAGE sql;

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


Question: Show a SQL definition from the timescaledb project (test_tss_callbacks, item 3).

CREATE OR REPLACE FUNCTION test.teardown_tss_hook_v1() RETURNS VOID
    AS :MODULE_PATHNAME, 'ts_teardown_tss_hook_v1' LANGUAGE C VOLATILE;

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


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

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


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

CREATE TRIGGER evtrg_nontemp_trig
  BEFORE INSERT ON evtrg_nontemp_table
  EXECUTE FUNCTION event_trigger_dummy_trigger();

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


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

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

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


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

SELECT '[{"attributes" : [2,3], "dependency" : "\ud83d", "degree": 0.250}]'::pg_dependencies;

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

SELECT count(*) FROM (SELECT '[{"attributes" : [2,3], "dependency" : "\ud83d", "degree": 0.250}]'::pg_dependencies) AS _sub;


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

SELECT encrypt('\xffffffffffffffff', '\x0000000000000000', 'bf-ecb/pad:none');

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


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

SELECT * FROM pg_input_error_info('no_such_dictionary', 'regdictionary');

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

SELECT count(*) FROM (SELECT * FROM pg_input_error_info('no_such_dictionary', 'regdictionary')) AS _sub;


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

Explanation: DML from PostgreSQL core regression test for Rules.


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

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

SELECT count(*) FROM (SELECT pg_input_is_valid('(1,2),-1', 'circle')) AS _sub;


Question: Show an example of PostgreSQL ALTER FOREIGN DATA WRAPPER (example 2).

ALTER FOREIGN DATA WRAPPER dbi VALIDATOR bob.myvalidator;

Explanation: PostgreSQL ALTER FOREIGN DATA WRAPPER command.


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

SELECT count(*) FROM int2tmp WHERE a >= 237;

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


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

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

SELECT count(*) FROM (SELECT regexp_split_to_array('123456','')) AS _sub;


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

CREATE UNIQUE INDEX unique_idx1 ON unique_tbl (i) NULLS DISTINCT;

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


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

CREATE OR REPLACE FUNCTION @extschema@.interpolate(value BIGINT,prev RECORD=NULL,next RECORD=NULL) RETURNS BIGINT
	AS '@MODULE_PATHNAME@', 'ts_gapfill_marker' LANGUAGE C VOLATILE PARALLEL SAFE;


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

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

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

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


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

SELECT * FROM pg_input_error_info('{"a": 1}', 'pg_dependencies');

SELECT count(*) FROM (SELECT * FROM pg_input_error_info('{"a": 1}', 'pg_dependencies')) AS _sub;


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

select(select (select grouping(a,b) from (values (1)) v2(c)) from (values (1,2)) v1(a,b) group by (a,b)) from (values(6,7)) v3(e,f) GROUP BY ROLLUP((e+1),(f+1));

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

SELECT count(*) FROM (select(select (select grouping(a,b) from (values (1)) v2(c)) from (values (1,2)) v1(a,b) group by (a,b)) from (values(6,7)) v3(e,f) GROUP BY ROLLUP((e+1),(f+1))) AS _sub;


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

ALTER FUNCTION foo_from_bar(TEXT, TEXT, TEXT)
  SUPPORT test_inline_in_from_support_func;

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


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

select array_agg(nullif(ten, 4)) from (select ten from tenk1 where unique1 < 15 order by unique1) ss;

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

SELECT count(*) FROM (select array_agg(nullif(ten, 4)) from (select ten from tenk1 where unique1 < 15 order by unique1) ss) AS _sub;


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

SELECT JSON_VALUE(jsonb '1', 'lax $.a' DEFAULT '2' ON EMPTY);

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

SELECT count(*) FROM (SELECT JSON_VALUE(jsonb '1', 'lax $.a' DEFAULT '2' ON EMPTY)) AS _sub;


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

CREATE OR REPLACE FUNCTION plperl_array_of_rows(foo[]) RETURNS TEXT AS $$
	my $array_arg = shift;
	my $result = "";

	for my $row_ref (@$array_arg) {
		die "not a hash reference" unless (ref $row_ref eq "HASH");
			$result .= $row_ref->{bar}." items of ".$row_ref->{baz}.";";
	}
	return $result .' '. $array_arg;
$$ LANGUAGE plperl;

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


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

DELETE FROM foo WHERE f1 = 4 RETURNING old.*,new.*, *;

Explanation: DML from PostgreSQL core regression test for Returning.


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

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

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


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

SELECT relispopulated FROM pg_class WHERE oid = 'mvtest_tm'::regclass;

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

SELECT count(*) FROM (SELECT relispopulated FROM pg_class WHERE oid = 'mvtest_tm'::regclass) AS _sub;


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

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


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

Explanation: Regression test for Generated Stored in PostgreSQL core test suite.

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


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

Explanation: DML from PostgreSQL core regression test for Numeric.


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

end $$
language plpgsql
set work_mem = '1MB';

select myfunc(0), current_setting('work_mem');

alter function myfunc(int) reset all;

select myfunc(0), current_setting('work_mem');

set work_mem = '3MB';

-- but SET isn't
create or replace function myfunc(int) returns text as $$
begin
  set work_mem = '2MB';

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


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

CREATE FUNCTION brintest_func() RETURNS int LANGUAGE sql IMMUTABLE RETURN 0;

Explanation: DDL from PostgreSQL core regression test for Brin.


Question: PostgreSQL regression test 'btree_index': Write the SELECT query (example 80).

select * from btree_bpchar where f1 like 'foo';

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

SELECT count(*) FROM (select * from btree_bpchar where f1 like 'foo') AS _sub;


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

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

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

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


Question: PostgreSQL Plpgsql: show example 85.

SELECT * FROM cs_parse_url('http://foobar.com/query.cgi?baz');

Explanation: Example from PostgreSQL documentation on Plpgsql.


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

-- Tests for functions returning void
SELECT test_void_func1(), test_void_func1() IS NULL AS "is null";

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


Question: pgTAP test for Resultset (assertion 287).

SELECT * FROM check_test(
    results_eq(
        'SELECT id, name FROM dupes LIMIT 2',
        'SELECT id, name FROM dupes LIMIT 2'
    ),
    true,
    'results_eq(nulls, nulls)',
    '',
    ''
);

Explanation: SQL assertion from pgTAP test suite for Resultset.


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

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

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


Question: Show a SQL definition from the citus project (foreign_key_to_reference_table, item 12).

-- we still do not support update/delete operations through foreign constraints if the foreign key includes the distribution column
-- All should fail
CREATE TABLE referencing_table(id int, ref_id int);

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


Question: pgTAP test for Proctap (assertion 13).

SELECT * FROM check_test(
    is_procedure( 'procschema', 'afunc', '{}'::name[], 'whatever' ),
    false,
    'is_procedure(schema, func, noargs, desc)',
    'whatever',
    ''
);

Explanation: SQL assertion from pgTAP test suite for Proctap.


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

insert into rem1(f2) values('hi remote');

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


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

create view v3 as select * from tt2 join tt3 using (b,c) full join tt4 using (b);

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


Question: Show a SQL definition from the postgrest project (jwt, item 9).

CREATE OR REPLACE FUNCTION jwt.sign(payload json, secret text, algorithm text DEFAULT 'HS256')
RETURNS text LANGUAGE sql AS $$
WITH
  header AS (
    SELECT jwt.url_encode(convert_to('{"alg":"' || algorithm || '","typ":"JWT"}', 'utf8'))
    ),
  payload AS (
    SELECT jwt.url_encode(convert_to(payload::text, 'utf8'))
    ),
  signables AS (
    SELECT (SELECT * FROM header) || '.' || (SELECT * FROM payload)
    )
SELECT
    (SELECT * FROM signables)
    || '.' ||
    jwt.algorithm_sign((SELECT * FROM signables), secret, algorithm);
$$;

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


Question: Show a SQL definition from the pg_partman project (pg_partman--2.3.2--2.3.3, item 23).

/*
 * Function to list all child partitions in a set in logical order.
 */
CREATE OR REPLACE FUNCTION show_partitions (p_parent_table text, p_order text DEFAULT 'ASC') RETURNS TABLE (partition_schemaname text, partition_tablename text)
    LANGUAGE plpgsql STABLE SECURITY DEFINER
    AS $$
DECLARE

v_datetime_string       text;
v_parent_schema         text;
v_parent_tablename      text;
v_partition_interval    text;
v_quarter               text;
v_type                  text;
v_year                  text;

BEGIN

IF upper(p_order) NOT IN ('ASC', 'DESC') THEN
    RAISE EXCEPTION 'p_order paramter must be one of the following values: ASC, DESC';
END IF;

SELECT partition_type
    , partition_interval
    , datetime_string
INTO v_type
    , v_partition_interval
    , v_datetime_string
FROM @extschema@.part_config
WHERE parent_table = p_parent_table;

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;

IF v_type IN ('time', 'time-custom') THEN

    IF v_partition_interval::interval <> '3 months' OR (v_partition_interval::interval = '3 months' AND v_type = 'time-custom') THEN
        RETURN QUERY EXECUTE
        format('SELECT n.nspname::text AS partition_schemaname, c.relname::text AS partition_name FROM
        pg_catalog.pg_inherits h
        JOIN pg_catalog.pg_class c ON c.oid = h.inhrelid
        JOIN pg_catalog.pg_namespace n ON c.relnamespace = n.oid
        WHERE h.inhparent = ''%I.%I''::regclass
        ORDER BY to_timestamp(substring(c.relname from ((length(c.relname) - position(''p_'' in reverse(c.relname))) + 2) ), %L) %s'
            , v_parent_schema
            , v_parent_tablename
            , v_datetime_string
            , p_order);
    ELSE
        -- For quarterly, to_timestamp() doesn't recognize "Q" in datetime string.
        -- First order by just the year, then order by the quarter number (should be last character in table name)
        RETURN QUERY EXECUTE
        format('SELECT n.nspname::text AS partition_schemaname, c.relname::text AS partition_name FROM
        pg_catalog.pg_inherits h
        JOIN pg_catalog.pg_class c ON c.oid = h.inhrelid
        JOIN pg_catalog.pg_namespace n ON c.relnamespace = n.oid
        WHERE h.inhparent = ''%I.%I''::regclass
        ORDER BY to_timestamp(substring(c.relname from ((length(c.relname) - position(''p_'' in reverse(c.relname))) + 2) for 4), ''YYYY'') %s
            , substring(reverse(c.relname) from 1 for 1) %s'
            , v_parent_schema
            , v_parent_tablename
            , p_order
            , p_order);
    END IF;

ELSIF v_type = 'id' THEN
    RETURN QUERY EXECUTE
    format('SELECT n.nspname::text AS partition_schemaname, c.relname::text AS partition_name FROM
    pg_catalog.pg_inherits h
    JOIN pg_catalog.pg_class c ON c.oid = h.inhrelid
    JOIN pg_catalog.pg_namespace n ON c.relnamespace = n.oid
    WHERE h.inhparent = ''%I.%I''::regclass
    ORDER BY substring(c.relname from ((length(c.relname) - position(''p_'' in reverse(c.relname))) + 2) )::bigint %s'
        , v_parent_schema
        , v_parent_tablename
        , p_order);

END IF;

END
$$;

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


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

SELECT i AS "Value",
  CASE WHEN (i < 0) THEN 'small'
       WHEN (i = 0) THEN 'zero'
       WHEN (i = 1) THEN 'one'
       WHEN (i = 2) THEN 'two'
       ELSE 'big'
  END AS "Category"
  FROM CASE_TBL;

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

SELECT count(*) FROM (SELECT i AS "Value",
  CASE WHEN (i < 0) THEN 'small'
       WHEN (i = 0) THEN 'zero'
       WHEN (i = 1) THEN 'one'
       WHEN (i = 2) THEN 'two'
       ELSE 'big'
  END AS "Category"
  FROM CASE_TBL) AS _sub;


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

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

SELECT count(*) FROM (select jsonb_set_lax('{"a":1,"b":2}','{d}','6', true) ) AS _sub;


Question: Show a query using PostgreSQL contrib extension 'sepgsql' (example 50).

SELECT * FROM ts1;		-- ok
SELECT * FROM ts2;		-- failed (relation not found)
SELECT * FROM my_schema_2.ts2;	-- failed (policy violation)

--
-- Clean up
--
-- @SECURITY-CONTEXT=unconfined_u:unconfined_r:sepgsql_regtest_superuser_t:s0-s0:c0.c255
DROP TABLE IF EXISTS t1 CASCADE;

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


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

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

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


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

CREATE OPERATOR !~ (
    PROCEDURE = texticregexne,
    LEFTARG   = citext,
    RIGHTARG  = text,
    NEGATOR   = ~,
    RESTRICT  = icregexnesel,
    JOIN      = icregexnejoinsel
);

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


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

SELECT * FROM my_property_secure WHERE f_leak(passwd);

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

SELECT count(*) FROM (SELECT * FROM my_property_secure WHERE f_leak(passwd)) AS _sub;


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

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

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


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

INSERT INTO bool_tab VALUES (1, true,  true);

Explanation: DML from PostgreSQL core regression test for Predicate.


Question: Show a SQL definition from the timescaledb project (time_bucket, item 17).

CREATE OR REPLACE FUNCTION @extschema@.time_bucket(bucket_width BIGINT, ts BIGINT) RETURNS BIGINT
	AS '@MODULE_PATHNAME@', 'ts_int64_bucket' LANGUAGE C IMMUTABLE PARALLEL SAFE STRICT;

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


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

SELECT table_name, column_name, dependent_column FROM information_schema.column_column_usage WHERE table_schema = 'generated_stored_tests' ORDER BY 1, 2, 3;

Explanation: Regression test for Generated Stored in PostgreSQL core test suite.

SELECT count(*) FROM (SELECT table_name, column_name, dependent_column FROM information_schema.column_column_usage WHERE table_schema = 'generated_stored_tests' ORDER BY 1, 2, 3) AS _sub;


Question: Write the DML statement from PostgreSQL regression test 'window' (example 239).

DELETE FROM empsalary RETURNING rank() OVER (ORDER BY random());

Explanation: DML from PostgreSQL core regression test for Window.


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

CREATE TABLE tgt (a int, b int, c int, d int);

Explanation: DDL from PostgreSQL core regression test for Merge.


Question: PostgreSQL Perform: show example 36.

EXPLAIN ANALYZE SELECT * FROM tenk1 WHERE thousand IN (1, 2, 3, 4); QUERY PLAN -------------------------------------------------------------------&zwsp;--------------------------------------------------------------- Bitmap Heap Scan on tenk1 (cost=9.45..73.44 rows=40 width=244) (actual time=0.009..0.019 rows=40.00 loops=1) Recheck Cond: (thousand = ANY ('{1,2,3,4}'::integer[])) Heap Blocks: exact=38 Buffers: shared hit=40 -> Bitmap Index Scan on tenk1_thous_tenthous (cost=0.00..9.44 rows=40 width=0) (actual time=0.005..0.005 rows=40.00 loops=1) Index Cond: (thousand = ANY ('{1,2,3,4}'::integer[])) Index Searches: 1 Buffers: shared hit=2 Planning Time: 0.029 ms Execution Time: 0.026 ms;

Explanation: Example from PostgreSQL documentation on Perform.


Question: Show a SQL definition from the pg_partman project (pg_partman--0.4.2--1.0.0, item 8).

/*
 * Function to create a child table in a time-based partition set
 */
CREATE OR REPLACE FUNCTION create_time_partition (p_parent_table text, p_control text, p_interval interval, p_datetime_string text, p_partition_times timestamp[]) RETURNS text
    LANGUAGE plpgsql SECURITY DEFINER
    AS $$
DECLARE

v_all                           text[] := ARRAY['SELECT', 'INSERT', 'UPDATE', 'DELETE', 'TRUNCATE', 'REFERENCES', 'TRIGGER'];
v_grantees                      text[];
v_job_id                        bigint;
v_jobmon_schema                 text;
v_old_search_path               text;
v_parent_grant                  record;
v_parent_owner                  text;
v_partition_name                text;
v_partition_timestamp_end       timestamp;
v_partition_timestamp_start     timestamp;
v_quarter                       text;
v_revoke                        text[];
v_step_id                       bigint;
v_tablename                     text;
v_trunc_value                   text;
v_time                          timestamp;
v_year                          text;

BEGIN

SELECT nspname INTO v_jobmon_schema FROM pg_namespace n, 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;

SELECT tableowner INTO v_parent_owner FROM pg_tables WHERE schemaname ||'.'|| tablename = p_parent_table;

FOREACH v_time IN ARRAY p_partition_times LOOP

    v_partition_name := p_parent_table || '_p';

    IF p_interval = '1 year' OR p_interval = '1 month' OR p_interval = '1 day' OR p_interval = '1 hour' OR p_interval = '30 mins' OR p_interval = '15 mins' THEN
        v_partition_name := v_partition_name || to_char(v_time, 'YYYY');
        v_trunc_value := 'year';

        IF p_interval = '1 month' OR p_interval = '1 day' OR p_interval = '1 hour' OR p_interval = '30 mins' OR p_interval = '15 mins' THEN
            v_partition_name := v_partition_name || '_' || to_char(v_time, 'MM');
            v_trunc_value := 'month';

            IF p_interval = '1 day' OR p_interval = '1 hour' OR p_interval = '30 mins' OR p_interval = '15 mins' THEN
                v_partition_name := v_partition_name || '_' || to_char(v_time, 'DD');
                    v_trunc_value := 'day';

                IF p_interval = '1 hour' OR p_interval = '30 mins' OR p_interval = '15 mins' THEN
                    v_partition_name := v_partition_name || '_' || to_char(v_time, 'HH24');
                    IF p_interval <> '30 mins' AND p_interval <> '15 mins' THEN
                        v_partition_name := v_partition_name || '00';
                        v_trunc_value := 'hour';
                    ELSIF p_interval = '15 mins' THEN
                        IF date_part('minute', v_time) < 15 THEN
                            v_partition_name := v_partition_name || '00';
                        ELSIF date_part('minute', v_time) >= 15 AND date_part('minute', v_time) < 30 THEN
                            v_partition_name := v_partition_name || '15';
                        ELSIF date_part('minute', v_time) >= 30 AND date_part('minute', v_time) < 45 THEN
                            v_partition_name := v_partition_name || '30';
                        ELSE
                            v_partition_name := v_partition_name || '45';
                        END IF;
                        v_trunc_value := 'minute';
                    ELSIF p_interval = '30 mins' THEN
                        IF date_part('minute', v_time) < 30 THEN
                            v_partition_name := v_partition_name || '00';
                        ELSE
                            v_partition_name := v_partition_name || '30';
                        END IF;
                        v_trunc_value := 'minute';
                    END IF;
                END IF; -- end hour IF
            END IF; -- end day IF
        END IF; -- end month IF
    ELSIF p_interval = '1 week' THEN
        v_partition_name := v_partition_name || to_char(v_time, 'IYYY') || 'w' || to_char(v_time, 'IW');
        v_trunc_value := 'week';
    END IF; -- end year/week IF

    -- pull out datetime portion of last partition's tablename if it matched one of the above partitioning intervals
    IF v_trunc_value IS NOT NULL THEN
        v_partition_timestamp_start := date_trunc(v_trunc_value, to_timestamp(substring(v_partition_name from char_length(p_parent_table||'_p')+1), p_datetime_string));
        v_partition_timestamp_end := date_trunc(v_trunc_value, to_timestamp(substring(v_partition_name from char_length(p_parent_table||'_p')+1), p_datetime_string) + p_interval);
    END IF;

    -- "Q" is ignored in to_timestamp, so handle special case
    IF p_interval = '3 months' THEN
        v_year := to_char(v_time, 'YYYY');
        v_quarter := to_char(v_time, 'Q');
        v_partition_name := v_partition_name || v_year || 'q' || v_quarter;
        v_trunc_value := 'quarter';
        CASE
            WHEN v_quarter = '1' THEN
                v_partition_timestamp_start := date_trunc(v_trunc_value, to_timestamp(v_year || '-01-01', 'YYYY-MM-DD'));
            WHEN v_quarter = '2' THEN
                v_partition_timestamp_start := date_trunc(v_trunc_value, to_timestamp(v_year || '-04-01', 'YYYY-MM-DD'));
            WHEN v_quarter = '3' THEN
                v_partition_timestamp_start := date_trunc(v_trunc_value, to_timestamp(v_year || '-07-01', 'YYYY-MM-DD'));
            WHEN v_quarter = '4' THEN
                v_partition_timestamp_start := date_trunc(v_trunc_value, to_timestamp(v_year || '-10-01', 'YYYY-MM-DD'));
        END CASE;
        v_partition_timestamp_end := date_trunc(v_trunc_value, (v_partition_timestamp_start + p_interval));
    END IF;

    SELECT schemaname ||'.'|| tablename INTO v_tablename FROM pg_catalog.pg_tables WHERE schemaname ||'.'|| tablename = v_partition_name;
    IF v_tablename IS NOT NULL THEN
        CONTINUE;
    END IF;

    IF v_jobmon_schema IS NOT NULL THEN
        v_job_id := add_job('PARTMAN CREATE TABLE: '||p_parent_table);
        v_step_id := add_step(v_job_id, 'Creating new partition '||v_partition_name||' with interval from '||v_partition_timestamp_start||' to '||(v_partition_timestamp_end-'1sec'::interval));
    END IF;

    IF position('.' in p_parent_table) > 0 THEN
        v_tablename := substring(v_partition_name from position('.' in v_partition_name)+1);
    END IF;

    EXECUTE 'CREATE TABLE '||v_partition_name||' (LIKE '||p_parent_table||' INCLUDING DEFAULTS INCLUDING INDEXES)';
    EXECUTE 'ALTER TABLE '||v_partition_name||' ADD CONSTRAINT '||v_tablename||'_partition_check
        CHECK ('||p_control||'>='||quote_literal(v_partition_timestamp_start)||' AND '||p_control||'<'||quote_literal(v_partition_timestamp_end)||')';
    EXECUTE 'ALTER TABLE '||v_partition_name||' INHERIT '||p_parent_table;

    FOR v_parent_grant IN
        SELECT array_agg(DISTINCT privilege_type::text ORDER BY privilege_type::text) AS types, grantee
        FROM information_schema.table_privileges
        WHERE table_schema ||'.'|| table_name = p_parent_table
        GROUP BY grantee
    LOOP
        EXECUTE 'GRANT '||array_to_string(v_parent_grant.types, ',')||' ON '||v_partition_name||' TO '||v_parent_grant.grantee;
        SELECT array_agg(r) INTO v_revoke FROM (SELECT unnest(v_all) AS r EXCEPT SELECT unnest(v_parent_grant.types)) x;
        IF v_revoke IS NOT NULL THEN
            EXECUTE 'REVOKE '||array_to_string(v_revoke, ',')||' ON '||v_partition_name||' FROM '||v_parent_grant.grantee||' CASCADE';
        END IF;
        v_grantees := array_append(v_grantees, v_parent_grant.grantee::text);
    END LOOP;
    -- Revoke all privileges from roles that have none on the parent
    IF v_grantees IS NOT NULL THEN
        SELECT array_agg(r) INTO v_revoke FROM (
            SELECT DISTINCT grantee::text AS r FROM information_schema.table_privileges WHERE table_schema ||'.'|| table_name = v_partition_name
            EXCEPT
            SELECT unnest(v_grantees)) x;
        IF v_revoke IS NOT NULL THEN
            EXECUTE 'REVOKE ALL ON '||v_partition_name||' FROM '||array_to_string(v_revoke, ',');
        END IF;
    END IF;

    EXECUTE 'ALTER TABLE '||v_partition_name||' OWNER TO '||v_parent_owner;

    IF v_jobmon_schema IS NOT NULL THEN
        PERFORM update_step(v_step_id, 'OK', 'Done');
        PERFORM close_job(v_job_id);
    END IF;

END LOOP;

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

RETURN v_partition_name;

EXCEPTION
    WHEN OTHERS THEN
        IF v_jobmon_schema IS NOT NULL THEN
            EXECUTE 'SELECT set_config(''search_path'',''@extschema@,'||v_jobmon_schema||''',''false'')';
            IF v_job_id IS NULL THEN
                v_job_id := add_job('PARTMAN CREATE TABLE: '||p_parent_table);
                v_step_id := add_step(v_job_id, 'Partition maintenance for table '||p_parent_table||' failed');
            ELSIF v_step_id IS NULL THEN
                v_step_id := add_step(v_job_id, 'EXCEPTION before first step logged');
            END IF;
            PERFORM update_step(v_step_id, 'CRITICAL', 'ERROR: '||coalesce(SQLERRM,'unknown'));
            PERFORM fail_job(v_job_id);
            EXECUTE 'SELECT set_config(''search_path'','''||v_old_search_path||''',''false'')';
        END IF;
        RAISE EXCEPTION '%', SQLERRM;
END
$$;


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

create view alter1.v1 as select * from alter1.t1;

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


Question: Write the DML statement from PostgreSQL regression test 'insert_conflict' (example 213).

insert into selfconflict values (12,1), (12,2) on conflict(f1) do select for update returning *;

Explanation: DML from PostgreSQL core regression test for Insert Conflict.


Question: Show a query using PostgreSQL contrib extension 'file_fdw' (example 36).

SELECT * FROM agg_csv c JOIN agg_text t ON (t.a = c.a) ORDER BY c.a;

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


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

insert into parted values (1, 1, 'uno uno v1');    -- works
create trigger t before insert or update or delete on parted
  for each row execute function parted_trigfunc();

Explanation: DML from PostgreSQL core regression test for Triggers.


Question: Show a SQL definition from the pg_partman project (pg_partman--5.1.0--5.2.0, item 19).

CREATE OR REPLACE FUNCTION @extschema@.create_partition_id(
    p_parent_table text
    , p_partition_ids bigint[]
    , p_start_partition text DEFAULT NULL
)
    RETURNS boolean
    LANGUAGE plpgsql
    AS $$
DECLARE

ex_context                      text;
ex_detail                       text;
ex_hint                         text;
ex_message                      text;
v_control                       text;
v_control_type                  text;
v_exists                        text;
v_id                            bigint;
v_inherit_privileges            boolean;
v_job_id                        bigint;
v_jobmon                        boolean;
v_jobmon_schema                 text;
v_new_search_path               text;
v_old_search_path               text;
v_parent_oid                    oid;
v_parent_schema                 text;
v_parent_tablename              text;
v_parent_tablespace             name;
v_partition_interval            bigint;
v_partition_created             boolean := false;
v_partition_name                text;
v_partition_type                text;
v_row                           record;
v_sql                           text;
v_step_id                       bigint;
v_sub_control                   text;
v_sub_partition_type            text;
v_sub_id_max                    bigint;
v_sub_id_min                    bigint;
v_template_table                text;

BEGIN
/*
 * Function to create id partitions
 */

SELECT control
    , partition_interval::bigint -- this shared field also used in partition_time as interval
    , partition_type
    , jobmon
    , template_table
    , inherit_privileges
INTO v_control
    , v_partition_interval
    , v_partition_type
    , v_jobmon
    , v_template_table
    , v_inherit_privileges
FROM @extschema@.part_config
WHERE parent_table = p_parent_table;

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

SELECT n.nspname
    , c.relname
    , c.oid
    , t.spcname
INTO v_parent_schema
    , v_parent_tablename
    , v_parent_oid
    , v_parent_tablespace
FROM pg_catalog.pg_class c
JOIN pg_catalog.pg_namespace n ON c.relnamespace = n.oid
LEFT OUTER JOIN pg_catalog.pg_tablespace t ON c.reltablespace = t.oid
WHERE n.nspname = split_part(p_parent_table, '.', 1)::name
AND c.relname = split_part(p_parent_table, '.', 2)::name;

SELECT general_type INTO v_control_type FROM @extschema@.check_control_type(v_parent_schema, v_parent_tablename, v_control);
IF v_control_type <> 'id' THEN
    RAISE EXCEPTION 'ERROR: Given parent table is not set up for id/serial partitioning';
END IF;

SELECT current_setting('search_path') INTO v_old_search_path;
IF length(v_old_search_path) > 0 THEN
   v_new_search_path := '@extschema@,pg_temp,'||v_old_search_path;
ELSE
    v_new_search_path := '@extschema@,pg_temp';
END IF;
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 := format('%s,%s',v_jobmon_schema, v_new_search_path);
    END IF;
END IF;
EXECUTE format('SELECT set_config(%L, %L, %L)', 'search_path', v_new_search_path, 'false');

-- Determine if this table is a child of a subpartition parent. If so, get limits of what child tables can be created based on parent suffix
SELECT sub_min::bigint, sub_max::bigint INTO v_sub_id_min, v_sub_id_max FROM @extschema@.check_subpartition_limits(p_parent_table, 'id');

IF v_jobmon_schema IS NOT NULL THEN
    v_job_id := add_job(format('PARTMAN CREATE TABLE: %s', p_parent_table));
END IF;

FOREACH v_id IN ARRAY p_partition_ids LOOP
-- Do not create the child table if it's outside the bounds of the top parent.
    IF v_sub_id_min IS NOT NULL THEN
        IF v_id < v_sub_id_min OR v_id >= v_sub_id_max THEN
            CONTINUE;
        END IF;
    END IF;

    v_partition_name := @extschema@.check_name_length(v_parent_tablename, v_id::text, TRUE);
    -- If child table already exists, skip creation
    -- Have to check pg_class because if subpartitioned, table will not be in pg_tables
    SELECT c.relname INTO v_exists
    FROM pg_catalog.pg_class c
    JOIN pg_catalog.pg_namespace n ON c.relnamespace = n.oid
    WHERE n.nspname = v_parent_schema::name AND c.relname = v_partition_name::name;
    IF v_exists IS NOT NULL THEN
        CONTINUE;
    END IF;

    IF v_jobmon_schema IS NOT NULL THEN
        v_step_id := add_step(v_job_id, 'Creating new partition '||v_partition_name||' with interval from '||v_id||' to '||(v_id + v_partition_interval)-1);
    END IF;

    -- Same INCLUDING list is used in create_parent()
    v_sql := format('CREATE TABLE %I.%I (LIKE %I.%I  INCLUDING COMMENTS INCLUDING COMPRESSION INCLUDING CONSTRAINTS INCLUDING DEFAULTS INCLUDING GENERATED INCLUDING STATISTICS INCLUDING STORAGE) '
            , v_parent_schema
            , v_partition_name
            , v_parent_schema
            , v_parent_tablename);

    IF v_parent_tablespace IS NOT NULL THEN
        v_sql := format('%s TABLESPACE %I ', v_sql, v_parent_tablespace);
    END IF;

    SELECT sub_partition_type, sub_control INTO v_sub_partition_type, v_sub_control
    FROM @extschema@.part_config_sub
    WHERE sub_parent = p_parent_table;
    IF v_sub_partition_type = 'range' THEN
        v_sql :=  format('%s PARTITION BY RANGE (%I) ', v_sql, v_sub_control);
    ELSIF v_sub_partition_type = 'list' THEN
        v_sql :=  format('%s PARTITION BY LIST (%I) ', v_sql, v_sub_control);
    END IF;

    RAISE DEBUG 'create_partition_id v_sql: %', v_sql;
    EXECUTE v_sql;

    IF v_template_table IS NOT NULL THEN
        PERFORM @extschema@.inherit_template_properties(p_parent_table, v_parent_schema, v_partition_name);
    END IF;

    IF v_partition_type = 'range' THEN
        EXECUTE format('ALTER TABLE %I.%I ATTACH PARTITION %I.%I FOR VALUES FROM (%L) TO (%L)'
            , v_parent_schema
            , v_parent_tablename
            , v_parent_schema
            , v_partition_name
            , v_id
            , v_id + v_partition_interval);
    ELSIF v_partition_type = 'list' THEN
        EXECUTE format('ALTER TABLE %I.%I ATTACH PARTITION %I.%I FOR VALUES IN (%L)'
            , v_parent_schema
            , v_parent_tablename
            , v_parent_schema
            , v_partition_name
            , v_id);
    ELSE
        RAISE EXCEPTION 'create_partition_id: Unexpected partition type (%) encountered in part_config table for parent table %', v_partition_type, p_parent_table;
    END IF;

    -- NOTE: Privileges not automatically inherited. Only do so if config flag is set
    IF v_inherit_privileges = TRUE THEN
        PERFORM @extschema@.apply_privileges(v_parent_schema, v_parent_tablename, v_parent_schema, v_partition_name, v_job_id);
    END IF;

    IF v_jobmon_schema IS NOT NULL THEN
        PERFORM update_step(v_step_id, 'OK', 'Done');
    END IF;

    -- Will only loop once and only if sub_partitioning is actually configured
    -- This seemed easier than assigning a bunch of variables then doing an IF condition
    -- This column list must be kept consistent between:
    --   create_parent, check_subpart_sameconfig, create_partition_id, create_partition_time, dump_partitioned_table_definition, and table definition
    FOR v_row IN
        SELECT
            sub_parent
            , sub_control
            , sub_time_encoder
            , sub_time_decoder
            , sub_partition_interval
            , sub_partition_type
            , sub_premake
            , sub_automatic_maintenance
            , sub_template_table
            , sub_retention
            , sub_retention_schema
            , sub_retention_keep_index
            , sub_retention_keep_table
            , sub_epoch
            , sub_constraint_cols
            , sub_optimize_constraint
            , sub_infinite_time_partitions
            , sub_jobmon
            , sub_inherit_privileges
            , sub_constraint_valid
            , sub_date_trunc_interval
            , sub_ignore_default_data
            , sub_default_table
            , sub_maintenance_order
            , sub_retention_keep_publication
            , sub_control_not_null
        FROM @extschema@.part_config_sub
        WHERE sub_parent = p_parent_table
    LOOP
        IF v_jobmon_schema IS NOT NULL THEN
            v_step_id := add_step(v_job_id, 'Subpartitioning '||v_partition_name);
        END IF;
        v_sql := format('SELECT @extschema@.create_parent(
                 p_parent_table := %L
                , p_control := %L
                , p_time_encoder := %L
                , p_time_decoder := %L
                , p_type := %L
                , p_interval := %L
                , p_default_table := %L
                , p_constraint_cols := %L
                , p_premake := %L
                , p_automatic_maintenance := %L
                , p_epoch := %L
                , p_template_table := %L
                , p_jobmon := %L
                , p_start_partition := %L
                , p_date_trunc_interval := %L
                , p_control_not_null := %L )'
            , v_parent_schema||'.'||v_partition_name
            , v_row.sub_control
            , v_row.sub_time_encoder
            , v_row.sub_time_decoder
            , v_row.sub_partition_type
            , v_row.sub_partition_interval
            , v_row.sub_default_table
            , v_row.sub_constraint_cols
            , v_row.sub_premake
            , v_row.sub_automatic_maintenance
            , v_row.sub_epoch
            , v_row.sub_template_table
            , v_row.sub_jobmon
            , p_start_partition
            , v_row.sub_date_trunc_interval
            , v_row.sub_control_not_null);
        RAISE DEBUG 'create_partition_id (create_parent loop): %', v_sql;
        EXECUTE v_sql;

        UPDATE @extschema@.part_config SET
            retention_schema = v_row.sub_retention_schema
            , retention_keep_table = v_row.sub_retention_keep_table
            , optimize_constraint = v_row.sub_optimize_constraint
            , infinite_time_partitions = v_row.sub_infinite_time_partitions
            , inherit_privileges = v_row.sub_inherit_privileges
            , constraint_valid = v_row.sub_constraint_valid
            , ignore_default_data = v_row.sub_ignore_default_data
            , maintenance_order = v_row.sub_maintenance_order
            , retention_keep_publication = v_row.sub_retention_keep_publication
        WHERE parent_table = v_parent_schema||'.'||v_partition_name;

        IF v_jobmon_schema IS NOT NULL THEN
            PERFORM update_step(v_step_id, 'OK', 'Done');
        END IF;

    END LOOP; -- end sub partitioning LOOP

    -- NOTE: Replication identity not automatically inherited as of PG16 (revisit in future versions)
    PERFORM @extschema@.inherit_replica_identity(v_parent_schema, v_parent_tablename, v_partition_name);

    -- Manage additional constraints if set
    PERFORM @extschema@.apply_constraints(p_parent_table, p_job_id := v_job_id);

    v_partition_created := true;

END LOOP;

IF v_jobmon_schema IS NOT NULL THEN
    IF v_partition_created = false THEN
        v_step_id := add_step(v_job_id, format('No partitions created for partition set: %s', p_parent_table));
        PERFORM update_step(v_step_id, 'OK', 'Done');
    END IF;

    PERFORM close_job(v_job_id);
END IF;

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

RETURN v_partition_created;

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 TABLE: %s'')', v_jobmon_schema, p_parent_table) INTO v_job_id;
                EXECUTE format('SELECT %I.add_step(%s, ''EXCEPTION before job logging started'')', v_jobmon_schema, v_job_id, p_parent_table) INTO v_step_id;
            ELSIF v_step_id IS NULL THEN
                EXECUTE format('SELECT %I.add_step(%s, ''EXCEPTION before first step logged'')', v_jobmon_schema, v_job_id) INTO v_step_id;
            END IF;
            EXECUTE format('SELECT %I.update_step(%s, ''CRITICAL'', %L)', v_jobmon_schema, v_step_id, 'ERROR: '||coalesce(SQLERRM,'unknown'));
            EXECUTE format('SELECT %I.fail_job(%s)', v_jobmon_schema, v_job_id);
        END IF;
        RAISE EXCEPTION '%
CONTEXT: %
DETAIL: %
HINT: %', ex_message, ex_context, ex_detail, ex_hint;
END
$$;

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


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

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


Question: Write the DDL statement from PostgreSQL regression test 'identity' (example 220).

CREATE TABLE itest15 (id integer NOT NULL GENERATED ALWAYS AS IDENTITY);

Explanation: DDL from PostgreSQL core regression test for Identity.


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

INSERT INTO caster (circle)        VALUES ('((0,0),2)'::citext);

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


Question: Show a query using PostgreSQL contrib extension 'jsonb_plpython' (example 21).

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


Question: PostgreSQL Ddl: show example 21.

CREATE TABLE products ( product_no integer NOT NULL, name text NOT NULL, price numeric NOT NULL CHECK (price > 0) );

Explanation: Example from PostgreSQL documentation on Ddl.


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

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

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


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

SELECT reltuples, relhassubclass
  FROM pg_class WHERE oid = 'past_inh_db_parent'::regclass;

Explanation: Regression test for Maintain Every in PostgreSQL core test suite.

SELECT count(*) FROM (SELECT reltuples, relhassubclass
  FROM pg_class WHERE oid = 'past_inh_db_parent'::regclass) AS _sub;


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

drop table parted_referenced, parted_trigger, unparted_trigger;

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


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

SELECT t4.*
FROM (SELECT t1.*, t2.a AS a1 FROM sj t1, sj t2 WHERE t1.b = t2.b) AS t3
JOIN sj t4 ON (t4.a = t3.a) WHERE t3.a1 = 42;

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

SELECT count(*) FROM (SELECT t4.*
FROM (SELECT t1.*, t2.a AS a1 FROM sj t1, sj t2 WHERE t1.b = t2.b) AS t3
JOIN sj t4 ON (t4.a = t3.a) WHERE t3.a1 = 42) AS _sub;


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

INSERT INTO TIMESTAMPTZ_TBL VALUES ('Feb 16 17:32:01 0597');

Explanation: DML from PostgreSQL core regression test for Timestamptz.


Question: Write the DDL statement from PostgreSQL regression test 'truncate' (example 165).

CREATE TABLE trunc_a3 PARTITION OF trunc_a FOR VALUES FROM (20) TO (30);

Explanation: DDL from PostgreSQL core regression test for Truncate.


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

BEGIN
    FOR r IN SELECT a FROM test1 FOR UPDATE LOOP
      UPDATE test1 SET b = b || ' ' || b WHERE a = r.a;

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


Question: Write the DML statement from PostgreSQL regression test 'jsonb' (example 183).

INSERT INTO foo VALUES (999999, NULL, 'bar');

Explanation: DML from PostgreSQL core regression test for Jsonb.


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

ALTER EXTENSION pgtap ADD FUNCTION row_eq( TEXT, anyelement );

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


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

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

SELECT count(*) FROM (SELECT INTERVAL 'today') AS _sub;


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

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

SELECT count(*) FROM (select '[{"b": "c"}, {"b": "cc"}]'::jsonb -> 1) AS _sub;


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

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


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

-- bucketing with timezone
CREATE OR REPLACE FUNCTION @extschema@.time_bucket(bucket_width INTERVAL, ts TIMESTAMPTZ, timezone TEXT, origin TIMESTAMPTZ DEFAULT NULL, "offset" INTERVAL DEFAULT NULL) RETURNS TIMESTAMPTZ
	AS '@MODULE_PATHNAME@', 'ts_timestamptz_timezone_bucket' LANGUAGE C IMMUTABLE PARALLEL SAFE;

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


Question: Write the DML statement from PostgreSQL regression test 'insert_conflict' (example 132).

insert into insertconflictv values (1,'bar')
  on conflict (f1) do update set f2 = excluded.f2;

Explanation: DML from PostgreSQL core regression test for Insert Conflict.


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

select interval '-9223372036854775.808 milliseconds';

SELECT count(*) FROM (select interval '-9223372036854775.808 milliseconds') AS _sub;


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

CREATE OR REPLACE FUNCTION perl_int(int) RETURNS INTEGER AS $$
return undef;
$$ LANGUAGE plperl;

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


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

SELECT * FROM pg_input_error_info('{}', 'pg_ndistinct');

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

SELECT count(*) FROM (SELECT * FROM pg_input_error_info('{}', 'pg_ndistinct')) AS _sub;


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

create table idxpart1pk partition of idxpart (a primary key) for values from (0) to (100);

Explanation: DDL from PostgreSQL core regression test for Indexing.


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

SELECT (timestamp with time zone 'tomorrow' > 'now') as "True";

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

SELECT count(*) FROM (SELECT (timestamp with time zone 'tomorrow' > 'now') as "True") AS _sub;


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

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

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


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

CREATE TABLE partitioned (
	a int
) PARTITION BY RANGE (const_func());

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


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

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

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

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


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

Explanation: DML from PostgreSQL core regression test for Polygon.


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

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


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

select string_to_array(NULL, '|') IS NULL;

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

SELECT count(*) FROM (select string_to_array(NULL, '|') IS NULL) AS _sub;


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

CREATE OR REPLACE FUNCTION rngfunc(in f1 int, out f2 int) RETURNS float
AS 'select $1+1' LANGUAGE sql;

Explanation: DDL from PostgreSQL core regression test for Rangefuncs.


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

CREATE OR REPLACE FUNCTION _have_index( NAME, NAME, NAME)
RETURNS BOOLEAN AS $$
    SELECT EXISTS (
    SELECT TRUE
      FROM pg_catalog.pg_index x
      JOIN pg_catalog.pg_class ct    ON ct.oid = x.indrelid
      JOIN pg_catalog.pg_class ci    ON ci.oid = x.indexrelid
      JOIN pg_catalog.pg_namespace n ON n.oid = ct.relnamespace
     WHERE n.nspname  = $1
       AND ct.relname = $2
       AND ci.relname = $3
    );
$$ LANGUAGE sql;

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


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

-- Check that aggregates which have the same transition function also have
-- the same combine, serialization, and deserialization functions.
-- While that isn't strictly necessary, it's fishy if they don't.

SELECT a.aggfnoid, a.aggcombinefn, a.aggserialfn, a.aggdeserialfn,
       b.aggfnoid, b.aggcombinefn, b.aggserialfn, b.aggdeserialfn
FROM
    pg_aggregate a, pg_aggregate b
WHERE
    a.aggfnoid < b.aggfnoid AND a.aggtransfn = b.aggtransfn AND
    (a.aggcombinefn != b.aggcombinefn OR a.aggserialfn != b.aggserialfn
     OR a.aggdeserialfn != b.aggdeserialfn);

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


Question: PostgreSQL Textsearch: show example 39.

SELECT to_tsquery('''supernovae stars'' & !crab'); to_tsquery --------------- 'sn' & !'crab';

Explanation: Example from PostgreSQL documentation on Textsearch.


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

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

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


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

CREATE OR REPLACE FUNCTION _get_index_owner( NAME, NAME, NAME )
RETURNS NAME AS $$
    SELECT pg_catalog.pg_get_userbyid(ci.relowner)
      FROM pg_catalog.pg_index x
      JOIN pg_catalog.pg_class ct    ON ct.oid = x.indrelid
      JOIN pg_catalog.pg_class ci    ON ci.oid = x.indexrelid
      JOIN pg_catalog.pg_namespace n ON n.oid = ct.relnamespace
     WHERE n.nspname  = $1
       AND ct.relname = $2
       AND ci.relname = $3;
$$ LANGUAGE sql;


Question: Show a SQL definition from the timescaledb project (ddl_api, item 18).

CREATE OR REPLACE FUNCTION @extschema@.show_tablespaces(hypertable REGCLASS) RETURNS SETOF NAME
AS '@MODULE_PATHNAME@', 'ts_tablespace_show' LANGUAGE C VOLATILE STRICT;

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


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

SELECT has_foreign_data_wrapper_privilege(
    (SELECT oid FROM pg_foreign_data_wrapper WHERE fdwname='foo'), 'USAGE');

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

SELECT count(*) FROM (SELECT has_foreign_data_wrapper_privilege(
    (SELECT oid FROM pg_foreign_data_wrapper WHERE fdwname='foo'), 'USAGE')) AS _sub;


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

CREATE OR REPLACE FUNCTION sql_error() RETURNS void AS $$
begin
  select 1/0;
end
$$ LANGUAGE plpgsql;

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


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

INSERT INTO insert_tbl (SELECT * FROM local_tbl UNION ALL SELECT * FROM remote_tbl);

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


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

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

SELECT count(*) FROM (select jsonb_set_lax('{"a":1,"b":2}','{d}',null,true)) AS _sub;


Question: Use pg_stat_statements to find the slowest queries.

SELECT query, calls, mean_exec_time AS avg_ms, total_exec_time AS total_ms,
       rows, shared_blks_hit, shared_blks_read
FROM pg_stat_statements
ORDER BY mean_exec_time DESC
LIMIT 20;

Explanation: pg_stat_statements extension tracks execution statistics for all queries. Ordering by mean_exec_time surfaces the slowest individual query patterns.


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

INSERT INTO nulltest values ('a', 'b', 'c', 'd', 'c');  -- Good
insert into nulltest values ('a', 'b', 'c', 'd', NULL);

Explanation: DML from PostgreSQL core regression test for Domain.


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

INSERT INTO PATH_TBL VALUES (' ( ( 1 , 2 ) , ( 3 , 4 ) ) ');

Explanation: DML from PostgreSQL core regression test for Path.


Question: pgTAP test for Pgtap--1.1.0--1.2.0 (assertion 19).

-- hasnt_leftop( name, right_type, return_type, description )
CREATE OR REPLACE FUNCTION hasnt_leftop ( NAME, NAME, NAME, TEXT )
RETURNS TEXT AS $$
    SELECT ok( NOT _op_exists(NULL, $1, $2, $3), $4 );
$$ LANGUAGE SQL;

Explanation: SQL assertion from pgTAP test suite for Pgtap--1.1.0--1.2.0.


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

CREATE TABLE collate_test_fail (
    a int COLLATE "en-x-icu",
    b text
);

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


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

SELECT * FROM pg_input_error_info('[null]', 'pg_ndistinct');

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

SELECT count(*) FROM (SELECT * FROM pg_input_error_info('[null]', 'pg_ndistinct')) AS _sub;


Question: Write the DML statement from PostgreSQL regression test 'money' (example 49).

INSERT INTO money_data VALUES ('$123.455');

Explanation: DML from PostgreSQL core regression test for Money.


Question: Show an example of PostgreSQL PSQL-REF (example 6).

SELECT $1 \parse stmt1 \close_prepared stmt1;

Explanation: PostgreSQL PSQL-REF command.


Question: Write the DML statement from PostgreSQL regression test 'stats_ext' (example 413).

INSERT INTO functional_dependencies_multi (a, b, c, d)
    SELECT
         mod(i,7),
         mod(i,7),
         mod(i,11),
         mod(i,11)
    FROM generate_series(1,5000) s(i);

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


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


Question: pgTAP test for Index (assertion 82).

SELECT * FROM check_test(
    index_is_partial( 'public', 'sometab', 'idx_baz' ),
    false,
    'index_is_partial() fail no desc',
    'Index idx_baz should be partial',
    ''
);

Explanation: SQL assertion from pgTAP test suite for Index.


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

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

SELECT count(*) FROM (SELECT pg_get_triggerdef(0)) AS _sub;


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

CREATE FOREIGN DATA WRAPPER extstats_dummy_fdw;

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


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

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

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

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


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

CREATE FUNCTION gc_to_sec(float8)
RETURNS float8
LANGUAGE SQL
IMMUTABLE STRICT
PARALLEL SAFE
AS 'SELECT CASE WHEN $1 < 0 THEN 0::float8 WHEN $1/earth() > pi() THEN 2*earth() ELSE 2*earth()*sin($1/(2*earth())) END';

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


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

Explanation: DML from PostgreSQL core regression test for Numeric.


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

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


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

SELECT COUNT(*) FROM (VALUES (1::INT, 2::INT)) AS t(a, b) GROUP BY b;

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


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

INSERT INTO temporal_mltrng (id, valid_at) VALUES ('[2,3)', datemultirange(daterange('2005-01-01', '2006-01-01'))) ON CONFLICT (id, valid_at) DO NOTHING;

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


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

INSERT INTO test VALUES ('Top.Hobbies');

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


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

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


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

select * from jsonb_path_query('[1, "2", null]', '$[*] ? (@ != null)');

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

SELECT count(*) FROM (select * from jsonb_path_query('[1, "2", null]', '$[*] ? (@ != null)')) AS _sub;


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

SELECT count(*) FROM (select jsonb_path_query('"nan"', '$.decimal()')) AS _sub;


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

SELECT xmltable.* FROM xmltest2, LATERAL xmltable(('/d/r/' || lower(_path) || 'c') PASSING x COLUMNS a int PATH '.');

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

SELECT count(*) FROM (SELECT xmltable.* FROM xmltest2, LATERAL xmltable(('/d/r/' || lower(_path) || 'c') PASSING x COLUMNS a int PATH '.')) AS _sub;


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

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

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

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


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

SELECT class, sum(a) FROM a_star* GROUP BY class ORDER BY class;

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

SELECT count(*) FROM (SELECT class, sum(a) FROM a_star* GROUP BY class ORDER BY class) AS _sub;


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

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

SELECT count(*) FROM (select jsonb_insert('{"a": [0,1,2]}', '{a, 1}', '{"b": "value"}')) AS _sub;