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

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

Explanation: DML from PostgreSQL core regression test for Timestamp.


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

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

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


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

SELECT dealloc FROM pg_stat_statements_info;

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


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

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

Explanation: DML from PostgreSQL core regression test for Rowtypes.


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

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

Explanation: DML from PostgreSQL core regression test for Rules.


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

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

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


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

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

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


Question: pgTAP test for Fktap (assertion 53).

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

Explanation: SQL assertion from pgTAP test suite for Fktap.


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

CREATE SEQUENCE sequence_test11 AS smallint;

Explanation: DDL from PostgreSQL core regression test for Sequence.


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

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

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


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

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


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

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


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

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


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

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

Explanation: DML from PostgreSQL core regression test for Timestamptz.


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

Explanation: DDL from PostgreSQL core regression test for Transactions.


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

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

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


Question: pgTAP test for Coltap (assertion 7).

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

Explanation: SQL assertion from pgTAP test suite for Coltap.


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

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

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


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

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

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


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

END
$$;

SELECT * FROM test2;

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

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


Question: pgTAP test for Coltap (assertion 37).

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


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

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

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

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


Question: PostgreSQL Typeconv: show example 22.

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

Explanation: Example from PostgreSQL documentation on Typeconv.


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

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

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


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

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

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

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


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

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


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

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

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


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

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

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


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

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

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

BEGIN

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

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

