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

/* contrib/pgstattuple/pgstattuple--1.2--1.3.sql */

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

CREATE FUNCTION pgstattuple_approx(IN reloid regclass,
    OUT table_len BIGINT,               -- physical table length in bytes
    OUT scanned_percent FLOAT8,         -- what percentage of the table's pages was scanned
    OUT approx_tuple_count BIGINT,      -- estimated number of live tuples
    OUT approx_tuple_len BIGINT,        -- estimated total length in bytes of live tuples
    OUT approx_tuple_percent FLOAT8,    -- live tuples in % (based on estimate)
    OUT dead_tuple_count BIGINT,        -- exact number of dead tuples
    OUT dead_tuple_len BIGINT,          -- exact total length in bytes of dead tuples
    OUT dead_tuple_percent FLOAT8,      -- dead tuples in % (based on estimate)
    OUT approx_free_space BIGINT,       -- estimated free space in bytes
    OUT approx_free_percent FLOAT8)     -- free space in % (based on estimate)
AS 'MODULE_PATHNAME', 'pgstattuple_approx'
LANGUAGE C STRICT;


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

CREATE FUNCTION zdb.schema_version() RETURNS text LANGUAGE sql AS $$
SELECT '3000.1.25 (aba9cd80d5456d604bd9de4fd68836af7676e608)'
$$;

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


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

select * from mr_outparam_succeed(int4multirange(int4range(1,2)));

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

SELECT count(*) FROM (select * from mr_outparam_succeed(int4multirange(int4range(1,2)))) AS _sub;


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

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

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


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

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

SELECT count(*) FROM (select jsonb_path_query('{"a": {"b": 1}}', 'lax $.**{1}')) AS _sub;


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

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


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

SELECT n_tup_ins, n_live_tup, n_dead_tup
  FROM pg_stat_all_tables WHERE relname = 'test_rewrite_alone_abort';

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

SELECT count(*) FROM (SELECT n_tup_ins, n_live_tup, n_dead_tup
  FROM pg_stat_all_tables WHERE relname = 'test_rewrite_alone_abort') AS _sub;


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

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


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

SELECT message FROM pg_input_error_info('<value>one</', 'xml');

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

SELECT count(*) FROM (SELECT message FROM pg_input_error_info('<value>one</', 'xml')) AS _sub;


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

Explanation: DML from PostgreSQL core regression test for Domain.


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

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

SELECT count(*) FROM (select null::int = any ('{1,2,3}')) AS _sub;


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

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


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

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

SELECT count(*) FROM (select '$a[*]'::jsonpath) AS _sub;


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

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

SELECT count(*) FROM (select pg_input_is_valid('(1,4', 'int4range')) AS _sub;


Question: Show a SQL definition from the citus project (citus_split_shard_by_split_points_negative, item 10).

CREATE TABLE table_to_split (id bigserial PRIMARY KEY, value char);

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


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

CREATE VIEW bv1 WITH (security_barrier) AS SELECT * FROM b1 WHERE a > 0 WITH CHECK OPTION;

Explanation: DDL from PostgreSQL core regression test for Rowsecurity.


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

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

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


Question: Write the DML statement from PostgreSQL regression test 'macaddr' (example 8).

INSERT INTO macaddr_data VALUES (7, '08002b010203');

Explanation: DML from PostgreSQL core regression test for Macaddr.


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

SELECT count(*) FROM (select jsonb_path_query('false', '$.boolean()')) AS _sub;


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

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

SELECT count(*) FROM (SELECT pg_input_is_valid('50000', 'int2')) AS _sub;


Question: Show a SQL definition from the timescaledb project (c_unit_tests, item 6).

CREATE OR REPLACE FUNCTION test.jsonb_utils() RETURNS VOID
AS :MODULE_PATHNAME, 'ts_test_jsonb_utils' LANGUAGE C;

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


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

select i, left('ahoj', i), right('ahoj', i) from generate_series(-5, 5) t(i) order by i;

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

SELECT count(*) FROM (select i, left('ahoj', i), right('ahoj', i) from generate_series(-5, 5) t(i) order by i) AS _sub;


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

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


Question: Write the DDL statement from PostgreSQL regression test 'lock' (example 130).

CREATE FUNCTION test_atomic_ops()
    RETURNS bool
    AS :'regresslib'
    LANGUAGE C;

Explanation: DDL from PostgreSQL core regression test for Lock.


Question: PostgreSQL Advanced: show example 15.

SELECT name, elevation FROM cities WHERE elevation > 500;

Explanation: Example from PostgreSQL documentation on Advanced.


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

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


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

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


Question: pgTAP test for Hastap (assertion 229).

SELECT * FROM check_test(
    has_language('aoijaoisjfaoidfjaisjdfosjf'),
    false,
    'has_language(nonexistent language)',
    'Procedural language aoijaoisjfaoidfjaisjdfosjf should exist',
    ''
);

Explanation: SQL assertion from pgTAP test suite for Hastap.


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

SELECT unique1, unique2 FROM onek_with_null WHERE unique1 = 500 ORDER BY unique2 DESC, unique1 DESC LIMIT 1;

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

SELECT count(*) FROM (SELECT unique1, unique2 FROM onek_with_null WHERE unique1 = 500 ORDER BY unique2 DESC, unique1 DESC LIMIT 1) AS _sub;


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

select interval '2147483647 days 1 week';

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

SELECT count(*) FROM (select interval '2147483647 days 1 week') AS _sub;


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

-- Exercise code in ExecGetTriggerResultRel() as there's been previous issues
-- with ResultRelInfos being returned with the incorrect ri_RootResultRelInfo
WITH cte AS (
  UPDATE fkpart13_t2_p1 SET part_id = part_id
) UPDATE fkpart13_t1 SET a = 2 WHERE a = 1;

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


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

CREATE FUNCTION gen_salt(text)
RETURNS text
AS 'MODULE_PATHNAME', 'pg_gen_salt'
LANGUAGE C VOLATILE STRICT PARALLEL SAFE;

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


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

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


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

SELECT JSON_VALUE(jsonb '"aaa"', '$' RETURNING json);

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

SELECT count(*) FROM (SELECT JSON_VALUE(jsonb '"aaa"', '$' RETURNING json)) AS _sub;


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

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

SELECT count(*) FROM (SELECT stddev_pop('nan'::numeric), stddev_samp('nan'::numeric)) AS _sub;


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


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

Explanation: DDL from PostgreSQL core regression test for Indexing.


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

SELECT foo, length(foo) FROM regexp_split_to_table('the quick brown fox jumps over the lazy dog', 'nomatch') AS foo;

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

SELECT count(*) FROM (SELECT foo, length(foo) FROM regexp_split_to_table('the quick brown fox jumps over the lazy dog', 'nomatch') AS foo) AS _sub;


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

create or replace function retc(int) returns two_int8s language plpgsql as
$$ declare r record; begin r := row($1::int8, 1::int8, 42); return r; end $$;
select retc(42);

-- but, for mostly historical reasons, we do convert when assigning
-- to a named-composite-type variable
create or replace function retc(int) returns two_int8s language plpgsql as
$$ declare r two_int8s; begin r := row($1::int8, 1::int8, 42); return r; end $$;

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


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

--
-- SQL-standard body
--
CREATE FUNCTION functest_S_1(a text, b date) RETURNS boolean
    LANGUAGE SQL
    RETURN a = 'abcd' AND b > '2001-01-01';

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


Question: Write the DML statement from PostgreSQL regression test 'sqljson' (example 196).

Explanation: DML from PostgreSQL core regression test for Sqljson.


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

$$;

TRUNCATE test1;

CALL cursor_fail_during_commit();

-- note that error occurs during first COMMIT, hence nothing is in test1
SELECT count(*) FROM test1;

CREATE PROCEDURE cursor_fail_during_rollback()
 LANGUAGE plpgsql
AS $$
  DECLARE id int;

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


Question: pgTAP test for Policy (assertion 53).

SELECT * FROM check_test(
    policy_cmd_is( 'passwd', 'daemon_insert', 'delete', 'whatever' ),
    false,
    'policy_cmd_is(table, policy, command, desc) for INSERT should fail',
    'whatever',
    '        have: INSERT
        want: DELETE'
);

Explanation: SQL assertion from pgTAP test suite for Policy.


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

SELECT data FROM test_float WHERE data IN ('1', '2');

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


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

SELECT * FROM test_interval WHERE i<='08:55:08'::interval ORDER BY i;

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


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

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


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

CREATE OR REPLACE FUNCTION perl_row() RETURNS testrowperl AS $$
    return undef;
$$ LANGUAGE plperl;

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


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

CREATE INDEX on tbl USING hash(c1, c2) INCLUDE (c3, c4);

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


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