SELECT nspname INTO v_jobmon_schema FROM pg_catalog.pg_namespace n, pg_catalog.pg_extension e WHERE e.extname = 'pg_jobmon' AND e.extnamespace = n.oid;
IF v_jobmon_schema IS NOT NULL THEN
    SELECT current_setting('search_path') INTO v_old_search_path;
    EXECUTE 'SELECT set_config(''search_path'',''@extschema@,'||v_jobmon_schema||''',''false'')';
END IF;

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

FOREACH v_col IN ARRAY v_constraint_cols
LOOP

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

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

END LOOP;

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

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

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

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


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

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

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


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

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


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

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

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


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

CREATE UNIQUE INDEX ON regress_constr_partitioned (a);

Explanation: DDL from PostgreSQL core regression test for Constraints.


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

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

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

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


Question: pgTAP test for Resultset (assertion 319).

Explanation: SQL assertion from pgTAP test suite for Resultset.


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

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


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

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

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


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

Explanation: DDL from PostgreSQL core regression test for Update.


Question: pgTAP test for Functap (assertion 382).

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

Explanation: SQL assertion from pgTAP test suite for Functap.


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

create index test_range_elem_idx on test_range_elem (i);

Explanation: DDL from PostgreSQL core regression test for Rangetypes.


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

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


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

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

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

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


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

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


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

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

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

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


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

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

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


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

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

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


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

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

Explanation: DDL from PostgreSQL core regression test for Plpgsql.


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

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

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


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

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

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


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

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

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


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

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

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


Question: pgTAP test for Resultset (assertion 115).

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


Question: pgTAP test for Proctap (assertion 2).

Explanation: SQL assertion from pgTAP test suite for Proctap.


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

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

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


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

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


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

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

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


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

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

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


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

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


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

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

Explanation: DDL from PostgreSQL core regression test for Polymorphism.


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

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

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


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

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


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

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

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

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


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

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

Explanation: DDL from PostgreSQL core regression test for Aggregates.


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

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

Explanation: DDL from PostgreSQL core regression test for Expressions.


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

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

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


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

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

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

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


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

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

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


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

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


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

create operator family my_op_family using btree;

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


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

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

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

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


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

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

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


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

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

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


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

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

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

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


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

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

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


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

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

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

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


Question: pgTAP test for Resultset (assertion 203).

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

Explanation: SQL assertion from pgTAP test suite for Resultset.


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

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

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


Question: pgTAP test for Functap (assertion 144).

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

Explanation: SQL assertion from pgTAP test suite for Functap.


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

DROP TRIGGER show_trigger_data_trig_after ON trigger_test_generated;

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


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

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


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

Explanation: DML from PostgreSQL core regression test for Rangefuncs.


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

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

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


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

-- Check for index amhandler functions with the wrong signature

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

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


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

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

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


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

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

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


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

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

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


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

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

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

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


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

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


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

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

Explanation: DDL from PostgreSQL core regression test for Publication.


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

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


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

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

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


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

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

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


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

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

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


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

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


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

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

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


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

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

Explanation: DML from PostgreSQL core regression test for Rules.


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

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

Explanation: DDL from PostgreSQL core regression test for Polymorphism.


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

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

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


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

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


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

UPDATE unique_tbl SET i = 4 WHERE i = 2;

Explanation: DML from PostgreSQL core regression test for Constraints.


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

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

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


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

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

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


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

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

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

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


Question: pgTAP test for Resultset (assertion 158).

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

Explanation: SQL assertion from pgTAP test suite for Resultset.


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

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

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


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

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

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


Question: pgTAP test for Hastap (assertion 193).

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

Explanation: SQL assertion from pgTAP test suite for Hastap.


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

select * from iboolpart where a is not false;

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

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


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

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

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


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

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

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


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

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

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


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

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


Question: pgTAP test for Valueset (assertion 307).

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

Explanation: SQL assertion from pgTAP test suite for Valueset.


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

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


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

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

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

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


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

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

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


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

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

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

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


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

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

Explanation: DDL from PostgreSQL core regression test for Insert.


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

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

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


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

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


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

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

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

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

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


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

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


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

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


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

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


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

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

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

BEGIN

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

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

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

IF v_jobmon_schema IS NOT NULL THEN
    IF p_job_id IS NULL THEN
        v_job_id := add_job(format('PARTMAN CREATE FUNCTION: %s', p_parent_table));
    ELSE
        v_job_id = p_job_id;
    END IF;
    v_step_id := add_step(v_job_id, format('Creating partition function for table %s', p_parent_table));
END IF;

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

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

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

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

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

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

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

    END LOOP;

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

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

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

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

    EXECUTE v_trig_func;

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

ELSIF v_type = 'time-custom' THEN

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

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

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

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

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

    END IF;

    v_trig_func := v_trig_func || '

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

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

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

    EXECUTE v_trig_func;

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

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

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

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

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

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


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

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

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

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


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

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

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


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

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

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


Question: PostgreSQL Json: show example 16.

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

Explanation: Example from PostgreSQL documentation on Json.


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

Explanation: DDL from PostgreSQL core regression test for Indexing.


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

DELETE FROM transition_table_level2
  WHERE level2_no BETWEEN 301 AND 305;

Explanation: DML from PostgreSQL core regression test for Plpgsql.


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

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

Explanation: DDL from PostgreSQL core regression test for Rowsecurity.


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

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

Explanation: DDL from PostgreSQL core regression test for Join.


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

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

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


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

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

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

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


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

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

Explanation: DDL from PostgreSQL core regression test for Numeric.


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

CREATE FUNCTION inherit_template_properties (p_parent_table text, p_child_schema text, p_child_tablename text) RETURNS boolean
    LANGUAGE plpgsql SECURITY DEFINER
    AS $$
DECLARE

v_child_relkind         char;
v_child_schema          text;
v_child_tablename       text;
v_fk_list               record;
v_index_list            record;
v_parent_oid            oid;
v_parent_table          text;
v_sql                   text;
v_template_oid          oid;
v_template_table        text;

BEGIN
/*
 * Function to inherit the properties of the template table to newly created child tables.
 * Currently used for PostgreSQL 10 to inherit indexes and FKs since that is not natively available
 */

SELECT parent_table, template_table
INTO v_parent_table, v_template_table
FROM @extschema@.part_config
WHERE parent_table = p_parent_table;
IF v_parent_table IS NULL THEN
    RAISE EXCEPTION 'Given parent table has no configuration in pg_partman: %', p_parent_table;
ELSIF v_template_table IS NULL THEN
    RAISE EXCEPTION 'No template table set in configuration for given parent table: %', p_parent_table;
END IF;

SELECT c.oid INTO v_parent_oid
FROM pg_catalog.pg_class c
JOIN pg_catalog.pg_namespace n ON c.relnamespace = n.oid
WHERE n.nspname = split_part(p_parent_table, '.', 1)::name
AND c.relname = split_part(p_parent_table, '.', 2)::name;
    IF v_parent_oid IS NULL THEN
        RAISE EXCEPTION 'Unable to find given parent table in system catalogs: %', p_parent_table;
    END IF;

SELECT n.nspname, c.relname, c.relkind INTO v_child_schema, v_child_tablename, v_child_relkind
FROM pg_catalog.pg_class c
JOIN pg_catalog.pg_namespace n ON c.relnamespace = n.oid
WHERE n.nspname = p_child_schema::name
AND c.relname = p_child_tablename::name;
    IF v_child_tablename IS NULL THEN
        RAISE EXCEPTION 'Unable to find given child table in system catalogs: %.%', v_child_schema, v_child_tablename;
    END IF;

IF v_child_relkind = 'p' THEN
    -- Subpartitioned parent, do not apply properties
    RAISE DEBUG 'inherit_template_properties: found given child is subpartition parent, so properties not inherited';
    RETURN false;
END IF;

SELECT c.oid INTO v_template_oid
FROM pg_catalog.pg_class c
JOIN pg_catalog.pg_namespace n ON c.relnamespace = n.oid
WHERE n.nspname = split_part(v_template_table, '.', 1)::name
AND c.relname = split_part(v_template_table, '.', 2)::name;
    IF v_child_tablename IS NULL THEN
        RAISE EXCEPTION 'Unable to find configured template table in system catalogs: %', v_template_table;
    END IF;

-- Index creation
FOR v_index_list IN
    SELECT
    array_to_string(regexp_matches(pg_get_indexdef(indexrelid), ' USING .*'),',') AS statement
    , i.indisprimary
    , ( SELECT array_agg( a.attname ORDER by x.r )
        FROM pg_catalog.pg_attribute a
        JOIN ( SELECT k, row_number() over () as r
                FROM unnest(i.indkey) k ) as x
        ON a.attnum = x.k AND a.attrelid = i.indrelid
    ) AS indkey_names
    , c.relname AS index_name
    FROM pg_catalog.pg_index i
    JOIN pg_catalog.pg_class c ON i.indexrelid = c.oid
    WHERE i.indrelid = v_template_oid
    AND i.indisvalid
    ORDER BY 1
LOOP

    IF v_index_list.indisprimary THEN
        v_sql := format('ALTER TABLE %I.%I ADD PRIMARY KEY (%s)'
                        , v_child_schema
                        , v_child_tablename
                        , '"' || array_to_string(v_index_list.indkey_names, '","') || '"');
        RAISE DEBUG 'Create pk: %', v_sql;
        EXECUTE v_sql;
    ELSE
        -- statement column should be just the portion of the index definition that defines what it actually is
        v_sql := format('CREATE INDEX ON %I.%I %s', v_child_schema, v_child_tablename, v_index_list.statement);
        RAISE DEBUG 'Create index: %', v_sql;
        EXECUTE v_sql;

    END IF;

END LOOP;
-- End index creation

-- Foreign key creation
FOR v_fk_list IN
    SELECT pg_get_constraintdef(con.oid) AS constraint_def
    FROM pg_catalog.pg_constraint con
    JOIN pg_catalog.pg_class c ON con.conrelid = c.oid
    WHERE c.oid = v_template_oid
    AND contype = 'f'
LOOP
    v_sql := format('ALTER TABLE %I.%I ADD %s', v_child_schema, v_child_tablename, v_fk_list.constraint_def);
    RAISE DEBUG 'Create FK: %', v_sql;
    EXECUTE v_sql;
END LOOP;
-- End foreign key creation

RETURN true;

END
$$;


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

SELECT * FROM test_bool WHERE i=true ORDER BY i;

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


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

INSERT INTO num_variance SELECT 9e131071 + x FROM generate_series(1, 5) x;

Explanation: DML from PostgreSQL core regression test for Numeric.


Question: Show a SQL definition from the pg_partman project (pg_partman--4.3.1--4.4.0, item 6).

CREATE OR REPLACE VIEW @extschema@.table_privs AS
    SELECT u_grantor.rolname AS grantor,
           grantee.rolname AS grantee,
           nc.nspname AS table_schema,
           c.relname AS table_name,
           c.prtype AS privilege_type
    FROM (
            SELECT oid, relname, relnamespace, relkind, relowner, (aclexplode(coalesce(relacl, acldefault('r', relowner)))).* FROM pg_class
         ) AS c (oid, relname, relnamespace, relkind, relowner, grantor, grantee, prtype, grantable),
         pg_namespace nc,
         pg_roles u_grantor,
         (
           SELECT oid, rolname FROM pg_roles
           UNION ALL
           SELECT 0::oid, 'PUBLIC'
         ) AS grantee (oid, rolname)
    WHERE c.relnamespace = nc.oid
          AND c.relkind IN ('r', 'v', 'p')
          AND c.grantee = grantee.oid
          AND c.grantor = u_grantor.oid
          AND c.prtype IN ('INSERT', 'SELECT', 'UPDATE', 'DELETE', 'TRUNCATE', 'REFERENCES', 'TRIGGER')
          AND (pg_has_role(u_grantor.oid, 'USAGE')
               OR pg_has_role(grantee.oid, 'USAGE')
               OR grantee.rolname = 'PUBLIC' );


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

INSERT INTO test_having VALUES (8, 4, 'CCCC', 'I');

Explanation: DML from PostgreSQL core regression test for Select Having.


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

CREATE TABLE plt2_adv_p3 PARTITION OF plt2_adv FOR VALUES IN ('0003');

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


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

SELECT 'copy' FROM pg_copy_physical_replication_slot('orig_slot1', 'copied_slot1_no_change');

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


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

select avg((select avg(a1.col1 order by (select avg(a2.col2) from tenk1 a3))
            from tenk1 a1(col1)))
from tenk1 a2(col2);

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

SELECT count(*) FROM (select avg((select avg(a1.col1 order by (select avg(a2.col2) from tenk1 a3))
            from tenk1 a1(col1)))
from tenk1 a2(col2)) AS _sub;


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

SELECT * FROM test_like_id_3;  -- identity was copied and applied
DROP TABLE test_like_id_1, test_like_id_2, test_like_id_3;

Explanation: Regression test for Create Table Like in PostgreSQL core test suite.

SELECT count(*) FROM (SELECT * FROM test_like_id_3;  -- identity was copied and applied
DROP TABLE test_like_id_1, test_like_id_2, test_like_id_3) AS _sub;


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

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

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


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

select a.unique1, b.unique2
  from onek a full join onek b on a.unique1 = b.unique2
  where b.unique2 = 43;

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

SELECT count(*) FROM (select a.unique1, b.unique2
  from onek a full join onek b on a.unique1 = b.unique2
  where b.unique2 = 43) AS _sub;


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

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

SELECT count(*) FROM (select '  {}  '::textmultirange) AS _sub;


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

SELECT v as value, hashfloat8(v)::bit(32) as standard,
       hashfloat8extended(v, 0)::bit(32) as extended0,
       hashfloat8extended(v, 1)::bit(32) as extended1
FROM   (VALUES (0), (1), (17), (42), (550273), (207112489)) x(v)
WHERE  hashfloat8(v)::bit(32) != hashfloat8extended(v, 0)::bit(32)
       OR hashfloat8(v)::bit(32) = hashfloat8extended(v, 1)::bit(32);

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

SELECT count(*) FROM (SELECT v as value, hashfloat8(v)::bit(32) as standard,
       hashfloat8extended(v, 0)::bit(32) as extended0,
       hashfloat8extended(v, 1)::bit(32) as extended1
FROM   (VALUES (0), (1), (17), (42), (550273), (207112489)) x(v)
WHERE  hashfloat8(v)::bit(32) != hashfloat8extended(v, 0)::bit(32)
       OR hashfloat8(v)::bit(32) = hashfloat8extended(v, 1)::bit(32)) AS _sub;


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

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


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

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


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

insert into people values ('(Joe,Blow)', '1984-01-10');

Explanation: DML from PostgreSQL core regression test for Rowtypes.


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

CREATE PUBLICATION testpub_parsertst FOR TABLES IN SCHEMA foo, test.foo;

Explanation: DDL from PostgreSQL core regression test for Publication.


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

SELECT xpath('//b', 'one two three etc');

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

SELECT count(*) FROM (SELECT xpath('//b', 'one two three etc')) AS _sub;


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

select range_adjacent(numrange(2.0, 3.0), numrange(3.1, 4.0));

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

SELECT count(*) FROM (select range_adjacent(numrange(2.0, 3.0), numrange(3.1, 4.0))) AS _sub;


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

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

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


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

insert into arr_pk_tbl values (1, '{3,4,5}') on conflict (pk)
  do update set f1[1] = excluded.f1[1], f1[3] = excluded.f1[3]
  returning pk, f1;

Explanation: DML from PostgreSQL core regression test for Arrays.


Question: pgTAP test for Functap (assertion 266).

SELECT * FROM check_test(
    is_window( 'someschema', 'huh', '{}'::name[], 'whatever' ),
    false,
    'is_window(schema, func, noarg, desc)',
    'whatever',
    ''
);

Explanation: SQL assertion from pgTAP test suite for Functap.


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

SELECT count(*) FROM (select '{[a,d], [b,e]}'::textmultirange) AS _sub;


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

SELECT relreplident FROM pg_class WHERE oid = 'pg_class'::regclass;

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

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


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

CREATE COLLATION mycoll3 FROM "default";  -- intentionally unsupported

DROP COLLATION mycoll1;

Explanation: DDL from PostgreSQL core regression test for Collate.


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

SELECT '0/1'::pg_lsn - 2::numeric; -- out of range error
SELECT '0/0'::pg_lsn + ('FFFFFFFF/FFFFFFFF'::pg_lsn - '0/0'::pg_lsn);

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

SELECT count(*) FROM (SELECT '0/1'::pg_lsn - 2::numeric; -- out of range error
SELECT '0/0'::pg_lsn + ('FFFFFFFF/FFFFFFFF'::pg_lsn - '0/0'::pg_lsn)) AS _sub;


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

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

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


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

create table rp1 partition of rp for values from (1) to (2);

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


Question: PostgreSQL Textsearch: show example 62.

SELECT ts_lexize('public.simple_dict', 'YeS'); ts_lexize ----------- {yes} SELECT ts_lexize('public.simple_dict', 'The'); ts_lexize ----------- {};

Explanation: Example from PostgreSQL documentation on Textsearch.


Question: Show an example of PostgreSQL DROP ROLE (example 1).

Explanation: PostgreSQL DROP ROLE command.


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

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

SELECT count(*) FROM (SELECT lo_open(2121, x'40000'::int)) AS _sub;


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

CREATE TABLE part4 PARTITION OF range_parted2 FOR VALUES FROM (90) TO (100);

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


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

SELECT to_date('2011 12  18', 'YYYY MM  DD');

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

SELECT count(*) FROM (SELECT to_date('2011 12  18', 'YYYY MM  DD')) AS _sub;


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

INSERT INTO num_exp_add VALUES (7,7,'-166056970');

Explanation: DML from PostgreSQL core regression test for Numeric.


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

SELECT tableoid::regclass, a, b FROM part_7 order by a;

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

SELECT count(*) FROM (SELECT tableoid::regclass, a, b FROM part_7 order by a) AS _sub;


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

CREATE TABLE FKTABLE_FAIL1 (ftest1 int REFERENCES pktable(ptest1));

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


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

create table idxpart (a int4range, exclude USING GIST (a with -|- )) partition by range (a);

Explanation: DDL from PostgreSQL core regression test for Indexing.


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

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

SELECT count(*) FROM (SELECT jsonb_contains('{"a":"b", "b":1, "c":null}', '{"a":"c"}')) AS _sub;


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

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


Question: PostgreSQL Rowtypes: show example 18.

SELECT * FROM inventory_item c ORDER BY c; SELECT * FROM inventory_item c ORDER BY c.*; SELECT * FROM inventory_item c ORDER BY ROW(c.*);

Explanation: Example from PostgreSQL documentation on Rowtypes.


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

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

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


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

SELECT i, to_timestamp('2018-11-02 12:34:56.123456789', 'YYYY-MM-DD HH24:MI:SS.FF' || i) FROM generate_series(1, 6) i;

SELECT count(*) FROM (SELECT i, to_timestamp('2018-11-02 12:34:56.123456789', 'YYYY-MM-DD HH24:MI:SS.FF' || i) FROM generate_series(1, 6) i) AS _sub;


Question: pgTAP test for Resultset (assertion 73).

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

Explanation: SQL assertion from pgTAP test suite for Resultset.


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

CREATE TABLE pt2 PARTITION OF pt FOR VALUES IN (2);


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

--
-- Verify behavior of statement triggers on (non-partition)
-- inheritance hierarchy with transition tables; similar to the
-- partition case, except there is no rerouting on insertion and child
-- tables can have extra columns
--

-- set up inheritance hierarchy with different TupleDescriptors
create table parent (a text, b int);

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


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

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

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


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

SELECT * FROM ROWS FROM( getrngfunc7(1) AS (rngfuncid int, rngfuncsubid int, rngfuncname text) ) WITH ORDINALITY;

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

SELECT count(*) FROM (SELECT * FROM ROWS FROM( getrngfunc7(1) AS (rngfuncid int, rngfuncsubid int, rngfuncname text) ) WITH ORDINALITY) AS _sub;


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

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 DML statement from PostgreSQL regression test 'oid8' (example 5).

INSERT INTO OID8_TBL(f1) VALUES ('-1040');

Explanation: DML from PostgreSQL core regression test for Oid8.


Question: pgTAP test for Enumtap (assertion 25).

SELECT * FROM check_test(
    enum_has_labels( 'bug_status', ARRAY['new', 'open', 'closed'] ),
    true,
    'enum_has_labels(enum, labels)',
    'Enum bug_status should have labels (new, open, closed)',
    ''
);

Explanation: SQL assertion from pgTAP test suite for Enumtap.


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

SELECT 'empty'::numrange &> nummultirange(numrange(1,2));

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

SELECT count(*) FROM (SELECT 'empty'::numrange &> nummultirange(numrange(1,2))) AS _sub;


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

CREATE STATISTICS s11 (ndistinct) ON a, b, (a*5), (b+1) FROM ndistinct;

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


Question: pgTAP test for Trigger (assertion 30).

SELECT * FROM check_test(
    triggers_are( 'public', 'users', ARRAY['set_users_pass'] ),
    false,
    'triggers_are(schema, table, triggers) + extra',
    'Table public.users should have the correct triggers',
    '    Extra triggers:
        upd_users_pass'
);

Explanation: SQL assertion from pgTAP test suite for Trigger.


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

CREATE TABLE partitioned (
	a int,
	b int
) PARTITION BY RANGE (a, ('unknown'));

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


Question: pgTAP test for Resultset (assertion 331).


Question: Write the DDL statement from PostgreSQL regression test 'portals' (example 278).

CREATE TABLE current_check_2 () INHERITS (current_check);

Explanation: DDL from PostgreSQL core regression test for Portals.


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

select range_intersect_agg(nmr) from (values ('{[1,6]}'::nummultirange), ('{[3,12]}'::nummultirange)) t(nmr);

SELECT count(*) FROM (select range_intersect_agg(nmr) from (values ('{[1,6]}'::nummultirange), ('{[3,12]}'::nummultirange)) t(nmr)) AS _sub;


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

SELECT 'Infinity'::float8 / 'Infinity'::float8;

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

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


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

CREATE DOMAIN ordered_named_pair AS named_pair CHECK((VALUE).i <= (VALUE).j);

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


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

SELECT * FROM check_estimated_rows('SELECT * FROM functional_dependencies WHERE (a * 2) = ANY (ARRAY[2, 52, 102, 152]) AND upper(b) = ANY (ARRAY[''1'', ''26'']) AND (c + 1) = 2');

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

SELECT count(*) FROM (SELECT * FROM check_estimated_rows('SELECT * FROM functional_dependencies WHERE (a * 2) = ANY (ARRAY[2, 52, 102, 152]) AND upper(b) = ANY (ARRAY[''1'', ''26'']) AND (c + 1) = 2')) AS _sub;


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

CREATE TABLE stock (
    s_w_id int NOT NULL,
    s_i_id int NOT NULL,
    s_quantity decimal(4,0) NOT NULL,
    s_ytd decimal(8,2) NOT NULL,
    s_order_cnt int NOT NULL,
    s_remote_cnt int NOT NULL,
    s_data varchar(50) NOT NULL,
    s_dist_01 char(24) NOT NULL,
    s_dist_02 char(24) NOT NULL,
    s_dist_03 char(24) NOT NULL,
    s_dist_04 char(24) NOT NULL,
    s_dist_05 char(24) NOT NULL,
    s_dist_06 char(24) NOT NULL,
    s_dist_07 char(24) NOT NULL,
    s_dist_08 char(24) NOT NULL,
    s_dist_09 char(24) NOT NULL,
    s_dist_10 char(24) NOT NULL,
    PRIMARY KEY (s_w_id,s_i_id)
);

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


Question: pgTAP test for Resultset (assertion 272).

PREPARE expect_ord AS SELECT id, name FROM toexpect ORDER BY id;


Question: pgTAP test for Resultset (assertion 326).

SELECT * FROM check_test(
    set_has(
        'SELECT 44 AS a, ''Anna''::text UNION ALL SELECT 44, ''Anna''',
        'SELECT 44 AS a, ''Anna''::text'
    ),
    true,
    'set_has( dupes, values )',
    '',
    ''
);


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

SELECT jsonb '{"a":null, "b":"qq"}' ? 'b';

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

SELECT count(*) FROM (SELECT jsonb '{"a":null, "b":"qq"}' ? 'b') AS _sub;


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

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

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


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

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


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

SELECT * FROM test_timetz WHERE i='08:55:08 GMT+2'::timetz ORDER BY i;


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

Explanation: DML from PostgreSQL core regression test for Publication.


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

INSERT INTO c_star (class, c) VALUES ('c', 'hi paul'::name);

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


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

SELECT 'ABC'::name ILIKE '_b_' AS "true";

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

SELECT count(*) FROM (SELECT 'ABC'::name ILIKE '_b_' AS "true") AS _sub;


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

SELECT count(*) FROM enumtmp WHERE a  = 'g'::rainbow;

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


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

SELECT * FROM sj j1, sj j2 WHERE j1.b = j2.b AND j1.a = 2 AND j2.a = 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 = 2 AND j2.a = 3) AS _sub;


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

SELECT interval '1 2:03:04' hour to minute;

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

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


Question: pgTAP test for Functap (assertion 158).

SELECT * FROM check_test(
    is_normal_function( 'public', 'tap_accum', ARRAY[etype()] ),
    false,
    'is_normal_function(schema, agg, noargs)',
    'Function public.tap_accum(' || etype() || ') should be a normal function',
    ''
);