SELECT time without time zone '040506.07';

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

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


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

SELECT count(*) FROM (SELECT JSON_EXISTS(jsonb '{}', '$.a')) AS _sub;


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

SELECT d1 as "timestamp",
   date_part( 'isoyear', d1) AS isoyear, date_part( 'week', d1) AS week,
   date_part( 'isodow', d1) AS isodow, date_part( 'dow', d1) AS dow,
   date_part( 'doy', d1) AS doy
   FROM TIMESTAMP_TBL;

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

SELECT count(*) FROM (SELECT d1 as "timestamp",
   date_part( 'isoyear', d1) AS isoyear, date_part( 'week', d1) AS week,
   date_part( 'isodow', d1) AS isodow, date_part( 'dow', d1) AS dow,
   date_part( 'doy', d1) AS doy
   FROM TIMESTAMP_TBL) AS _sub;


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

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

Explanation: DDL from PostgreSQL core regression test for Box.


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

ALTER EXTENSION pgtap ADD FUNCTION _types_are ( NAME[], TEXT, CHAR[] );

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


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

INSERT INTO TIMESTAMP_TBL VALUES ('Feb 16 17:32:01 5097 BC');

Explanation: DML from PostgreSQL core regression test for Timestamp.


Question: pgTAP test for Hastap (assertion 278).

SELECT * FROM check_test(
    domain_type_isnt( 'us_postal_code', 'text', 'whatever'),
    false,
    'domain_type_isnt(domain, type, desc) fail',
    'whatever',
    '        have: text
        want: anything else'
);

Explanation: SQL assertion from pgTAP test suite for Hastap.


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

CREATE TABLE tststats.priv_test_tbl (
    a int,
    b int
);

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


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

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

SELECT count(*) FROM (SELECT t1.*, t2.* FROM alpha t1 INNER JOIN beta t2 ON (t1.a = t2.a AND t1.c = t2.c) WHERE ((t1.b >= 100 AND t1.b < 110) OR (t1.b >= 200 AND t1.b < 210)) AND ((t2.b >= 100 AND t2.b < 110) OR (t2.b >= 200 AND t2.b < 210)) AND t1.c IN ('0004', '0009') ORDER BY t1.a, t1.b, t2.b) AS _sub;


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

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

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


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

select from generate_series(1,5) intersect select from generate_series(1,3);

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

SELECT count(*) FROM (select from generate_series(1,5) intersect select from generate_series(1,3)) AS _sub;


Question: pgTAP test for Proctap (assertion 58).

SELECT * FROM check_test(
    isnt_procedure( 'argpubproc', ARRAY['integer', 'text'] ),
    false,
    'isnt_procedure(proc, args)',
    'Function argpubproc(integer, text) should not be a procedure',
    ''
);

Explanation: SQL assertion from pgTAP test suite for Proctap.


Question: pgTAP test for Inheritance (assertion 26).

SELECT * FROM check_test(
    hasnt_inherited_tables( 'hide', 'h_child1'::name ),
    false,
    'hasnt_inherited_tables(sch, tab) fail',
    'Table hide.h_child1 should not have descendents',
    ''
);

Explanation: SQL assertion from pgTAP test suite for Inheritance.


Question: Write the DDL statement from PostgreSQL regression test 'subscription' (example 29).

CREATE SUBSCRIPTION regress_testsub2 CONNECTION 'dbname=regress_doesnotexist' PUBLICATION testpub WITH (slot_name = NONE, enabled = false, create_slot = true);

Explanation: DDL from PostgreSQL core regression test for Subscription.


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

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

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


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

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


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

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


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

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

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


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

SELECT * FROM multiout_record_as('tuple', null, 2, false);

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


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

create function testpolym(a int, inout a int) returns int as $$ select 1;$$ language sql;

-- valid
create function testpolym(a int, out a int) returns int as $$ select $1;$$ language sql;

Explanation: DDL from PostgreSQL core regression test for Polymorphism.


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

SELECT '1'::seg && '0 .. 2'::seg AS bool;

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


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

UPDATE pk SET a = 90 WHERE a = 30 RETURNING *;

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


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

SELECT COUNT(*) FROM pg_stat_statements WHERE query LIKE '%FETCH FIRST%';

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


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

-- test with more than one reason to rewrite a single table
CREATE OR REPLACE FUNCTION test_evtrig_no_rewrite() RETURNS event_trigger
LANGUAGE plpgsql AS $$
BEGIN
  RAISE NOTICE 'Table ''%'' is being rewritten (reason = %)',
               pg_event_trigger_table_rewrite_oid()::regclass,
               pg_event_trigger_table_rewrite_reason();
END;
$$;

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


Question: Write the DML statement from PostgreSQL regression test 'tablespace' (example 61).

Explanation: DML from PostgreSQL core regression test for Tablespace.


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


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

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


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

SELECT sum(x::numeric), avg(x::numeric), var_pop(x::numeric)
FROM (VALUES ('1'), ('infinity')) v(x);

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

SELECT count(*) FROM (SELECT sum(x::numeric), avg(x::numeric), var_pop(x::numeric)
FROM (VALUES ('1'), ('infinity')) v(x)) AS _sub;


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

create or replace function perl_encode_typed_literal() returns setof text language plperl as $$
	return_next encode_typed_literal({a => 0, b => ['PL','/','Perl']}, 'perl_foo_pos');
$$;

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


Question: Write the DDL statement from PostgreSQL regression test 'inherit' (example 1).

Explanation: DDL from PostgreSQL core regression test for Inherit.


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

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

SELECT count(*) FROM (SELECT '2012-12-12 12:00'::timestamptz) AS _sub;


Question: pgTAP test for Functap (assertion 350).

SELECT * FROM check_test(
    isnt_strict( 'oww', ARRAY['int', 'text'], 'whatever' ),
    true,
    'isnt_strict(func, args, desc)',
    'whatever',
    ''
);

Explanation: SQL assertion from pgTAP test suite for Functap.


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

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


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

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

SELECT count(*) FROM (SELECT lpad('hello', 2)) AS _sub;


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

select * from pgstathashindex('test_hashidx');

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


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

INSERT INTO department VALUES (1, 0, 'A');

Explanation: DML from PostgreSQL core regression test for With.


Question: PostgreSQL Plpgsql: show example 40.

IF v_count > 0 THEN INSERT INTO users_count (count) VALUES (v_count); RETURN 't'; ELSE RETURN 'f'; END IF;

Explanation: Example from PostgreSQL documentation on Plpgsql.


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

-- Use hand-rolled hash functions and operator classes to get predictable
-- result on different machines.  See the definitions of
-- part_test_int4_ops and part_test_text_ops in test_setup.sql.

CREATE TABLE mchash (a int, b text, c jsonb)
  PARTITION BY HASH (a part_test_int4_ops, b part_test_text_ops);

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


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

INSERT INTO fk_partitioned_fk (a,b) VALUES (1500, 1501);


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

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

SELECT count(*) FROM (select 1 ^ 'NaN'::numeric) AS _sub;


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

SELECT nextval('sequence_test_temp1');  -- ok
SELECT nextval('sequence_test2');  -- error
ROLLBACK;

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

SELECT count(*) FROM (SELECT nextval('sequence_test_temp1');  -- ok
SELECT nextval('sequence_test2');  -- error
ROLLBACK) AS _sub;


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

INSERT INTO bool_tab VALUES (2, false, NULL);

Explanation: DML from PostgreSQL core regression test for Predicate.


Question: PostgreSQL Typeconv: show example 28.

SELECT NULL UNION SELECT NULL UNION SELECT 1; ERROR: UNION types text and integer cannot be matched;

Explanation: Example from PostgreSQL documentation on Typeconv.


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

SELECT server_name FROM postgres_fdw_get_connections() ORDER BY 1;

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


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

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

SELECT count(*) FROM (select jsonb_strip_nulls('null', true)) AS _sub;


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

create trigger table2_trig
  after insert on table2 referencing new table as new_table
  for each statement execute procedure dump_insert();

Explanation: DDL from PostgreSQL core regression test for Triggers.


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

UPDATE target SET balance = 0 WHERE tid = 3;

Explanation: DML from PostgreSQL core regression test for Merge.


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

INSERT INTO temporal_rng3 (id, valid_at) VALUES (NULL, daterange('2018-01-01', '2018-01-05'));

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


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

ALTER EXTENSION pgtap ADD FUNCTION cmp_ok (anyelement, text, anyelement, text);

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


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

SELECT TRIM(LEADING FROM '  bunch o blanks  ') = 'bunch o blanks  ' AS "bunch o blanks  ";

SELECT count(*) FROM (SELECT TRIM(LEADING FROM '  bunch o blanks  ') = 'bunch o blanks  ' AS "bunch o blanks  ") AS _sub;


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

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

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


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