Explanation: SQL assertion from pgTAP test suite for Functap.


Question: PostgreSQL regression test 'create_index_spgist': Write the SELECT query (example 81).

SELECT count(*) FROM kd_point_tbl WHERE p >> '(5000, 4000)';

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

SELECT count(*) FROM (SELECT count(*) FROM kd_point_tbl WHERE p >> '(5000, 4000)') AS _sub;


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

ALTER EXTENSION pgtap ADD FUNCTION _col_is_null ( NAME, NAME, TEXT, bool );

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


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

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

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


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

UPDATE update_test SET (c,b) = ('car', a+b), a = a + 1 WHERE a = 10;

Explanation: DML from PostgreSQL core regression test for Update.


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

/* compression policy */
CREATE OR REPLACE FUNCTION @extschema@.add_compression_policy(
    hypertable REGCLASS,
    compress_after "any" = NULL,
    if_not_exists BOOL = false,
    schedule_interval INTERVAL = NULL,
    initial_start TIMESTAMPTZ = NULL,
    timezone TEXT = NULL,
    compress_created_before INTERVAL = NULL
)
RETURNS INTEGER
AS '@MODULE_PATHNAME@', 'ts_policy_compression_add'
LANGUAGE C VOLATILE; -- not strict because we need to set different default values for schedule_interval

CREATE OR REPLACE PROCEDURE @extschema@.add_columnstore_policy(
    hypertable REGCLASS,
    after "any" = NULL,
    if_not_exists BOOL = false,
    schedule_interval INTERVAL = NULL,
    initial_start TIMESTAMPTZ = NULL,
    timezone TEXT = NULL,
    created_before INTERVAL = NULL
) LANGUAGE C AS '@MODULE_PATHNAME@', 'ts_policy_compression_add';

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


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

CREATE FUNCTION texticregexne(citext, citext)
RETURNS bool AS 'texticregexne'
LANGUAGE internal IMMUTABLE STRICT PARALLEL SAFE;


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

SELECT COUNT(*) FROM array_gin_test WHERE a @> '{2}';

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

SELECT count(*) FROM (SELECT COUNT(*) FROM array_gin_test WHERE a @> '{2}') AS _sub;


Question: pgTAP test for Hastap (assertion 62).

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

Explanation: SQL assertion from pgTAP test suite for Hastap.


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

CREATE OPERATOR CLASS ismn13_ops DEFAULT
	FOR TYPE ismn13 USING hash FAMILY isn_ops AS
	OPERATOR 1  =,
	FUNCTION 1  hashismn13(ismn13);


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

-- Almost all of the core distribution's Btree opclasses can use one of the
-- two generic "equalimage" functions as their support function 4.  Look for
-- opclasses that don't allow deduplication unconditionally here.
--
-- Newly added Btree opclasses don't have to support deduplication.  It will
-- usually be trivial to add support, though.  Note that the expected output
-- of this part of the test will need to be updated when a new opclass cannot
-- support deduplication (by using btequalimage).
SELECT amp.amproc::regproc AS proc, opf.opfname AS opfamily_name,
       opc.opcname AS opclass_name, opc.opcintype::regtype AS opcintype