SELECT * FROM test_timestamp WHERE i>'4714-11-23 17:00 BC'::timestamptz ORDER BY i;

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


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

CREATE TABLE plt2_p2 PARTITION OF plt2 FOR VALUES IN ('0001', '0005', '0002', '0009');

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


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

CREATE TABLE notnull_child_upg () INHERITS (notnull_parent_upg);

Explanation: DDL from PostgreSQL core regression test for Constraints.


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

CREATE FUNCTION cursor_aborted_subxact() RETURNS int AS $$
try:
    with plpy.subtransaction():
        cur = plpy.cursor("select * from generate_series(1, 20) as gen(i)")
        cur.fetch(10);
        plpy.execute("select no_such_function()")
except plpy.SPIError:
    fetched = cur.fetch(10)
    return int(fetched[5]["i"])
return 0 # not reached
$$ LANGUAGE plpython3u;

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


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

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


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

SELECT pg_catalog.pg_clear_relation_stats(schemaname => 'stats_import', relname => 'testview');

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

SELECT count(*) FROM (SELECT pg_catalog.pg_clear_relation_stats(schemaname => 'stats_import', relname => 'testview')) AS _sub;


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

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


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

SELECT * FROM test_float4 WHERE i<='Inf'::float8 ORDER BY i;


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

SELECT count(*) FROM (SELECT jsonb_typeof('null') AS "null") AS _sub;


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

CREATE FUNCTION test_type_conversion_array_tuple() RETURNS text[] AS $$
return ('abc', 'def')
$$ LANGUAGE plpython3u;

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


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

create rule rtest_emp_ins as on insert to rtest_emp do
	insert into rtest_emplog values (new.ename, current_user,
			'hired', new.salary, '0.00');

Explanation: DDL from PostgreSQL core regression test for Rules.


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

Explanation: DML from PostgreSQL core regression test for Inherit.


Question: Show a SQL definition from the zombodb project (issue-864, item 3).

CREATE INDEX es_idx_cake_brand on cake.brand
    USING zombodb ((brand.*))
    WITH (max_analyze_token_count='10000000', max_terms_count='2147483647');

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


Question: pgTAP test for Hastap (assertion 176).

SELECT * FROM check_test(
  has_operator( 'int4', 'pg_catalog', '<=', 'integer', 'boolean'::name ),
  true,
  'has_operator( left, schema, name, right, result )',
  'Operator pg_catalog.<=(int4,integer) RETURNS boolean should exist',
  ''
);

Explanation: SQL assertion from pgTAP test suite for Hastap.


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

SELECT TRIM(BOTH 'x' FROM 'xxxxxsome Xsxxxxx') = 'some Xs' AS "some Xs";

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

SELECT count(*) FROM (SELECT TRIM(BOTH 'x' FROM 'xxxxxsome Xsxxxxx') = 'some Xs' AS "some Xs") AS _sub;


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

SELECT 'init' FROM pg_create_physical_replication_slot('physical_slot');

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


Question: Write the DML statement from PostgreSQL regression test 'subselect' (example 22).

INSERT INTO SUBSELECT_TBL VALUES (8, 9, NULL);

Explanation: DML from PostgreSQL core regression test for Subselect.


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

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


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

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

SELECT count(*) FROM (SELECT to_tsquery('english', '(asd&and)|fghj')) AS _sub;


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

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


Question: Show a SQL definition from the timescaledb project (size_utils, item 33).

CREATE OR REPLACE FUNCTION _timescaledb_functions.range_value_to_pretty(
    time_value      BIGINT,
    column_type     REGTYPE
)
    RETURNS TEXT LANGUAGE PLPGSQL STABLE AS
$BODY$
DECLARE
BEGIN
    IF NOT (time_value > (-9223372036854775808)::bigint AND
	   	    time_value < 9223372036854775807::bigint) THEN
        RETURN '';

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


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

CREATE TABLE owned_by_me (
	a int
) PARTITION BY LIST (a);

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


Question: pgTAP test for Index (assertion 67).

SELECT * FROM check_test(
    index_is_unique( 'blahblah' ),
    false,
    'index_is_unique() no such index',
    'Index blahblah should be unique',
    ''
);

Explanation: SQL assertion from pgTAP test suite for Index.


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


Question: Write the DDL statement from PostgreSQL regression test 'bit' (example 37).

CREATE TABLE bit_table (a BIT(16), b BIT(16));

Explanation: DDL from PostgreSQL core regression test for Bit.


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

SELECT * FROM return_record('999') AS r(val text, t integer);

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


Question: Show a SQL definition from the timescaledb project (hash, item 37).

-- Test hashing Var values
CREATE TABLE hash_test(id int, value text);


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

CREATE FUNCTION myvarcharin(cstring, oid, integer) RETURNS myvarchar
LANGUAGE internal IMMUTABLE PARALLEL SAFE STRICT AS 'varcharin';

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


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

CREATE FOREIGN DATA WRAPPER foo; -- ERROR
RESET ROLE;

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


Question: Write the DDL statement from PostgreSQL regression test 'eager_aggregate' (example 54).

CREATE TABLE eager_agg_tab2_p3 PARTITION OF eager_agg_tab2 FOR VALUES FROM (10) TO (15);

Explanation: DDL from PostgreSQL core regression test for Eager Aggregate.


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

select interval '2147483647 months 0.1 decades';

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

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


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

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

SELECT count(*) FROM (SELECT to_char(q2, 'L9999999999999999.000')  FROM INT8_TBL) AS _sub;


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

CREATE OR REPLACE FUNCTION @extschema@.time_bucket_gapfill(bucket_width BIGINT, ts BIGINT, start BIGINT=NULL, finish BIGINT=NULL) RETURNS BIGINT
	AS '@MODULE_PATHNAME@', 'ts_gapfill_int64_bucket' LANGUAGE C VOLATILE PARALLEL SAFE;


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

SELECT regexp_match('foobarbequebaz'::citext, '(BAR)(BEQUE)'::citext) = ARRAY[ 'bar', 'beque' ] AS t;

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


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

CREATE TABLE truncpart_2_d PARTITION OF truncpart_2 DEFAULT;

Explanation: DDL from PostgreSQL core regression test for Truncate.


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

create view view_of_joins_2d as select * from (tbl1 join tbl1a using (a) as x) as y;

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


Question: Write the DDL statement from PostgreSQL regression test 'sqljson' (example 177).

CREATE VIEW json_objectagg_view AS
SELECT JSON_OBJECTAGG(i: ('111' || i)::bytea FORMAT JSON WITH UNIQUE RETURNING text) FILTER (WHERE i > 3)
FROM generate_series(1,5) i;

Explanation: DDL from PostgreSQL core regression test for Sqljson.


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

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

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


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

SELECT proname, prosecdef FROM pg_proc
       WHERE oid in ('functest_C_1'::regproc,
                     'functest_C_2'::regproc,
                     'functest_C_3'::regproc) ORDER BY proname;

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

SELECT count(*) FROM (SELECT proname, prosecdef FROM pg_proc
       WHERE oid in ('functest_C_1'::regproc,
                     'functest_C_2'::regproc,
                     'functest_C_3'::regproc) ORDER BY proname) AS _sub;


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

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

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


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

CREATE OR REPLACE FUNCTION _timescaledb_functions.create_compressed_chunk(
    chunk REGCLASS,
    chunk_table REGCLASS,
    uncompressed_heap_size BIGINT,
    uncompressed_toast_size BIGINT,
    uncompressed_index_size BIGINT,
    compressed_heap_size BIGINT,
    compressed_toast_size BIGINT,
    compressed_index_size BIGINT,
    numrows_pre_compression BIGINT,
    numrows_post_compression BIGINT
) RETURNS REGCLASS AS '@MODULE_PATHNAME@', 'ts_create_compressed_chunk' LANGUAGE C STRICT VOLATILE;

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


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

SELECT point(f1) AS center
   FROM CIRCLE_TBL;

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

SELECT count(*) FROM (SELECT point(f1) AS center
   FROM CIRCLE_TBL) AS _sub;


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

INSERT INTO tr_sub(path) VALUES ('1-top-1-#1');

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


Question: pgTAP test for Functap (assertion 64).

SELECT * FROM check_test(
    function_lang_is( 'someschema', 'huh', 'sql', 'whatever' ),
    true,
    'function_lang_is(schema, func, sql, desc)',
    'whatever',
    ''
);

Explanation: SQL assertion from pgTAP test suite for Functap.


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

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


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

create table parted_conflict_1 partition of parted_conflict for values from (0) to (1000) partition by range (a);

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


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

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

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


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