FROM pg_am AS am
JOIN pg_opclass AS opc ON opc.opcmethod = am.oid
JOIN pg_opfamily AS opf ON opc.opcfamily = opf.oid
LEFT JOIN pg_amproc AS amp ON amp.amprocfamily = opf.oid AND
    amp.amproclefttype = opc.opcintype AND amp.amprocnum = 4
WHERE am.amname = 'btree' AND
    amp.amproc IS DISTINCT FROM 'btequalimage'::regproc
ORDER BY 1, 2, 3;

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


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

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

SELECT count(*) FROM (select websearch_to_tsquery('simple', 'abc:def')) AS _sub;


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

CREATE OPERATOR <| (
        PROCEDURE = int8lt,
        LEFTARG = bigint,
        RIGHTARG = bigint
);

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


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

CREATE TABLE itest12 OF itest_type (f1 WITH OPTIONS GENERATED ALWAYS AS IDENTITY); -- error
DROP TYPE itest_type CASCADE;

Explanation: DDL from PostgreSQL core regression test for Identity.


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

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

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


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

SELECT c FROM jsonb_populate_record(NULL::jsbrec, '{"c": "aaa"}') q;

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

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


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

INSERT INTO num_exp_sub VALUES (3,3,'0');

Explanation: DML from PostgreSQL core regression test for Numeric.


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

INSERT INTO restaurants SELECT 'Szczecin' FROM generate_series(1, 10000);

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


Question: pgTAP test for Pktap (assertion 18).

SELECT * FROM check_test(
    hasnt_pk( 'sometab', 'sometab should not have a pk' ),
    false,
    'hasnt_pk( table, description )',
    'sometab should not have a pk',
    ''
);

Explanation: SQL assertion from pgTAP test suite for Pktap.


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

--
-- range_intersect_agg function
--
select range_intersect_agg(nmr) from nummultirange_test;

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


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

CREATE TEMP TABLE kd_point_tbl_ord_idx1 AS
SELECT row_number() OVER (ORDER BY p <-> '0,0') n, p <-> '0,0' dist, p
FROM kd_point_tbl;

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


Question: pgTAP test for Functap (assertion 99).

SELECT * FROM check_test(
    function_returns( 'yay', 'bool', 'whatever' ),
    true,
    'function_returns(func, bool, desc)',
    'whatever',
    ''
);

Explanation: SQL assertion from pgTAP test suite for Functap.


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

/* contrib/hstore/hstore--1.1--1.2.sql */

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

-- A version of 1.1 was shipped with these objects mistakenly in 9.3.0.
-- Therefore we only add them if we detect that they aren't already there and
-- dependent on the extension.