CREATE OR REPLACE PROCEDURE _timescaledb_functions.policy_reorder(job_id INTEGER, config JSONB)
AS '@MODULE_PATHNAME@', 'ts_policy_reorder_proc'
LANGUAGE C;


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

SELECT count(*) FROM (select interval '9223372036854.775807 seconds') AS _sub;


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

select 'aa=>b, c=>d , b=>16'::hstore->'aa';


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

SELECT count(*) FROM (SELECT to_char(q2, '0999999999999999')       FROM INT8_TBL) AS _sub;


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

ALTER EXTENSION pgtap ADD FUNCTION throws_ok ( TEXT, CHAR(5), TEXT, TEXT );

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


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

INSERT INTO fract_only VALUES (3, '1.0');	-- should fail
INSERT INTO fract_only VALUES (4, '-0.9999');

Explanation: DML from PostgreSQL core regression test for Numeric.


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

INSERT INTO d_star (class, a, c, d)
   VALUES ('d', 10, 'hi kristin'::name, '10.01'::float8);

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


Question: pgTAP test for Hastap (assertion 63).

SELECT * FROM check_test(
    has_sequence( 'foo', '__SDFSDFD__', 'desc' ),
    false,
    'has_sequence(sch, non-existent sequence, desc)',
    'desc',
    ''
);

Explanation: SQL assertion from pgTAP test suite for Hastap.


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

SELECT count(*) from more__int WHERE a = '{73,23,20}';

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


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

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

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


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

CREATE OR REPLACE FUNCTION _ikeys( NAME, NAME, NAME)
RETURNS TEXT[] AS $$
    SELECT ARRAY(
        SELECT pg_catalog.pg_get_indexdef( ci.oid, s.i + 1, false)
          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
          JOIN generate_series(0, current_setting('max_index_keys')::int - 1) s(i)
            ON x.indkey[s.i] IS NOT NULL
         WHERE ct.relname = $2
           AND ci.relname = $3
           AND n.nspname  = $1
         ORDER BY s.i
    );
$$ LANGUAGE sql;

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


Question: PostgreSQL regression test 'publication': Write the SELECT query (example 69).

SELECT pubname, puballtables, puballsequences FROM pg_publication WHERE pubname = 'regress_pub_forallsequences1';

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

SELECT count(*) FROM (SELECT pubname, puballtables, puballsequences FROM pg_publication WHERE pubname = 'regress_pub_forallsequences1') AS _sub;


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

CREATE OPERATOR < (
        LEFTARG = ltree,
	RIGHTARG = ltree,
	PROCEDURE = ltree_lt,
        COMMUTATOR = '>',
	NEGATOR = '>=',
        RESTRICT = contsel,
	JOIN = contjoinsel
);

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


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

SELECT set_byte('\x1234567890abcdef00'::bytea, 99, 11);  -- error

--
-- conversions between bytea and integer types
--
SELECT 0x1234::int2::bytea AS "\x1234", (-0x1234)::int2::bytea AS "\xedcc";

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

SELECT count(*) FROM (SELECT set_byte('\x1234567890abcdef00'::bytea, 99, 11);  -- error

--
-- conversions between bytea and integer types
--
SELECT 0x1234::int2::bytea AS "\x1234", (-0x1234)::int2::bytea AS "\xedcc") AS _sub;


Question: pgTAP test for Ownership (assertion 31).

/****************************************************************************/
-- Test relation_owner_is() with a partition.
SELECT * FROM check_test(
    relation_owner_is('public', 'apart', current_user, 'mumble'),
	true,
    'relation_owner_is(sch, part, user, desc)',
    'mumble',
    ''
);

Explanation: SQL assertion from pgTAP test suite for Ownership.


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

insert into part_default_p2 values ('de', 35);

Explanation: DML from PostgreSQL core regression test for Insert.


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

SELECT count(*) FROM point_tbl WHERE f1 <@ circle '<(50,50),50>';

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

SELECT count(*) FROM (SELECT count(*) FROM point_tbl WHERE f1 <@ circle '<(50,50),50>') AS _sub;


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

SELECT data FROM pg_logical_slot_get_changes('regression_slot', NULL, NULL, 'include-xids', '0', 'skip-empty-xacts', '1');

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


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

insert into insertconflicttest as t values (23, 'Blackberry') on conflict (key) where fruit like '%berry' and t.fruit = 'inconsequential' do nothing;

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


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

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


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

-- ensure dependencies are straight
DROP FUNCTION myvarcharsend(myvarchar);  -- fail
DROP TYPE myvarchar;  -- fail

DROP TYPE myvarchar CASCADE;

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


Question: Write the DDL statement from PostgreSQL regression test 'window' (example 292).

CREATE INDEX empsalary_salary_empno_idx ON empsalary (salary, empno);

Explanation: DDL from PostgreSQL core regression test for Window.


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

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

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


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

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


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

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

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


Question: Write the DDL statement from PostgreSQL regression test 'temp' (example 98).

create temp table temp_parted_oncommit_test2
  partition of temp_parted_oncommit_test
  for values in (2) on commit drop;

Explanation: DDL from PostgreSQL core regression test for Temp.


Question: pgTAP test for Resultset (assertion 281).

INSERT INTO dupes (id, name) VALUES(86, 'Angelina');

Explanation: SQL assertion from pgTAP test suite for Resultset.


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

SELECT ia FROM jsonb_populate_record(NULL::jsbrec, '{"ia": [1, "2", null, 4]}') q;

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

SELECT count(*) FROM (SELECT ia FROM jsonb_populate_record(NULL::jsbrec, '{"ia": [1, "2", null, 4]}') q) AS _sub;


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


Question: pgTAP test for Hastap (assertion 254).

SELECT * FROM check_test(
    domain_type_is( 'public', 'zip_code', 'pg_catalog', 'int', 'whatever'),
    false,
    'domain_type_is(schema, nondomain, schema, type, desc)',
    'whatever',
    '   Domain public.zip_code does not exist'
);

Explanation: SQL assertion from pgTAP test suite for Hastap.


Question: pgTAP test for Index (assertion 53).

SELECT * FROM check_test(
    hasnt_index( 'sometab', 'idx_blah', 'whatever' ),
    true,
    'hasnt_index(table, non-index, desc)',
    'whatever',
    ''
);

Explanation: SQL assertion from pgTAP test suite for Index.


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

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


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

-- test encode_array_literal

create or replace function perl_encode_array_literal() returns setof text language plperl as $$
	return_next encode_array_literal(undef);
	return_next encode_array_literal(0);
	return_next encode_array_literal(42);
	return_next encode_array_literal($_)
		for [], [0], [1..5], [[]], [[1,2,[3]],4];
	return_next encode_array_literal($_,'|')
		for [], [0], [1..5], [[]], [[1,2,[3]],4];
	return undef;
$$;

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


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

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


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

SELECT 'i_dio' NOT LIKE 'i$_d_o' ESCAPE '$' AS "false";

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

SELECT count(*) FROM (SELECT 'i_dio' NOT LIKE 'i$_d_o' ESCAPE '$' AS "false") AS _sub;


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

Explanation: DML from PostgreSQL core regression test for Domain.


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

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

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


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

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

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

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


Question: pgTAP test for Resultset (assertion 169).

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


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

SELECT * FROM sj j1, sj j2
WHERE j1.b = j2.b
  AND (j1.a*j1.c/3) = (random()/3 + 3)::int
  AND (random()/3 + 3)::int = (j2.a*j2.c/3);

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

SELECT count(*) FROM (SELECT * FROM sj j1, sj j2
WHERE j1.b = j2.b
  AND (j1.a*j1.c/3) = (random()/3 + 3)::int
  AND (random()/3 + 3)::int = (j2.a*j2.c/3)) AS _sub;


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

update utrtest set b = b || b from (values (1), (2)) s(x) where a = s.x
  returning *, tableoid::regclass, xmin = pg_current_xact_id()::xid as xmin_ok;

Explanation: DML from PostgreSQL core regression test for Update.


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

SELECT ia2 FROM jsonb_populate_record(NULL::jsbrec, '{"ia2": [[1, 2], 3, 4]}') q;

SELECT count(*) FROM (SELECT ia2 FROM jsonb_populate_record(NULL::jsbrec, '{"ia2": [[1, 2], 3, 4]}') q) AS _sub;


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