DO LANGUAGE plpgsql
$$
DECLARE
  my_schema pg_catalog.text := pg_catalog.quote_ident(pg_catalog.current_schema());
  old_path pg_catalog.text := pg_catalog.current_setting('search_path');
BEGIN
-- for safety, transiently set search_path to just pg_catalog+pg_temp
PERFORM pg_catalog.set_config('search_path', 'pg_catalog, pg_temp', true);

   PERFORM 1
   FROM pg_proc p
       JOIN  pg_depend d
          ON p.proname = 'hstore_to_json_loose'
            AND d.classid = 'pg_proc'::regclass
            AND d.objid = p.oid
            AND d.refclassid = 'pg_extension'::regclass
       JOIN pg_extension x
          ON d.refobjid = x.oid
            AND  x.extname = 'hstore';

   IF NOT FOUND
   THEN
        PERFORM pg_catalog.set_config('search_path', old_path, true);

        CREATE FUNCTION hstore_to_json(hstore)
        RETURNS json
        AS 'MODULE_PATHNAME', 'hstore_to_json'
        LANGUAGE C IMMUTABLE STRICT;

        CREATE CAST (hstore AS json)
          WITH FUNCTION hstore_to_json(hstore);

        CREATE FUNCTION hstore_to_json_loose(hstore)
        RETURNS json
        AS 'MODULE_PATHNAME', 'hstore_to_json_loose'
        LANGUAGE C IMMUTABLE STRICT;

   END IF;

PERFORM pg_catalog.set_config('search_path', old_path, true);
END;

$$;

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


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

CREATE SCHEMA pubme2 CREATE TABLE t0 (c int, d int);

Explanation: DDL from PostgreSQL core regression test for Publication.


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

SELECT citext_larger( 'ABC'::citext, 'bbbb'::citext ) = 'bbbb' AS t;

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


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

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

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


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

CREATE RULE rw_view16_del_rule AS ON DELETE TO rw_view16
  WHERE OLD.a > 0 DO INSTEAD DELETE FROM base_tbl WHERE a=OLD.a;

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


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

SELECT * FROM check_estimated_rows('SELECT a, b FROM stxdinh* GROUP BY 1, 2');

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

SELECT count(*) FROM (SELECT * FROM check_estimated_rows('SELECT a, b FROM stxdinh* GROUP BY 1, 2')) AS _sub;


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

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

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


Question: pgTAP test for Aretap (assertion 90).

SELECT * FROM check_test(
    indexes_are( 'fou', ARRAY['idx_fou_id', 'idx_fou_name', 'fou_pkey', 'howdy'] ),
    false,
    'indexes_are(table, indexes) + missing',
    'Table fou should have the correct indexes',
    '    Missing indexes:
        howdy'
);

Explanation: SQL assertion from pgTAP test suite for Aretap.


Question: pgTAP test for Functap (assertion 138).

SELECT * FROM check_test(
    isnt_definer( 'oww', ARRAY['int', 'text'] ),
    true,
    'isnt_definer(func, args)',
    'Function oww(int, text) should not be security definer',
    ''
);


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

-- isnt_window( schema, function )
CREATE OR REPLACE FUNCTION isnt_window( NAME, NAME )
RETURNS TEXT AS $$
    SELECT _func_compare(
        $1, $2, NOT _type_func('w', $1, $2),
        'Function ' || quote_ident($1) || '.' || quote_ident($2) || '() should not be a window function'
    );
$$ LANGUAGE sql;

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