-- Sanity check on the previous table, checking that all core types are
-- included in this table.
SELECT oid, typname, typtype, typelem, typarray
  FROM pg_type t
  WHERE oid < 16384 AND
    -- Exclude pseudotypes and composite types.
    typtype NOT IN ('p', 'c') AND
    -- These reg* types cannot be pg_upgraded, so discard them.
    oid != ALL(ARRAY['regproc', 'regprocedure', 'regoper',
                     'regoperator', 'regconfig', 'regdictionary',
                     'regnamespace', 'regcollation']::regtype[]) AND
    -- Discard types that do not accept input values as these cannot be
    -- tested easily.
    -- Note: XML might be disabled at compile-time.
    oid != ALL(ARRAY['gtsvector', 'pg_node_tree',
                     'pg_ndistinct', 'pg_dependencies', 'pg_mcv_list',
                     'pg_brin_bloom_summary',
                     'pg_brin_minmax_multi_summary', 'xml']::regtype[]) AND
    -- Discard arrays.
    NOT EXISTS (SELECT 1 FROM pg_type u WHERE u.typarray = t.oid)
    -- Exclude everything from the table created above.  This checks
    -- that no in-core types are missing in tab_core_types.
    AND NOT EXISTS (SELECT 1
                    FROM pg_attribute a
                    WHERE a.atttypid=t.oid AND
                          a.attnum > 0 AND
                          a.attrelid='tab_core_types'::regclass);

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


Question: Show a SQL definition from the zombodb project (zombodb--3000.0.3--3000.0.4, item 19).

CREATE OR REPLACE FUNCTION zdb.auto_date_histogram_agg(aggregate_name text, field text, buckets int8, format text DEFAULT NULL, minimum_interval zdb.intervals DEFAULT NULL, missing text DEFAULT NULL) RETURNS jsonb AS 'MODULE_PATHNAME', 'auto_date_histogram_agg_wrapper' IMMUTABLE LANGUAGE c PARALLEL SAFE;

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


Question: Write the DDL statement from PostgreSQL regression test 'encoding' (example 42).

CREATE TABLE encoding_tests (encoding text, description text, input bytea);

Explanation: DDL from PostgreSQL core regression test for Encoding.


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

CREATE TABLE quuux_default PARTITION OF quuux DEFAULT PARTITION BY LIST (b);

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


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

PREPARE fooplan (int, text, bool, numeric) AS INSERT INTO foo VALUES($1, $2, $3, $4); EXECUTE fooplan(1, 'Hunter Valley', 't', 200.00);

Explanation: PostgreSQL PREPARE command.


Question: pgTAP test for Ruletap (assertion 36).

SELECT * FROM check_test(
    rule_is_on( 'public', 'sometab', 'upd_me', 'update', 'whatever' ),
    true,
    'rule_is_on(schema, table, rule, update, desc)',
    'whatever',
    ''
);

Explanation: SQL assertion from pgTAP test suite for Ruletap.


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

SELECT tableoid::regclass, * FROM ONLY a;

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


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

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


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

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


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

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

SELECT count(*) FROM (select return_int_input(1) not in (10, 9, 2, 8, 3, 7, 4, 6, 5, 1)) AS _sub;


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

-- Drop chunks older than the given timestamp for the specific
-- hypertable or continuous aggregate.
CREATE OR REPLACE FUNCTION @extschema@.drop_chunks(
    relation               REGCLASS,
    older_than             "any" = NULL,
    newer_than             "any" = NULL,
    verbose                BOOLEAN = FALSE,
    created_before         "any" = NULL,
    created_after          "any" = NULL
) RETURNS SETOF TEXT AS '@MODULE_PATHNAME@', 'ts_chunk_drop_chunks'
LANGUAGE C VOLATILE PARALLEL UNSAFE;

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


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

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


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

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

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

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


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

CREATE TABLE shoelace_data (
	sl_name    char(10),      -- primary key
	sl_avail   integer,       -- available # of pairs
	sl_color   char(10),      -- shoelace color
	sl_len     float,         -- shoelace length
	sl_unit    char(8)        -- length unit
);

Explanation: DDL from PostgreSQL core regression test for Rules.


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

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

SELECT count(*) FROM (select jsonb '[1]' @? '$[0.5]') AS _sub;


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

SELECT count(*) FILTER (WHERE r < -1.5 OR r > 1.5) AS out_of_range,
       (count(*) FILTER (WHERE r < -1.47)) > 0 AS has_small,
       (count(*) FILTER (WHERE r > 1.47)) > 0 AS has_large
FROM (SELECT random(-1.500000000000000, 1.500000000000000) r
      FROM generate_series(1, 2000)) ss;

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

SELECT count(*) FROM (SELECT count(*) FILTER (WHERE r < -1.5 OR r > 1.5) AS out_of_range,
       (count(*) FILTER (WHERE r < -1.47)) > 0 AS has_small,
       (count(*) FILTER (WHERE r > 1.47)) > 0 AS has_large
FROM (SELECT random(-1.500000000000000, 1.500000000000000) r
      FROM generate_series(1, 2000)) ss) AS _sub;


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

insert into cities values ('Las Vegas', 2.583E+5, 2174);

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


Question: PostgreSQL regression test 'brin_multi': Write the SELECT query (example 99).

SELECT COUNT(*) FROM brin_test_multi_1 WHERE a > 71;

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

SELECT count(*) FROM (SELECT COUNT(*) FROM brin_test_multi_1 WHERE a > 71) AS _sub;


Question: PostgreSQL Ddl: show example 106.

CREATE INDEX measurement_y2006m02_logdate ON measurement_y2006m02 (logdate); CREATE INDEX measurement_y2006m03_logdate ON measurement_y2006m03 (logdate); CREATE INDEX measurement_y2007m11_logdate ON measurement_y2007m11 (logdate); CREATE INDEX measurement_y2007m12_logdate ON measurement_y2007m12 (logdate); CREATE INDEX measurement_y2008m01_logdate ON measurement_y2008m01 (logdate);

Explanation: Example from PostgreSQL documentation on Ddl.


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

SELECT ctid FROM tidrangescan WHERE ctid > '(2,8)';

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

SELECT count(*) FROM (SELECT ctid FROM tidrangescan WHERE ctid > '(2,8)') AS _sub;


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

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


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

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


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

CREATE OPERATOR @@ (
	LEFTARG = _int4,
	RIGHTARG = query_int,
	PROCEDURE = boolop,
	COMMUTATOR = '~~',
	RESTRICT = _int_matchsel,
	JOIN = contjoinsel
);

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


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

select array_agg(ten) 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(ten) from (select ten from tenk1 where unique1 < 15 order by unique1) ss) AS _sub;


Question: pgTAP test for Unique (assertion 25).

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

Explanation: SQL assertion from pgTAP test suite for Unique.


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

SELECT cube_ll_coord(earth_box(ll_to_earth(0,0),10*earth()),1)::numeric(20,5),
       cube_ll_coord(earth_box(ll_to_earth(0,0),10*earth()),2)::numeric(20,5),
       cube_ll_coord(earth_box(ll_to_earth(0,0),10*earth()),3)::numeric(20,5),
       cube_ur_coord(earth_box(ll_to_earth(0,0),10*earth()),1)::numeric(20,5),
       cube_ur_coord(earth_box(ll_to_earth(0,0),10*earth()),2)::numeric(20,5),
       cube_ur_coord(earth_box(ll_to_earth(0,0),10*earth()),3)::numeric(20,5);

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


Question: pgTAP test for Roletap (assertion 11).

SELECT * FROM check_test(
    roles_are( ___myroles(''), 'whatever' ),
    true,
    'roles_are(roles, desc)',
    'whatever',
    ''
);

Explanation: SQL assertion from pgTAP test suite for Roletap.


Question: pgTAP test for Index (assertion 61).

SELECT * FROM check_test(
    index_is_unique( 'sometab', 'sometab_pkey' ),
    true,
    'index_is_unique() on pk no schema',
    'Index sometab_pkey should be unique',
    ''
);

Explanation: SQL assertion from pgTAP test suite for Index.


Question: pgTAP test for Proctap (assertion 1).

\unset ECHO
\i test/setup.sql

SELECT plan(192);

Explanation: SQL assertion from pgTAP test suite for Proctap.


Question: PostgreSQL Xfunc: show example 11.

CREATE FUNCTION getfoo(int) RETURNS SETOF foo AS $$ SELECT * FROM foo WHERE fooid = $1; $$ LANGUAGE SQL; SELECT * FROM getfoo(1) AS t1;

Explanation: Example from PostgreSQL documentation on Xfunc.


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

select jsonb_insert('{"a": []}', '{a, 1}', '"new_value"', true);

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

SELECT count(*) FROM (select jsonb_insert('{"a": []}', '{a, 1}', '"new_value"', true)) AS _sub;


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

create view vv2a as
select * from (values(now(),2,3,now(),5)) v(a,b,c,d,e)
union all
select * from tt7a left join tt8a using (x), tt8a tt8ax;

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


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

CREATE OPERATOR <= (
	PROCEDURE = isnle,
	LEFTARG = ean13,
	RIGHTARG = issn13,
	COMMUTATOR = >=,
	NEGATOR = >,
	RESTRICT = scalarltsel,
	JOIN = scalarltjoinsel);


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

--
-- pgp_pub_encrypt(data, key, args)
--
CREATE FUNCTION pgp_pub_encrypt(text, bytea, text)
RETURNS bytea
AS 'MODULE_PATHNAME', 'pgp_pub_encrypt_text'
LANGUAGE C STRICT PARALLEL SAFE;


Question: Write the DML statement from PostgreSQL regression test 'sqljson_queryfuncs' (example 200).

INSERT INTO test_jsonb_constraints VALUES ('[]');

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


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

SELECT count(*) FROM testjsonb WHERE j @@ 'exists($.public) && exists($.disabled)';

SELECT count(*) FROM (SELECT count(*) FROM testjsonb WHERE j @@ 'exists($.public) && exists($.disabled)') AS _sub;


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

CREATE VIEW street AS
   SELECT r.name, r.thepath, c.cname AS cname
   FROM ONLY road r, real_city c
   WHERE c.outline ?# r.thepath;


Question: Write the DML statement from PostgreSQL regression test 'join' (example 769).

update xx1 set x2 = f1 from lateral (select * from int4_tbl where f1 = x1) ss;

Explanation: DML from PostgreSQL core regression test for Join.


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

create policy p1 on ec1 using (f1 < '5'::int8alias1);

Explanation: DDL from PostgreSQL core regression test for Equivclass.


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

CREATE FUNCTION zdb.schema_version() RETURNS text LANGUAGE sql AS $$
SELECT '3000.0.1 (8573638e96d98024a0e64e350d30bcbdac568385)'
$$;

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


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

CREATE TABLE cake.flavor
(
    pk_flavor    SERIAL8 NOT NULL PRIMARY KEY,
    fk_flv_to_bd bigint,
    flv_name     varchar,
    flv_color    varchar
);


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

-- calling a trigger function directly

SELECT stupid7();

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


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

insert into cth values(DEFAULT,'test2','02 March 2003','volts','3.1234');

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


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

CREATE TABLE tp1 partition OF temporal_partitioned_rng FOR VALUES IN ('[1,2)', '[3,4)', '[5,6)', '[7,8)', '[9,10)', '[11,12)');

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


Question: pgTAP test for Coltap (assertion 15).

SELECT * FROM check_test(
    col_not_null( 'sometab', 'foo' ),
    false,
    'col_not_null( table, noncolumn ) fail',
    'Column sometab.foo should be NOT NULL',
    '    Column sometab.foo does not exist'
);

Explanation: SQL assertion from pgTAP test suite for Coltap.


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

SELECT (@@ f1) AS center
   FROM POLYGON_TBL
   WHERE (# f1) > 2;

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

SELECT count(*) FROM (SELECT (@@ f1) AS center
   FROM POLYGON_TBL
   WHERE (# f1) > 2) AS _sub;


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

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

SELECT count(*) FROM (SELECT pg_snapshot '1:9223372036854775808:3') AS _sub;


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

create function tcl_int4le(int4,int4) returns bool as '
    if {$1 <= $2} {
        return t
    }
    return f
' language pltcl;

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


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

CREATE INDEX ON test_jsonb_mutability (JSON_QUERY(js, '$.a ? (@.time() < $.datetime("HH:MI TZH"))'));

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


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

SELECT c1,c2,c3 FROM ft2 WHERE CASE WHEN c1 > 990 THEN c1 END < 1000 ORDER BY c1;

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


Question: pgTAP test for Resultset (assertion 420).

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

Explanation: SQL assertion from pgTAP test suite for Resultset.


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

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

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


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

CREATE INDEX sp_kd_ind ON kd_point_tbl USING spgist (p kd_point_ops);

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


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

CREATE OPERATOR >= (
	PROCEDURE = isnge,
	LEFTARG = ean13,
	RIGHTARG = ismn13,
	COMMUTATOR = <=,
	NEGATOR = <,
	RESTRICT = scalargtsel,
	JOIN = scalargtjoinsel);

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


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

CREATE STATISTICS ctlt1_a_b_stat ON a,b FROM ctlt1;

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


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

select c2, least_agg(c1) from ft1 where c2 < 100 group by c2 order by c2;


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

-- Alias for compress_chunk above.
CREATE OR REPLACE PROCEDURE @extschema@.convert_to_columnstore(
    chunk REGCLASS,
    if_not_columnstore BOOLEAN = true,
    recompress BOOLEAN = false
) AS '@MODULE_PATHNAME@', 'ts_compress_chunk' LANGUAGE C;

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


Question: pgTAP test for Index (assertion 28).

SELECT * FROM check_test(
    has_index( 'public', 'sometab', 'idx_foo'::name ),
    true,
    'has_index() no cols hash index no desc',
    'Index idx_foo should exist',
    ''
);

Explanation: SQL assertion from pgTAP test suite for Index.


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

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

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


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

SELECT EXTRACT(CENTURY FROM INTERVAL '100 y');

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

SELECT count(*) FROM (SELECT EXTRACT(CENTURY FROM INTERVAL '100 y')) AS _sub;


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

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


Question: PostgreSQL Ddl: show example 37.

CREATE TABLE products ( product_no integer PRIMARY KEY, name text, price numeric ); CREATE TABLE orders ( order_id integer PRIMARY KEY, shipping_address text, ... ); CREATE TABLE order_items ( product_no integer REFERENCES products, order_id integer REFERENCES orders, quantity integer, PRIMARY KEY (product_no, order_id) );

Explanation: Example from PostgreSQL documentation on Ddl.


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

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


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

insert into rtest_unitfact values ('inch', 2.54);

Explanation: DML from PostgreSQL core regression test for Rules.


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

CREATE OR REPLACE FUNCTION _timescaledb_functions.bloom1_contains(_timescaledb_internal.bloom1, anyelement)
RETURNS bool
AS '@MODULE_PATHNAME@', 'ts_bloom1_contains'
LANGUAGE C IMMUTABLE PARALLEL SAFE;


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

select count(*) from testhstore where h @> 'wait=>CC, public=>t';

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


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

create table part_aa_bb partition of list_parted FOR VALUES IN ('aa', 'bb');

Explanation: DDL from PostgreSQL core regression test for Insert.


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

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

SELECT count(*) FROM (select fcompos3(row(3,'three'))) AS _sub;


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

INSERT INTO PKTABLE VALUES (2, 'Test2');

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


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

CREATE FUNCTION functest_A_2(text[]) RETURNS int LANGUAGE 'sql'
       AS 'SELECT $1[1]::int';

Explanation: DDL from PostgreSQL core regression test for Create Function Sql.


Question: PostgreSQL Perform: show example 37.

EXPLAIN ANALYZE SELECT four, unique1 FROM tenk1 WHERE four BETWEEN 1 AND 3 AND unique1 = 42; QUERY PLAN -------------------------------------------------------------------&zwsp;--------------------------------------------------------------- Index Only Scan using tenk1_four_unique1_idx on tenk1 (cost=0.29..6.90 rows=1 width=8) (actual time=0.006..0.007 rows=1.00 loops=1) Index Cond: ((four >= 1) AND (four <= 3) AND (unique1 = 42)) Heap Fetches: 0 Index Searches: 3 Buffers: shared hit=7 Planning Time: 0.029 ms Execution Time: 0.012 ms;

Explanation: Example from PostgreSQL documentation on Perform.


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

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


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

select count(*) from test_multirange_gist where mr &< int4multirange(int4range(100,200), int4range(400,500));

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

SELECT count(*) FROM (select count(*) from test_multirange_gist where mr &< int4multirange(int4range(100,200), int4range(400,500))) AS _sub;


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

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

SELECT count(*) FROM (SELECT m > '$124.00' FROM money_data) AS _sub;


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

/* reorder policy */
CREATE OR REPLACE FUNCTION @extschema@.add_reorder_policy(
    hypertable REGCLASS,
    index_name NAME,
    if_not_exists BOOL = false,
    initial_start timestamptz = NULL,
    timezone TEXT = NULL
) RETURNS INTEGER
AS '@MODULE_PATHNAME@', 'ts_policy_reorder_add'
LANGUAGE C VOLATILE;

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


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

CREATE TABLE clstrpart2 PARTITION OF clstrpart FOR VALUES FROM (10) TO (20);

Explanation: DDL from PostgreSQL core regression test for Cluster.


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

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

COMMIT;

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

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

COMMIT) AS _sub;


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

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

Explanation: DML from PostgreSQL core regression test for Timestamptz.


Question: pgTAP test for Todotap (assertion 14).

SELECT is(
    ARRAY(
        SELECT fail('This is a todo test 1') AS stuff
        UNION
        SELECT todo::text FROM todo('inside')
        UNION
        SELECT fail('This is a todo test 2')
        UNION
        SELECT fail('This is a todo test 3')
        ORDER BY stuff
    ),
    ARRAY[
        'not ok 25 - This is a todo test 1 # TODO just because
# Failed (TODO) test 25: "This is a todo test 1"',
        'not ok 26 - This is a todo test 2 # TODO inside
# Failed (TODO) test 26: "This is a todo test 2"',
        'not ok 27 - This is a todo test 3 # TODO just because
# Failed (TODO) test 27: "This is a todo test 3"'
    ],
    'Nested todos should work properly'
);

Explanation: SQL assertion from pgTAP test suite for Todotap.


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

SELECT * FROM test_type_record_as('dict', null, null, false);

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


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

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


Question: PostgreSQL Queries: show example 50.

WITH w AS NOT MATERIALIZED ( SELECT * FROM big_table ) SELECT * FROM w AS w1 JOIN w AS w2 ON w1.key = w2.ref WHERE w2.key = 123;

Explanation: Example from PostgreSQL documentation on Queries.


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

CREATE FUNCTION upc(ean13)
RETURNS upc
AS 'MODULE_PATHNAME', 'upc_cast_from_ean13'
LANGUAGE C IMMUTABLE STRICT PARALLEL SAFE;

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


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

SELECT t1.a, t1.c, t2.b, t2.c FROM prt1_l t1 RIGHT JOIN prt2_l t2 ON t1.a = t2.b AND t1.c = t2.c WHERE t2.a = 0 ORDER BY t1.a, t2.b;

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

SELECT count(*) FROM (SELECT t1.a, t1.c, t2.b, t2.c FROM prt1_l t1 RIGHT JOIN prt2_l t2 ON t1.a = t2.b AND t1.c = t2.c WHERE t2.a = 0 ORDER BY t1.a, t2.b) AS _sub;


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

SELECT multirange_minus_multi(nummultirange(numrange(1,2), numrange(4,5)), nummultirange(numrange(3,5)));

SELECT count(*) FROM (SELECT multirange_minus_multi(nummultirange(numrange(1,2), numrange(4,5)), nummultirange(numrange(3,5)))) AS _sub;


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

-- check that we can "use" a module that has already been loaded
-- runtime error: "Can't use string ("foo") as a SCALAR ref while "strict refs" in use
DO $do$ use strict; my $name = "foo"; my $ref = $$name; $do$ LANGUAGE plperl;

-- check that we can "use warnings" (in this case to turn a warn into an error)
-- yields "ERROR:  Useless use of sort in void context."
DO $do$ use warnings FATAL => qw(void) ; my @y; sort @y; 1; $do$ LANGUAGE plperl;

-- make sure functions marked as VOID without an explicit return work
CREATE OR REPLACE FUNCTION myfuncs() RETURNS void AS $$
   $_SHARED{myquote} = sub {
       my $arg = shift;

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


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

CREATE TABLE inh_error1 () INHERITS (ctlt1, ctlt4);

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


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

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


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

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

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


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

end $$;
call p1();

-- clean up
alter event trigger regress_event_trigger disable;
drop table event_trigger_fire2, event_trigger_fire3, event_trigger_fire4, event_trigger_fire5, event_trigger_fire6, event_trigger_fire7;
drop routine f1(), p1();

-- regress_event_trigger_end should fire on these commands
grant all on table event_trigger_fire1 to public;
comment on table event_trigger_fire1 is 'here is a comment';
revoke all on table event_trigger_fire1 from public;
drop table event_trigger_fire1;
create foreign data wrapper useless;
create server useless_server foreign data wrapper useless;
create user mapping for regress_evt_user server useless_server;
alter default privileges for role regress_evt_user
 revoke delete on tables from regress_evt_user;

-- alter owner to non-superuser should fail
alter event trigger regress_event_trigger owner to regress_evt_user;

-- alter owner to superuser should work
alter role regress_evt_user superuser;
alter event trigger regress_event_trigger owner to regress_evt_user;

-- should fail, name collision
alter event trigger regress_event_trigger rename to regress_event_trigger2;

-- OK
alter event trigger regress_event_trigger rename to regress_event_trigger3;

-- should fail, doesn't exist any more
drop event trigger regress_event_trigger;

-- should fail, regress_evt_user owns some objects
drop role regress_evt_user;

-- cleanup before next test
-- these are all OK; the second one should emit a NOTICE
drop event trigger if exists regress_event_trigger2;
drop event trigger if exists regress_event_trigger2;
drop event trigger regress_event_trigger3;
drop event trigger regress_event_trigger_end;

-- test support for dropped objects
CREATE SCHEMA schema_one authorization regress_evt_user;
CREATE SCHEMA schema_two authorization regress_evt_user;
CREATE SCHEMA audit_tbls authorization regress_evt_user;
CREATE TEMP TABLE a_temp_tbl ();
SET SESSION AUTHORIZATION regress_evt_user;

CREATE TABLE schema_one.table_one(a int);
CREATE TABLE schema_one."table two"(a int);
CREATE TABLE schema_one.table_three(a int);
CREATE TABLE audit_tbls.schema_one_table_two(the_value text);

CREATE TABLE schema_two.table_two(a int);
CREATE TABLE schema_two.table_three(a int, b text);
CREATE TABLE audit_tbls.schema_two_table_three(the_value text);

CREATE OR REPLACE FUNCTION schema_two.add(int, int) RETURNS int LANGUAGE plpgsql
  CALLED ON NULL INPUT
  AS $$ BEGIN RETURN coalesce($1,0) + coalesce($2,0); END; $$;

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


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

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


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

INSERT INTO num_exp_div VALUES (0,6,'0');

Explanation: DML from PostgreSQL core regression test for Numeric.


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

select * from
(
  select unique1, q1, coalesce(unique1, -1) + q1 as fault
  from int8_tbl left join tenk1 on (q2 = unique2)
) ss
where fault = 122
order by fault;

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

SELECT count(*) FROM (select * from
(
  select unique1, q1, coalesce(unique1, -1) + q1 as fault
  from int8_tbl left join tenk1 on (q2 = unique2)
) ss
where fault = 122
order by fault) AS _sub;


Question: pgTAP test for Index (assertion 56).

SELECT * FROM check_test(
    index_is_unique( 'public', 'sometab', 'idx_baz' ),
    true,
    'index_is_unique() no desc',
    'Index idx_baz should be unique',
    ''
);

Explanation: SQL assertion from pgTAP test suite for Index.


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

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


Question: pgTAP test for Inheritance (assertion 123).

SELECT * FROM check_test(
    isnt_descendent_of( 'hide', 'h_child1', 'hide', 'nope', 1 ),
    true,
    'isnt_descendent_of(csch, ctab, psch, nope, 1)',
    'Table hide.h_child1 should not be descendent 1 from hide.nope',
    ''
);

Explanation: SQL assertion from pgTAP test suite for Inheritance.


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

INSERT INTO num_exp_mul VALUES (7,8,'-6217255985285');


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

INSERT INTO t1 VALUES (1, 'aaa'), (2, 'bbb'), (3, 'ccc');

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


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

SELECT rpad('hi'::citext, 5, 'xy'::text  ) = 'hixyx' AS t;

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


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

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

SELECT count(*) FROM (select f.last from fullname f) AS _sub;


Question: pgTAP test for Resultset (assertion 466).

PREPARE someset(boolean) AS SELECT * FROM names WHERE $1;

Explanation: SQL assertion from pgTAP test suite for Resultset.


Question: PL/pgSQL test: Plpgsql Control (example 35).

for r in select gs as aa, 'BB' as bb, 'CC' as cc from generate_series(1,4) gs loop
    raise notice '% % %', r.aa, r.bb, r.cc;

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


Question: Write the DML statement from PostgreSQL regression test 'subselect' (example 61).

Explanation: DML from PostgreSQL core regression test for Subselect.


Question: pgTAP test for Roletap (assertion 2).

Explanation: SQL assertion from pgTAP test suite for Roletap.


Question: Show a SQL definition from the pg_partman project (pg_partman--1.6.1--1.7.0, item 15).

/*
 * Function to create id partitions
 */
CREATE OR REPLACE FUNCTION create_id_partition (p_parent_table text, p_partition_ids bigint[]) RETURNS text
    LANGUAGE plpgsql SECURITY DEFINER
    AS $$
DECLARE

v_all               text[] := ARRAY['SELECT', 'INSERT', 'UPDATE', 'DELETE', 'TRUNCATE', 'REFERENCES', 'TRIGGER'];
v_analyze           boolean := FALSE;
v_control           text;
v_grantees          text[];
v_hasoids           boolean;
v_id                bigint;
v_job_id            bigint;
v_jobmon            boolean;
v_jobmon_schema     text;
v_old_search_path   text;
v_parent_grant      record;
v_parent_owner      text;
v_parent_schema     text;
v_parent_tablename  text;
v_parent_tablespace text;
v_part_interval     bigint;
v_partition_name    text;
v_revoke            text[];
v_sql               text;
v_step_id           bigint;
v_tablename         text;

BEGIN

SELECT control
    , part_interval
    , jobmon
INTO v_control
    , v_part_interval
    , v_jobmon
FROM @extschema@.part_config
WHERE parent_table = p_parent_table
AND (type = 'id-static' OR type = 'id-dynamic');

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

IF v_jobmon THEN
    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;
END IF;

SELECT tableowner, schemaname, tablename, tablespace INTO v_parent_owner, v_parent_schema, v_parent_tablename, v_parent_tablespace FROM pg_tables WHERE schemaname ||'.'|| tablename = p_parent_table;

FOREACH v_id IN ARRAY p_partition_ids LOOP
    v_partition_name := @extschema@.check_name_length(v_parent_tablename, v_parent_schema, v_id::text, TRUE);

    -- If child table already exists, skip creation
    SELECT 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;

    -- Ensure analyze is run if a new partition is created. Otherwise if one isn't, will be false and analyze will be skipped
    v_analyze := TRUE;

    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_id||' to '||(v_id + v_part_interval)-1);
    END IF;

    v_sql := 'CREATE TABLE '||v_partition_name||' (LIKE '||p_parent_table||' INCLUDING DEFAULTS INCLUDING CONSTRAINTS INCLUDING INDEXES INCLUDING STORAGE INCLUDING COMMENTS)';
    SELECT relhasoids INTO v_hasoids FROM pg_class WHERE oid::regclass = p_parent_table::regclass;
    IF v_hasoids IS TRUE THEN
        v_sql := v_sql || ' WITH (OIDS)';
    END IF;
    EXECUTE v_sql;
    SELECT tablename INTO v_tablename FROM pg_catalog.pg_tables WHERE schemaname ||'.'|| tablename = v_partition_name;
    IF v_parent_tablespace IS NOT NULL THEN
        EXECUTE 'ALTER TABLE '||v_partition_name||' SET TABLESPACE '||v_parent_tablespace;
    END IF;
    EXECUTE 'ALTER TABLE '||v_partition_name||' ADD CONSTRAINT '||v_tablename||'_partition_check
        CHECK ('||v_control||'>='||quote_literal(v_id)||' AND '||v_control||'<'||quote_literal(v_id + v_part_interval)||')';
    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_analyze THEN
    EXECUTE 'ANALYZE '||p_parent_table;
END IF;

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
            IF v_job_id IS NULL THEN
                EXECUTE 'SELECT '||v_jobmon_schema||'.add_job(''PARTMAN CREATE TABLE: '||p_parent_table||''')' INTO v_job_id;
                EXECUTE 'SELECT '||v_jobmon_schema||'.add_step('||v_job_id||', ''EXCEPTION before job logging started'')' INTO v_step_id;
            ELSIF v_step_id IS NULL THEN
                EXECUTE 'SELECT '||v_jobmon_schema||'.add_step('||v_job_id||', ''EXCEPTION before first step logged'')' INTO v_step_id;
            END IF;
            EXECUTE 'SELECT '||v_jobmon_schema||'.update_step('||v_step_id||', ''CRITICAL'', ''ERROR: '||coalesce(SQLERRM,'unknown')||''')';
            EXECUTE 'SELECT '||v_jobmon_schema||'.fail_job('||v_job_id||')';
        END IF;
        RAISE EXCEPTION '%', SQLERRM;
END
$$;

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


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

CREATE OR REPLACE FUNCTION _get_ac_privs(NAME, TEXT)
RETURNS TEXT[] AS $$
DECLARE
    privs  TEXT[] := ARRAY['INSERT', 'REFERENCES', 'SELECT', 'UPDATE'];
    grants TEXT[] := '{}';
BEGIN
    FOR i IN 1..array_upper(privs, 1) LOOP
        BEGIN
            IF pg_catalog.has_any_column_privilege($1, $2, privs[i]) THEN
                grants := grants || privs[i];
            END IF;
        EXCEPTION WHEN undefined_table THEN
            -- Not a valid table name.
            RETURN '{undefined_table}';
        WHEN undefined_object THEN
            -- Not a valid role.
            RETURN '{undefined_role}';
        WHEN invalid_parameter_value THEN
            -- Not a valid permission on this version of PostgreSQL; ignore;
        END;
    END LOOP;
    RETURN grants;
END;
$$ LANGUAGE plpgsql;

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


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

CREATE TABLE ruletest_tbl2 (a int, b int);

Explanation: DDL from PostgreSQL core regression test for Rules.


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


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

-- Create the operator class
CREATE OPERATOR CLASS gist_date_ops
DEFAULT FOR TYPE date USING gist
AS
	OPERATOR	1	<  ,
	OPERATOR	2	<= ,
	OPERATOR	3	=  ,
	OPERATOR	4	>= ,
	OPERATOR	5	>  ,
	OPERATOR	6	<> ,
	OPERATOR	15	<-> FOR ORDER BY pg_catalog.integer_ops ,
	FUNCTION	1	gbt_date_consistent (internal, date, int2, oid, internal),
	FUNCTION	2	gbt_date_union (internal, internal),
	FUNCTION	3	gbt_date_compress (internal),
	FUNCTION	4	gbt_decompress (internal),
	FUNCTION	5	gbt_date_penalty (internal, internal, internal),
	FUNCTION	6	gbt_date_picksplit (internal, internal),
	FUNCTION	7	gbt_date_same (gbtreekey8, gbtreekey8, internal),
	FUNCTION	8	gbt_date_distance (internal, date, int2, oid, internal),
	FUNCTION	9	gbt_date_fetch (internal),
	FUNCTION	11	gbt_date_sortsupport (internal),
	FUNCTION	12 ("any", "any") gist_translate_cmptype_btree (int),
	STORAGE		gbtreekey8;

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


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

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

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


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

CREATE TABLE t (c) AS VALUES ('bar'::text);

Explanation: DDL from PostgreSQL core regression test for Rowsecurity.


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

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

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

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


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

Explanation: DML from PostgreSQL core regression test for Select.


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

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

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

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


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

select * from hash_join_batches(
$$
  select count(*) from simple r join extremely_skewed s using (id);
$$);

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

SELECT count(*) FROM (select * from hash_join_batches(
$$
  select count(*) from simple r join extremely_skewed s using (id);
$$)) AS _sub;


Question: Show a SQL definition from the zombodb project (issue-290, item 1).

create table issue290 (
    id serial8 not null primary key,
    data text
);

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


Question: Write the DDL statement from PostgreSQL regression test 'select_into' (example 13).

CREATE TABLE selinto_schema.tbl_nodata1 (a) AS
  SELECT generate_series(1,3) WITH NO DATA;

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


Question: pgTAP test for Proctap (assertion 3).

CREATE FUNCTION procschema.afunc() RETURNS BOOL AS 'SELECT TRUE' LANGUAGE SQL;

Explanation: SQL assertion from pgTAP test suite for Proctap.


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

ALTER EXTENSION pgtap ADD FUNCTION _are ( text, name[], name[], TEXT );

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


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

SELECT count(*) FROM test_tsvector WHERE a @@ '!(pl <-> yh)';

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

SELECT count(*) FROM (SELECT count(*) FROM test_tsvector WHERE a @@ '!(pl <-> yh)') AS _sub;


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

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


Question: pgTAP test for Index (assertion 63).

SELECT * FROM check_test(
    index_is_unique( 'public', 'sometab', 'idx_bar', 'whatever' ),
    false,
    'index_is_unique() fail',
    'whatever',
    ''
);

Explanation: SQL assertion from pgTAP test suite for Index.


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

INSERT INTO TIMESTAMP_TBL VALUES ('1997.041 17:32:01 UTC');

Explanation: DML from PostgreSQL core regression test for Timestamp.


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

CREATE TABLE itest11 (a int generated always as identity, b text);

Explanation: DDL from PostgreSQL core regression test for Identity.


Question: Write the DML statement from PostgreSQL regression test 'transactions' (example 83).

Explanation: DML from PostgreSQL core regression test for Transactions.


Question: Show an example of PostgreSQL CREATE TRIGGER (example 2).

CREATE OR REPLACE TRIGGER check_update BEFORE UPDATE OF balance ON accounts FOR EACH ROW EXECUTE FUNCTION check_account_update();

Explanation: PostgreSQL CREATE TRIGGER command.


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

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