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

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

SELECT count(*) FROM (SELECT b, c FROM forcetest WHERE a = 5) AS _sub;


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

CREATE FUNCTION functest_sri2() RETURNS SETOF int
LANGUAGE SQL
STABLE
BEGIN ATOMIC
    SELECT * FROM functest3;

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


Question: pgTAP test for Aretap (assertion 109).

SELECT * FROM check_test(
    languages_are( ___mylangs('plpgsql'), 'whatever' ),
    false,
    'languages_are(languages, desc) extras',
    'whatever',
    '    Extra languages:
        plpgsql'
);

Explanation: SQL assertion from pgTAP test suite for Aretap.


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

SELECT max(f1), min(f1), max(f2), min(f2), max(f3), min(f3) FROM arraggtest;

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

SELECT count(*) FROM (SELECT max(f1), min(f1), max(f2), min(f2), max(f3), min(f3) FROM arraggtest) AS _sub;


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

CREATE TABLE fail_part PARTITION OF range_parted2 FOR VALUES FROM (10) TO (50);

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


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

select explain_filter('explain (analyze,buffers off,costs off) select sum(n) over() from generate_series(1,2500) a(n)');

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

SELECT count(*) FROM (select explain_filter('explain (analyze,buffers off,costs off) select sum(n) over() from generate_series(1,2500) a(n)')) AS _sub;


Question: pgTAP test for Ownership (assertion 93).

SELECT * FROM check_test(
    function_owner_is('public', '__non__function', ARRAY['integer'], current_user, 'mumble'),
	false,
    'function_owner_is(sch, non-function, args[integer], user, desc)',
    'mumble',
    '    Function public.__non__function(integer) does not exist'
);

Explanation: SQL assertion from pgTAP test suite for Ownership.


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

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

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

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


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

SELECT date 'tomorrow' - date 'yesterday' AS "Two days";

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

SELECT count(*) FROM (SELECT date 'tomorrow' - date 'yesterday' AS "Two days") AS _sub;


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

-- same test with an after trigger
INSERT INTO trunc_trigger_test VALUES(1, 'foo', 'bar'), (2, 'baz', 'quux');

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


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

SELECT t2.y, sum(t1.y), count(*)
  FROM eager_agg_tab1 t1
  JOIN eager_agg_tab2 t2 ON t1.x = t2.y
GROUP BY t2.y ORDER BY t2.y;

Explanation: Regression test for Eager Aggregate in PostgreSQL core test suite.

SELECT count(*) FROM (SELECT t2.y, sum(t1.y), count(*)
  FROM eager_agg_tab1 t1
  JOIN eager_agg_tab2 t2 ON t1.x = t2.y
GROUP BY t2.y ORDER BY t2.y) AS _sub;


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

select count(*) from date_tbl
  where f1 not between symmetric '1997-01-01' and '1998-01-01';

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

SELECT count(*) FROM (select count(*) from date_tbl
  where f1 not between symmetric '1997-01-01' and '1998-01-01') AS _sub;


Question: PostgreSQL Plpgsql: show example 67.

<<block>> DECLARE foo int; BEGIN foo := ...; INSERT INTO dest (col) SELECT block.foo + bar FROM src;

Explanation: Example from PostgreSQL documentation on Plpgsql.


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

CREATE TRIGGER parted_mod_b before update on sub_part1
   for each row execute procedure func_parted_mod_b();

Explanation: DDL from PostgreSQL core regression test for Update.


Question: pgTAP test for Functap (assertion 280).

-- is_window ( NAME, NAME, TEXT )
-- isnt_window ( NAME, NAME, TEXT )
SELECT * FROM check_test(
    is_window( 'pg_catalog', 'ntile'::name, 'whatever' ),
    true,
    'is_window(schema, win, desc)',
    'whatever',
    ''
);

Explanation: SQL assertion from pgTAP test suite for Functap.


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

SELECT t1.c1, t2.c1 FROM ft1 t1 JOIN ft2 t2 ON (t1.c1 = t2.c1) ORDER BY t1.c3, t1.c1 OFFSET 100 LIMIT 10;

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


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

ALTER FUNCTION functest_B_3(int) COST 100;	-- unrelated change, no effect
SELECT proname, provolatile FROM pg_proc
       WHERE oid in ('functest_B_1'::regproc,
                     'functest_B_2'::regproc,
                     'functest_B_3'::regproc,
		     'functest_B_4'::regproc) ORDER BY proname;

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


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

INSERT INTO BIT_SHIFT_TABLE VALUES (B'1101100000000000');

Explanation: DML from PostgreSQL core regression test for Bit.


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

SELECT JSON_VALUE(jsonb '"2017-02-20"', '$' RETURNING date) + 9;

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

SELECT count(*) FROM (SELECT JSON_VALUE(jsonb '"2017-02-20"', '$' RETURNING date) + 9) AS _sub;


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

select format('%s, %s', variadic array[true, false]);

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

SELECT count(*) FROM (select format('%s, %s', variadic array[true, false])) AS _sub;


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

SELECT t1.c1, ss.a, ss.b FROM (SELECT c1 FROM ft4 WHERE c1 between 50 and 60) t1 FULL JOIN (SELECT t2.c1, t3.c1 FROM ft4 t2 LEFT JOIN ft5 t3 ON (t2.c1 = t3.c1) WHERE (t2.c1 between 50 and 60)) ss(a, b) ON (t1.c1 = ss.a) ORDER BY t1.c1, ss.a, ss.b;


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

SELECT count(*) FROM (SELECT to_timestamp('-44-02-01 11:12:13','YYYY-MM-DD HH24:MI:SS')) AS _sub;


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

ALTER EXTENSION pgtap ADD FUNCTION todo ( how_many int );

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


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

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

SELECT count(*) FROM (select '1_000.'::jsonpath) AS _sub;


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

CREATE TABLE sales_jan_feb2022 PARTITION OF sales_date FOR VALUES FROM (2022, 1, 1) TO (2022, 3, 1);

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


Question: PL/pgSQL test: Plperl Setup (example 5).

DO $$
begin
  execute format('grant create on database %I to regress_plperl_user1',
                 current_database());
end;
$$;

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


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

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


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

SELECT pg_replication_origin_progress('regress_test_decoding: regression_slot', true);

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


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

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


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

select * from numrange_test where nr < numrange(-1000.0, -1000.0,'[]');

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

SELECT count(*) FROM (select * from numrange_test where nr < numrange(-1000.0, -1000.0,'[]')) AS _sub;


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

SELECT c.*
   FROM CHAR_TBL c
   WHERE c.f1 > 'a';

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

SELECT count(*) FROM (SELECT c.*
   FROM CHAR_TBL c
   WHERE c.f1 > 'a') AS _sub;


Question: Write the DDL statement from PostgreSQL regression test 'xmlmap' (example 5).

CREATE TABLE testxmlschema.test2 (z int, y varchar(500), x char(6),
    w numeric(9,2), v smallint, u bigint, t real,
    s time, stz timetz, r timestamp, rtz timestamptz, q date,
    p xml, o testxmldomain, n bool, m bytea, aaa text);

Explanation: DDL from PostgreSQL core regression test for Xmlmap.


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

CREATE TABLE notnull_part1_2_upg (a int, CONSTRAINT nn2 NOT NULL a, b int);

Explanation: DDL from PostgreSQL core regression test for Constraints.


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

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

SELECT count(*) FROM (select jsonb_set('[]','{1}','"b"', false)) AS _sub;


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

SELECT numrange(6,7) &< nummultirange(numrange(3,4));

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

SELECT count(*) FROM (SELECT numrange(6,7) &< nummultirange(numrange(3,4))) AS _sub;


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

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

SELECT count(*) FROM (select '12:13:0'::txid_snapshot) AS _sub;


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

create table capitals (
	state		char(2)
) inherits (cities);

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


Question: pgTAP test for Resultset (assertion 52).

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

Explanation: SQL assertion from pgTAP test suite for Resultset.


Question: PL/pgSQL test: Plpgsql Copy (example 1).

\getenv abs_srcdir PG_ABS_SRCDIR
\getenv abs_builddir PG_ABS_BUILDDIR

-- set up file names to use
\set srcfilename :abs_srcdir '/data/copy1.data'
\set destfilename :abs_builddir '/results/copy1.data'

CREATE TABLE copy1 (a int, b float);

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


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

/*
 * Function to manage pre-creation of the next partitions in a time-based partition set.
 * Also manages dropping old partitions if the retention option is set.
 */
CREATE OR REPLACE FUNCTION run_maintenance(p_jobmon BOOLEAN DEFAULT true) RETURNS void
    LANGUAGE plpgsql SECURITY DEFINER
    AS $$
DECLARE

v_adv_lock                      boolean;
v_create_count                  int := 0;
v_current_partition             text;
v_current_partition_id          bigint;
v_current_partition_timestamp   timestamp;
v_datetime_string               text;
v_drop_count                    int := 0;
v_id_position                   int;
v_job_id                        bigint;
v_jobmon                        boolean;
v_jobmon_schema                 text;
v_last_partition                text;
v_last_partition_id             bigint;
v_last_partition_timestamp      timestamp;
v_next_partition_id             bigint;
v_next_partition_timestamp      timestamp;
v_old_search_path               text;
v_premade_count                 int;
v_quarter                       text;
v_step_id                       bigint;
v_step_overflow_id              bigint;
v_step_serial_id                bigint;
v_row                           record;
v_tablename                     text;
v_time_position                 int;
v_year                          text;

BEGIN

v_adv_lock := pg_try_advisory_xact_lock(hashtext('pg_partman run_maintenance'));
IF v_adv_lock = 'false' THEN
    RAISE NOTICE 'Partman maintenance already running.';
    RETURN;
END IF;

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

IF v_jobmon_schema IS NOT NULL THEN
    v_job_id := add_job('PARTMAN RUN MAINTENANCE');
    v_step_id := add_step(v_job_id, 'Running maintenance loop');
END IF;

FOR v_row IN
SELECT parent_table
    , type
    , part_interval
    , control
    , premake
    , datetime_string
    , last_partition
    , undo_in_progress
FROM @extschema@.part_config WHERE use_run_maintenance = true
LOOP

    CONTINUE WHEN v_row.undo_in_progress;

    -- Double check that last created partition exists
    IF v_row.last_partition IS NOT NULL THEN
        SELECT tablename INTO v_tablename FROM pg_tables WHERE schemaname || '.' || tablename = v_row.last_partition;
        IF v_tablename IS NULL THEN
            RAISE EXCEPTION 'Last known partition table missing for parent table %. Unable to determine next partition in sequence.', v_row.parent_table;
        END IF;
    ELSE
        RAISE EXCEPTION 'Last known partition missing from config table for parent table %.', p_parent_table;
    END IF;

    IF v_row.type = 'time-static' OR v_row.type = 'time-dynamic' OR v_row.type = 'time-custom' THEN
        IF v_row.type = 'time-static' OR v_row.type = 'time-dynamic' THEN
            CASE
                WHEN v_row.part_interval::interval = '15 mins' THEN
                    v_current_partition_timestamp := date_trunc('hour', CURRENT_TIMESTAMP) +
                        '15min'::interval * floor(date_part('minute', CURRENT_TIMESTAMP) / 15.0);
                WHEN v_row.part_interval::interval = '30 mins' THEN
                    v_current_partition_timestamp := date_trunc('hour', CURRENT_TIMESTAMP) +
                        '30min'::interval * floor(date_part('minute', CURRENT_TIMESTAMP) / 30.0);
                WHEN v_row.part_interval::interval = '1 hour' THEN
                    v_current_partition_timestamp := date_trunc('hour', CURRENT_TIMESTAMP);
                 WHEN v_row.part_interval::interval = '1 day' THEN
                    v_current_partition_timestamp := date_trunc('day', CURRENT_TIMESTAMP);
                WHEN v_row.part_interval::interval = '1 week' THEN
                    v_current_partition_timestamp := date_trunc('week', CURRENT_TIMESTAMP);
                WHEN v_row.part_interval::interval = '1 month' THEN
                    v_current_partition_timestamp := date_trunc('month', CURRENT_TIMESTAMP);
                WHEN v_row.part_interval::interval = '3 months' THEN
                    v_current_partition_timestamp := date_trunc('quarter', CURRENT_TIMESTAMP);
                WHEN v_row.part_interval::interval = '1 year' THEN
                    v_current_partition_timestamp := date_trunc('year', CURRENT_TIMESTAMP);
            END CASE;
        ELSIF v_row.type = 'time-custom' THEN
            SELECT child_table INTO v_current_partition FROM @extschema@.custom_time_partitions
                WHERE parent_table = v_row.parent_table AND partition_range @> CURRENT_TIMESTAMP;
            IF v_current_partition IS NULL THEN
                RAISE EXCEPTION 'Current time partition missing from custom_time_partitions config table for table % and timestamp %',
                     CURRENT_TIMESTAMP, v_row.parent_table;
            END IF;
            v_time_position := (length(v_current_partition) - position('p_' in reverse(v_current_partition))) + 2;
            v_current_partition_timestamp := to_timestamp(substring(v_current_partition from v_time_position), v_row.datetime_string);
        END IF;

        v_time_position := (length(v_row.last_partition) - position('p_' in reverse(v_row.last_partition))) + 2;
        IF v_row.part_interval::interval <> '3 months' OR (v_row.part_interval::interval = '3 months' AND v_row.type = 'time-custom') THEN
           v_last_partition_timestamp := to_timestamp(substring(v_row.last_partition from v_time_position), v_row.datetime_string);
        ELSE
            -- to_timestamp doesn't recognize 'Q' date string formater. Handle it
            v_year := split_part(substring(v_row.last_partition from v_time_position), 'q', 1);
            v_quarter := split_part(substring(v_row.last_partition from v_time_position), 'q', 2);
            CASE
                WHEN v_quarter = '1' THEN
                    v_last_partition_timestamp := to_timestamp(v_year || '-01-01', 'YYYY-MM-DD');
                WHEN v_quarter = '2' THEN
                    v_last_partition_timestamp := to_timestamp(v_year || '-04-01', 'YYYY-MM-DD');
                WHEN v_quarter = '3' THEN
                    v_last_partition_timestamp := to_timestamp(v_year || '-07-01', 'YYYY-MM-DD');
                WHEN v_quarter = '4' THEN
                    v_last_partition_timestamp := to_timestamp(v_year || '-10-01', 'YYYY-MM-DD');
            END CASE;
        END IF;

        -- Check and see how many premade partitions there are.
        v_premade_count = round(EXTRACT('epoch' FROM age(v_last_partition_timestamp, v_current_partition_timestamp)) / EXTRACT('epoch' FROM v_row.part_interval::interval));
        v_next_partition_timestamp := v_last_partition_timestamp;
        -- Loop premaking until config setting is met. Allows it to catch up if it fell behind or if premake changed.
        WHILE v_premade_count < v_row.premake LOOP
            BEGIN
                v_next_partition_timestamp := v_next_partition_timestamp + v_row.part_interval::interval;
            EXCEPTION WHEN datetime_field_overflow THEN
                v_premade_count := v_row.premake; -- do this so it can exit the premake check loop and continue in the outer for loop
                IF v_jobmon_schema IS NOT NULL THEN
                    v_step_overflow_id := add_step(v_job_id, 'Attempted partition time interval is outside PostgreSQL''s supported time range.');
                    PERFORM update_step(v_step_overflow_id, 'CRITICAL', 'Child partition creation skippd for parent table '||v_partition_time);
                END IF;
                RAISE WARNING 'Attempted partition time interval is outside PostgreSQL''s supported time range. Child partition creation skipped for parent table %', v_row.parent_table;
                CONTINUE;
            END;

            v_last_partition := @extschema@.create_time_partition(v_row.parent_table, ARRAY[v_next_partition_timestamp]);
            IF v_last_partition IS NOT NULL THEN
                UPDATE @extschema@.part_config SET last_partition = v_last_partition WHERE parent_table = v_row.parent_table;
            END IF;

            v_create_count := v_create_count + 1;
            IF v_row.type = 'time-static' THEN
                PERFORM @extschema@.create_time_function(v_row.parent_table);
            END IF;

            -- Manage additonal constraints if set
            PERFORM @extschema@.apply_constraints(v_row.parent_table);
            v_premade_count = round(EXTRACT('epoch' FROM age(v_next_partition_timestamp, v_current_partition_timestamp)) / EXTRACT('epoch' FROM v_row.part_interval::interval));
        END LOOP;
    ELSIF v_row.type = 'id-static' OR v_row.type ='id-dynamic' THEN
--        EXECUTE 'SELECT max('||v_row.control||') - ('||v_row.control||' % '||v_row.part_interval::int||') FROM '||v_row.parent_table INTO v_current_partition_id;
        EXECUTE 'SELECT '||v_row.control||' - ('||v_row.control||' % '||v_row.part_interval::int||') FROM '||v_row.parent_table||'
            WHERE '||v_row.control||' = (SELECT max('||v_row.control||') FROM '||v_row.parent_table||')'
            INTO v_current_partition_id;
        v_id_position := (length(v_row.last_partition) - position('p_' in reverse(v_row.last_partition))) + 2;
        v_last_partition_id = substring(v_row.last_partition from v_id_position)::bigint;
        -- This catches if there's invalid data in a parent table set that's outside all child table ranges.
        IF v_last_partition_id < v_current_partition_id THEN
            IF v_jobmon_schema IS NOT NULL THEN
                v_step_serial_id := add_step(v_job_id, 'Found inconsistent data in serial partition set.');
                PERFORM update_step(v_step_serial_id, 'CRITICAL', 'Child partition creation skipped for parent table '||v_row.parent_table||'. Current max serial id value ('||v_current_partition_id||') is greater than the id range covered by the last partition created ('||v_row.last_partition||'). Run check_parent() to find possible cause.');
            END IF;
            RAISE WARNING 'Child partition creation skipped for parent table %. Found inconsistent data in serial partition set. Current max serial id value (%) is greater than the id range covered by the last partition created (%). Run check_parent() to find possible cause.', v_row.parent_table, v_current_partition_id, v_row.last_partition;
            CONTINUE;
        END IF;
        v_next_partition_id := v_last_partition_id + v_row.part_interval::bigint;
        WHILE ((v_next_partition_id - v_current_partition_id) / v_row.part_interval::bigint) <= v_row.premake LOOP
            v_last_partition := @extschema@.create_id_partition(v_row.parent_table, ARRAY[v_next_partition_id]);
            IF v_last_partition IS NOT NULL THEN
                UPDATE @extschema@.part_config SET last_partition = v_last_partition WHERE parent_table = v_row.parent_table;
                PERFORM @extschema@.create_id_function(v_row.parent_table);
                PERFORM @extschema@.apply_constraints(v_row.parent_table);
            END IF;
            v_next_partition_id := v_next_partition_id + v_row.part_interval::bigint;
        END LOOP;

    END IF; -- end main IF check for time or id

END LOOP; -- end of creation loop

-- Manage dropping old partitions if retention option is set
FOR v_row IN
    SELECT parent_table FROM @extschema@.part_config WHERE retention IS NOT NULL AND undo_in_progress = false AND
        (type = 'time-static' OR type = 'time-dynamic' OR type = 'time-custom')
LOOP
    v_drop_count := v_drop_count + @extschema@.drop_partition_time(v_row.parent_table);
END LOOP;
FOR v_row IN
    SELECT parent_table FROM @extschema@.part_config WHERE retention IS NOT NULL AND undo_in_progress = false AND (type = 'id-static' OR type = 'id-dynamic')
LOOP
    v_drop_count := v_drop_count + @extschema@.drop_partition_id(v_row.parent_table);
END LOOP;

IF v_jobmon_schema IS NOT NULL THEN
    PERFORM update_step(v_step_id, 'OK', 'Partition maintenance finished. '||v_create_count||' partitions made. '||v_drop_count||' partitions dropped.');
    IF v_step_overflow_id IS NOT NULL OR v_step_serial_id IS NOT NULL THEN
        PERFORM fail_job(v_job_id);
    ELSE
        PERFORM close_job(v_job_id);
    END IF;
    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 RUN MAINTENANCE'')' INTO v_job_id;
                EXECUTE 'SELECT '||v_jobmon_schema||'.add_step('||v_job_id||', ''EXCEPTION before job logging started'')' INTO v_step_id;
            ELSIF v_step_id IS NULL THEN
                EXECUTE 'SELECT '||v_jobmon_schema||'.add_step('||v_job_id||', ''EXCEPTION before first step logged'')' INTO v_step_id;
            END IF;
            EXECUTE 'SELECT '||v_jobmon_schema||'.update_step('||v_step_id||', ''CRITICAL'', ''ERROR: '||coalesce(SQLERRM,'unknown')||''')';
            EXECUTE 'SELECT '||v_jobmon_schema||'.fail_job('||v_job_id||')';
        END IF;
        RAISE EXCEPTION '%', SQLERRM;
END
$$;

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


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

-- test returning a composite literal
CREATE OR REPLACE FUNCTION perl_row_lit() RETURNS testrowperl AS $$
    return '(1,hello,world,"({{1}})")';
$$ LANGUAGE plperl;

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


Question: pgTAP test for Resultset (assertion 285).

SELECT * FROM check_test(
    results_eq(
        'SELECT id, name FROM dupes ORDER BY pk',
        'SELECT id, name FROM dupes ORDER BY pk'
    ),
    true,
    'results_eq(values with null, values with null)',
    '',
    ''
);


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

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

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

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


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

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

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


Question: PostgreSQL Ddl: show example 36.

CREATE TABLE tree ( node_id integer PRIMARY KEY, parent_id integer REFERENCES tree, name text, ... );

Explanation: Example from PostgreSQL documentation on Ddl.


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

INSERT INTO OID8_TBL(f1) VALUES ('1234');

Explanation: DML from PostgreSQL core regression test for Oid8.


Question: PostgreSQL Plpgsql: show example 73.

CREATE OR REPLACE FUNCTION testfunc(integer) RETURNS integer AS $PROC$ .... $PROC$ LANGUAGE plpgsql;

Explanation: Example from PostgreSQL documentation on Plpgsql.


Question: pgTAP test for Check (assertion 22).

SELECT * FROM check_test(
    col_has_check( 'argh', ARRAY['id', 'name'], 'id + name should have a check' ),
    true,
    'col_has_check( tab, col[], desc )',
    'id + name should have a check',
    ''
);

Explanation: SQL assertion from pgTAP test suite for Check.


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

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

SELECT count(*) FROM (SELECT pg_stat_reset_single_table_counters('test_last_scan'::regclass)) AS _sub;


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

INSERT INTO joinme VALUES('zoo2', 54321);

Explanation: DML from PostgreSQL core regression test for Returning.


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

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

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

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


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

SELECT * FROM pg_input_error_info('9999999999', 'oid');

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

SELECT count(*) FROM (SELECT * FROM pg_input_error_info('9999999999', 'oid')) AS _sub;


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

create table parent_tab (id int) partition by range (id);

Explanation: DDL from PostgreSQL core regression test for Psql.


Question: Write the DDL statement from PostgreSQL regression test 'tablespace' (example 99).

CREATE TABLE testschema.dflt (a int PRIMARY KEY USING INDEX TABLESPACE regress_tblspace) PARTITION BY LIST (a);

Explanation: DDL from PostgreSQL core regression test for Tablespace.


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

create unique index fruit_index on insertconflicttest(fruit);

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


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

insert into outer_text values ('b', 'a');

Explanation: DML from PostgreSQL core regression test for Subselect.


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

Explanation: DML from PostgreSQL core regression test for Numeric.


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

CREATE TABLE fk1 PARTITION OF fk FOR VALUES FROM (1) TO (100) PARTITION BY RANGE (a);

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


Question: pgTAP test for Inheritance (assertion 135).

SELECT * FROM check_test(
    isnt_descendent_of( 'child2', 'parent', 2, 'Howdy' ),
    false,
    'isnt_descendent_of(ctab, ptab, 2, desc)',
    'Howdy',
    ''
);

Explanation: SQL assertion from pgTAP test suite for Inheritance.


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

SELECT xmlserialize(CONTENT  '' AS text INDENT);

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

SELECT count(*) FROM (SELECT xmlserialize(CONTENT  '' AS text INDENT)) AS _sub;


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

Explanation: DDL from PostgreSQL core regression test for Temp.


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

create function polyf(a anyelement, b anyarray,
                      c anycompatible, d anycompatible,
                      OUT x anyarray, OUT y anycompatiblearray)
as $$
  select a || b, array[c, d]
$$ language sql;

Explanation: DDL from PostgreSQL core regression test for Polymorphism.


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

INSERT INTO tr_sub_ddl VALUES ('blah-blah');

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


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

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

SELECT count(*) FROM (select interval 'PT-2562047789') AS _sub;


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

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

SELECT count(*) FROM (SELECT pg_input_is_valid('mauve', 'rainbow')) AS _sub;


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

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


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

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


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

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

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


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

INSERT INTO PG_LSN_TBL VALUES ('ABCD/');

Explanation: DML from PostgreSQL core regression test for Pg Lsn.


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

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

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

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


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

-- this revealed a bug in the original implementation
CREATE FUNCTION testRegexpResultToJsonb() RETURNS jsonb
LANGUAGE plperl
TRANSFORM FOR TYPE jsonb
AS $$
return ('1' =~ m(0\t2));
$$;

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


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

SELECT * FROM crosstab('SELECT rowid, attribute, val FROM ct where rowclass = ''group1'' ORDER BY 1,2;') AS c(rowid text, att1 text, att2 text, att3 text);

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


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

select * from
(select hundred, lag(hundred) over () as lhundred,
        thousand, lag(thousand) over () as lthousand,
        tenthous, lag(tenthous) over () as ltenthous from clstr_4) ss
where row(hundred, thousand, tenthous) <= row(lhundred, lthousand, ltenthous);

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

SELECT count(*) FROM (select * from
(select hundred, lag(hundred) over () as lhundred,
        thousand, lag(thousand) over () as lthousand,
        tenthous, lag(tenthous) over () as ltenthous from clstr_4) ss
where row(hundred, thousand, tenthous) <= row(lhundred, lthousand, ltenthous)) AS _sub;


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

insert into capitals values ('Madison', 1.913E+5, 845, 'WI');

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


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

create or replace view agg_view1 as
  select aggfns(distinct a,b,c)
    from (values (1,3,'foo'),(0,null,null),(2,2,'bar'),(3,1,'baz')) v(a,b,c),
         generate_series(1,3) i;

Explanation: DDL from PostgreSQL core regression test for Aggregates.


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

INSERT INTO orderstest VALUES (66, 1, false);

Explanation: DML from PostgreSQL core regression test for Subselect.


Question: PostgreSQL Xfunc: show example 42.

Explanation: Example from PostgreSQL documentation on Xfunc.


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

MERGE INTO wines w USING new_wine_list s ON s.winename = w.winename WHEN NOT MATCHED BY TARGET THEN INSERT VALUES(s.winename, s.stock) WHEN MATCHED AND w.stock != s.stock THEN UPDATE SET stock = s.stock WHEN NOT MATCHED BY SOURCE THEN DELETE;

Explanation: PostgreSQL MERGE command.


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

create function polyf(anymultirange) returns anyelement
as 'select lower($1);' language sql;


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

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

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


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

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

SELECT count(*) FROM (SELECT -0x8000000000000001) AS _sub;


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

$$;

CREATE TRIGGER gtest12_01 BEFORE INSERT OR UPDATE ON gtest26
  FOR EACH ROW
  EXECUTE PROCEDURE gtest_trigger_func();

CREATE TRIGGER gtest12_02 BEFORE INSERT OR UPDATE ON gtest26
  FOR EACH ROW
  EXECUTE PROCEDURE gtest_trigger_func4();

CREATE TRIGGER gtest12_03 BEFORE INSERT OR UPDATE ON gtest26
  FOR EACH ROW
  EXECUTE PROCEDURE gtest_trigger_func();

INSERT INTO gtest26 (a) VALUES (1);
SELECT * FROM gtest26 ORDER BY a;
UPDATE gtest26 SET a = 11 WHERE a = 10;
SELECT * FROM gtest26 ORDER BY a;

-- LIKE INCLUDING GENERATED and dropped column handling
CREATE TABLE gtest28a (
  a int,
  b int,
  c int,
  x int GENERATED ALWAYS AS (b * 2) STORED
);

ALTER TABLE gtest28a DROP COLUMN a;

CREATE TABLE gtest28b (LIKE gtest28a INCLUDING GENERATED);

\d gtest28*

-- sanity check of system catalog
SELECT attrelid, attname, attgenerated FROM pg_attribute WHERE attgenerated NOT IN ('', 's', 'v');

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


Question: Show a SQL definition from the pg_partman project (pg_partman--2.0.0--2.1.0, item 36).

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

v_datetime_string       text;
v_parent_schema         text;
v_parent_tablename      text;
v_partition_interval    text;
v_type                  text;

BEGIN

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

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

SELECT schemaname, tablename INTO v_parent_schema, v_parent_tablename FROM pg_catalog.pg_tables WHERE schemaname||'.'||tablename = p_parent_table;

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

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

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

END IF;

END
$$;

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


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

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


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

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


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

CREATE UNIQUE INDEX num_exp_sqrt_idx ON num_exp_sqrt (id);

Explanation: DDL from PostgreSQL core regression test for Numeric.


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

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

SELECT count(*) FROM (SELECT date 'J2451187') AS _sub;


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

select t1.f1 from t1 left join t2 using (f1) group by f1;

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

SELECT count(*) FROM (select t1.f1 from t1 left join t2 using (f1) group by f1) AS _sub;


Question: pgTAP test for Enumtap (assertion 19).

SELECT * FROM check_test(
    hasnt_enum( 'bug_status', 'mydesc' ),
    false,
    'hasnt_enum(enum, desc)',
    'mydesc',
    ''
);

Explanation: SQL assertion from pgTAP test suite for Enumtap.


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

select count(*) from
  (select 1 from tenk1 a
   where unique1 IN (select distinct hundred from tenk1 b)) ss;

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

SELECT count(*) FROM (select count(*) from
  (select 1 from tenk1 a
   where unique1 IN (select distinct hundred from tenk1 b)) ss) AS _sub;


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

SELECT a, a <-> '-1890.0' FROM float8tmp ORDER BY a <-> '-1890.0' LIMIT 3;

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


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

SELECT f1
   FROM BOOLTBL1
   WHERE f1 IS FALSE;

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

SELECT count(*) FROM (SELECT f1
   FROM BOOLTBL1
   WHERE f1 IS FALSE) AS _sub;


Question: Show a SQL definition from the timescaledb project (test_utils, item 4).

CREATE OR REPLACE FUNCTION test.double_eq() RETURNS VOID
    AS :MODULE_PATHNAME, 'ts_test_utils_double_eq' LANGUAGE C IMMUTABLE STRICT PARALLEL SAFE;

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


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

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


Question: PostgreSQL Rules: show example 27.

Explanation: Example from PostgreSQL documentation on Rules.


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

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

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

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


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

ALTER TABLESPACE index_space RENAME TO fast_raid;

Explanation: PostgreSQL ALTER TABLESPACE command.


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

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

SELECT count(*) FROM (SELECT log('-inf'::numeric, '10')) AS _sub;


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

select polyf(stavalues1) from pg_statistic;  -- fail, can't infer element type

drop function polyf(x anyarray);

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

SELECT count(*) FROM (select polyf(stavalues1) from pg_statistic;  -- fail, can't infer element type

drop function polyf(x anyarray)) AS _sub;


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

select (select (a.*)::text) from view_a a;

SELECT count(*) FROM (select (select (a.*)::text) from view_a a) AS _sub;


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

create table issue618 (id bigint not null primary key);

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


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

CREATE TEMP TABLE temptest(col) ON COMMIT DELETE ROWS AS SELECT 1;

Explanation: DDL from PostgreSQL core regression test for Temp.


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


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

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


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

SELECT nummultirange(numrange(1,2)) -|- nummultirange(numrange(3,4));

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

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


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

CREATE FUNCTION citext_pattern_ge( citext, citext )
RETURNS bool
AS 'MODULE_PATHNAME'
LANGUAGE C IMMUTABLE STRICT PARALLEL SAFE;

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


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

select x, y,
       first_value(y) over w,
       last_value(y) over w
from
  (select x, x as y from generate_series(1,5) as x
   union all select null, 42
   union all select null, 43) ss
window w as
  (order by x asc nulls last range between 2 preceding and 2 following);

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

SELECT count(*) FROM (select x, y,
       first_value(y) over w,
       last_value(y) over w
from
  (select x, x as y from generate_series(1,5) as x
   union all select null, 42
   union all select null, 43) ss
window w as
  (order by x asc nulls last range between 2 preceding and 2 following)) AS _sub;


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

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


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

SELECT * FROM test_float4 WHERE i < 1e-300::float8 ORDER BY i;

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


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

SELECT phraseto_tsquery('english', 'PostgreSQL can be extended by the user in many ways');

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

SELECT count(*) FROM (SELECT phraseto_tsquery('english', 'PostgreSQL can be extended by the user in many ways')) AS _sub;


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

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

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


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

Explanation: DDL from PostgreSQL core regression test for Object Address.


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

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

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


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

SELECT to_char(val, '999999SG9999999999')			FROM num_data;

SELECT count(*) FROM (SELECT to_char(val, '999999SG9999999999')			FROM num_data) AS _sub;


Question: Show a SQL definition from the pglogical project (node_origin_cascade, item 6).

DO $$
BEGIN
        IF version() ~ 'Postgres-XL' THEN
                CREATE EXTENSION IF NOT EXISTS pglogical;
        ELSE
                CREATE EXTENSION IF NOT EXISTS pglogical VERSION '1.0.0';
        END IF;
END;
$$;

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


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

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


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

select jsonb_path_query('[]', 'strict $["a"]', silent => true);

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

SELECT count(*) FROM (select jsonb_path_query('[]', 'strict $["a"]', silent => true)) AS _sub;


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

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

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


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

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


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

end
$$ language plpgsql;

select namedparmcursor_test1(20000, 20000) as "Should be false",
       namedparmcursor_test1(20, 20) as "Should be true";

-- mixing named and positional argument notations
create function namedparmcursor_test2(int, int) returns boolean as $$
declare
    c1 cursor (param1 int, param2 int) for select * from rc_test where a > param1 and b > param2;

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


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

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

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


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

CREATE TRIGGER show_trigger_data_trig_before
BEFORE INSERT OR UPDATE OR DELETE ON trigger_test_generated
FOR EACH ROW EXECUTE PROCEDURE trigger_data();

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


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

SELECT explain_mask_costs($$
SELECT * FROM generate_series(25.0, 2.0, 0.0) g(s);$$,
false, true, false, true);

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

SELECT count(*) FROM (SELECT explain_mask_costs($$
SELECT * FROM generate_series(25.0, 2.0, 0.0) g(s);$$,
false, true, false, true)) AS _sub;


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

select * from phrase_index_test where fts @@ phraseto_tsquery('english', 'fat cat');

SELECT count(*) FROM (select * from phrase_index_test where fts @@ phraseto_tsquery('english', 'fat cat')) AS _sub;


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

create index HSlot_hubname on HSlot using btree (hubname bpchar_ops);

Explanation: DDL from PostgreSQL core regression test for Plpgsql.


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

CREATE FUNCTION ltree_same(ltree_gist, ltree_gist, internal)
RETURNS internal as 'MODULE_PATHNAME' LANGUAGE C IMMUTABLE STRICT PARALLEL SAFE;


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

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


Question: pgTAP test for Check (assertion 11).

SELECT * FROM check_test(
    col_has_check( 'public', 'sometab', ARRAY['numb', 'myint'], 'public.sometab.numb+myint should have a check' ),
    true,
    'col_has_check( sch, tab, cols, desc )',
    'public.sometab.numb+myint should have a check',
    ''
);

Explanation: SQL assertion from pgTAP test suite for Check.


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

SELECT * FROM nummultirange_test WHERE nmr @> numrange(4.0, 4.2);

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

SELECT count(*) FROM (SELECT * FROM nummultirange_test WHERE nmr @> numrange(4.0, 4.2)) AS _sub;


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

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

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

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


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

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

SELECT count(*) FROM (SELECT bool 'off' AS false) AS _sub;


Question: pgTAP test for Ownership (assertion 82).

SELECT * FROM check_test(
    composite_owner_is('someview', current_user, 'mumble'),
	false,
    'composite_owner_is(view, user, desc)',
    'mumble',
    '    Composite type someview does not exist'
);

Explanation: SQL assertion from pgTAP test suite for Ownership.


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

create index minmaxtesti on minmaxtest(f1);

Explanation: DDL from PostgreSQL core regression test for Aggregates.


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

SELECT generate_series(1, generate_series(1, 3)), generate_series(2, 4);

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

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


Question: PostgreSQL Queries: show example 36.

WITH RECURSIVE included_parts(sub_part, part, quantity) AS ( SELECT sub_part, part, quantity FROM parts WHERE part = 'our_product' UNION ALL SELECT p.sub_part, p.part, p.quantity * pr.quantity FROM included_parts pr, parts p WHERE p.part = pr.sub_part ) SELECT sub_part, SUM(quantity) AS total_quantity FROM included_parts GROUP BY sub_part;

Explanation: Example from PostgreSQL documentation on Queries.


Question: pgTAP test for Hastap (assertion 51).

SELECT * FROM check_test(
    has_view( 'information_schema', 'tables', 'desc' ),
    true,
    'has_view(sch, view, desc)',
    'desc',
    ''
);

Explanation: SQL assertion from pgTAP test suite for Hastap.


Question: PostgreSQL Xfunc: show example 22.

CREATE FUNCTION anyleast (VARIADIC anyarray) RETURNS anyelement AS $$ SELECT min($1[i] COLLATE "en_US") FROM generate_subscripts($1, 1) g(i); $$ LANGUAGE SQL;

Explanation: Example from PostgreSQL documentation on Xfunc.


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

INSERT INTO TIMETZ_TBL VALUES ('23:59 PDT');

Explanation: DML from PostgreSQL core regression test for Timetz.


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

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


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

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

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


Question: pgTAP test for Hastap (assertion 287).

-- It should not ignore views and types.
SELECT * FROM check_test(
    has_relation( 'pg_catalog', 'pg_type', 'desc' ),
    true,
    'has_relation(sch, view, desc)',
    'desc',
    ''
);


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

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

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


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

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

SELECT count(*) FROM (SELECT U&' \' UESCAPE '!' AS "tricky") AS _sub;


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

/* contrib/btree_gist/btree_gist--1.9.sql */

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

CREATE FUNCTION gbtreekey2_in(cstring)
RETURNS gbtreekey2
AS 'MODULE_PATHNAME', 'gbtreekey_in'
LANGUAGE C IMMUTABLE STRICT PARALLEL SAFE;

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


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

select interval '-2147483648 months -0.1 yrs';

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

SELECT count(*) FROM (select interval '-2147483648 months -0.1 yrs') AS _sub;


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

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

SELECT count(*) FROM (SELECT xmlpi(name xmlstuff, null)) AS _sub;


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

select interval '-0.1 yrs -2147483648 months';

SELECT count(*) FROM (select interval '-0.1 yrs -2147483648 months') AS _sub;


Question: pgTAP test for Fktap (assertion 21).

SELECT * FROM check_test(
    has_fk( 'pg_class', 'pg_class should have an fk' ),
    false,
    'has_fk( table, description ) fail',
    'pg_class should have an fk'
);

Explanation: SQL assertion from pgTAP test suite for Fktap.


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

SELECT f1 AS "None" FROM TIMETZ_TBL WHERE f1 < '00:00-07';

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

SELECT count(*) FROM (SELECT f1 AS "None" FROM TIMETZ_TBL WHERE f1 < '00:00-07') AS _sub;


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

Explanation: DML from PostgreSQL core regression test for Numeric.


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

select explain_filter('explain (memory) execute int8_query');

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

SELECT count(*) FROM (select explain_filter('explain (memory) execute int8_query')) AS _sub;


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

SELECT 'Türkiye' COLLATE "tr_TR" ~* 'KI' AS "false";

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

SELECT count(*) FROM (SELECT 'Türkiye' COLLATE "tr_TR" ~* 'KI' AS "false") AS _sub;


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

SELECT 'a'::citext <> 'ab'::citext AS t;

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


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

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

SELECT count(*) FROM (select ''::nonempty) AS _sub;


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

INSERT INTO test_text VALUES ('a'),('ab'),('abc'),('abb'),('axy'),('xyz');

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


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

select count(*) from
  onek o cross join lateral (
    select * from onek i1 where i1.unique1 = o.unique1
    except
    select * from onek i2 where i2.unique1 = o.unique2
  ) ss
where o.ten = 1;

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

SELECT count(*) FROM (select count(*) from
  onek o cross join lateral (
    select * from onek i1 where i1.unique1 = o.unique1
    except
    select * from onek i2 where i2.unique1 = o.unique2
  ) ss
where o.ten = 1) AS _sub;


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

select count(*) from tenk1 a,
  tenk1 b join lateral (values(a.unique1),(-1)) ss(x) on b.unique2 = ss.x;

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

SELECT count(*) FROM (select count(*) from tenk1 a,
  tenk1 b join lateral (values(a.unique1),(-1)) ss(x) on b.unique2 = ss.x) AS _sub;


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

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


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

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


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

SELECT DISTINCT p1.proargtypes[6]::regtype, p2.proargtypes[6]::regtype
FROM pg_proc AS p1, pg_proc AS p2
WHERE p1.oid != p2.oid AND
    p1.prosrc = p2.prosrc AND
    p1.prolang = 12 AND p2.prolang = 12 AND
    p1.prokind != 'a' AND p2.prokind != 'a' AND
    (p1.proargtypes[6] < p2.proargtypes[6])
ORDER BY 1, 2;

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

SELECT count(*) FROM (SELECT DISTINCT p1.proargtypes[6]::regtype, p2.proargtypes[6]::regtype
FROM pg_proc AS p1, pg_proc AS p2
WHERE p1.oid != p2.oid AND
    p1.prosrc = p2.prosrc AND
    p1.prolang = 12 AND p2.prolang = 12 AND
    p1.prokind != 'a' AND p2.prokind != 'a' AND
    (p1.proargtypes[6] < p2.proargtypes[6])
ORDER BY 1, 2) AS _sub;


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

CREATE OR REPLACE FUNCTION _opc_exists( NAME )
RETURNS BOOLEAN AS $$
    SELECT EXISTS (
        SELECT TRUE
          FROM pg_catalog.pg_opclass oc
         WHERE oc.opcname = $1
           AND pg_opclass_is_visible(oid)
    );
$$ LANGUAGE SQL;

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


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

CREATE TABLE history_p2 PARTITION OF history FOR VALUES FROM ('2020-01-01') TO ('2021-01-01');

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


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

ALTER EXTENSION pgtap ADD FUNCTION _lang ( NAME );

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


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

/* contrib/dict_int/dict_int--1.0.sql */

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

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

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


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

INSERT INTO test_having VALUES (4, 3, 'BBBB', 'e');

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


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

CREATE OR REPLACE FUNCTION _timescaledb_functions.relation_size(relation REGCLASS)
RETURNS TABLE (total_size BIGINT, heap_size BIGINT, index_size BIGINT, toast_size BIGINT)
AS '@MODULE_PATHNAME@', 'ts_relation_size' LANGUAGE C VOLATILE;

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


Question: PostgreSQL Queries: show example 9.

SELECT a.* FROM my_table AS a JOIN your_table AS b ON ...;

Explanation: Example from PostgreSQL documentation on Queries.


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

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

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


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

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

SELECT count(*) FROM (select 'b' ~ '^([bc])\1*$' as t) AS _sub;


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

CREATE FUNCTION zdb.schema_version() RETURNS text LANGUAGE sql AS $$
SELECT '3000.1.17 (3a00af1aa6597c6306ab323bb279962dfdc99f2e)'
$$;

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


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

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


Question: Show a SQL definition from the zombodb project (_cat-api, item 13).

CREATE OR REPLACE VIEW zdb.cat_plugins AS
SELECT
    url,
    (response->>'name') AS "name",
    (response->>'component') AS "component",
    (response->>'version') AS "version",
    (response->>'description') AS "description"
FROM zdb._all_indices_cat_request('plugins');


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

ALTER EXTENSION pgtap ADD FUNCTION _expand_vol( char );


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

Explanation: DML from PostgreSQL core regression test for Timestamp.


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

CREATE OR REPLACE FUNCTION _constraint ( NAME, NAME, CHAR, NAME[], TEXT, TEXT )
RETURNS TEXT AS $$
DECLARE
    akey NAME[];
    keys TEXT[] := '{}';
    have TEXT;
BEGIN
    FOR akey IN SELECT * FROM _keys($1, $2, $3) LOOP
        IF akey = $4 THEN RETURN pass($5); END IF;
        keys = keys || akey::text;
    END LOOP;
    IF array_upper(keys, 0) = 1 THEN
        have := 'No ' || $6 || ' constraints';
    ELSE
        have := array_to_string(keys, E'\n              ');
    END IF;

    RETURN fail($5) || E'\n' || diag(
             '        have: ' || have
       || E'\n        want: ' || CASE WHEN $4 IS NULL THEN 'NULL' ELSE $4::text END
    );
END;
$$ LANGUAGE plpgsql;


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

CREATE TABLE sales_external (LIKE sales_list);

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


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

--
--
--
-- text/bpchar ops
--
--
--
-- define the GiST support methods
CREATE FUNCTION gbt_text_consistent(internal,text,int2,oid,internal)
RETURNS bool
AS 'MODULE_PATHNAME'
LANGUAGE C IMMUTABLE STRICT PARALLEL SAFE;


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

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

SELECT count(*) FROM (select jsonb '{"a": {"b": 1}}' @? '$.**{0 to last}.b ? ( @ > 0)') AS _sub;


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

-- 2 triggers should fire here (row + statement):
INSERT INTO salespeople VALUES (20, 'Smirnoff');

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


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

insert into mic_inputs  values
  ('\x666f6f',		'valid, pure ASCII'),
  ('\x8bc68bcf8bcf',	'valid (in KOI8R)'),
  ('\x8bc68bcf8b',	'invalid,incomplete char'),
  ('\x92bedd',		'valid (in SHIFT_JIS)'),
  ('\x92be',		'invalid, incomplete char)'),
  ('\x666f6f95a3c1',	'valid (in Big5)'),
  ('\x666f6f95a3',	'invalid, incomplete char'),
  ('\x9200bedd',	'invalid, NUL byte'),
  ('\x92bedd00',	'invalid, NUL byte'),
  ('\x8b00c68bcf8bcf',	'invalid, NUL byte');

Explanation: DML from PostgreSQL core regression test for Conversion.


Question: pgTAP test for Ownership (assertion 48).

SELECT * FROM check_test(
    table_owner_is('public', '__not__sometab', current_user, 'mumble'),
	false,
    'table_owner_is(sch, non-tab, user)',
    'mumble',
    '    Table public.__not__sometab does not exist'
);

Explanation: SQL assertion from pgTAP test suite for Ownership.


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

$$ LANGUAGE plpgsql;

CREATE FUNCTION leaker_2(fail BOOL, OUT error_code INTEGER, OUT new_id INTEGER)
  RETURNS RECORD AS $$
BEGIN
  IF fail THEN
    RAISE EXCEPTION 'fail ...';

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


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

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


Question: pgTAP test for Functap (assertion 282).

SELECT * FROM check_test(
    is_window( 'someschema', 'bah'::name, 'whatever' ),
    false,
    'is_window(schema, func, desc)',
    'whatever',
    ''
);

Explanation: SQL assertion from pgTAP test suite for Functap.


Question: pgTAP test for Aretap (assertion 117).

SELECT * FROM check_test(
    opclasses_are( ___myopc('') ),
    true,
    'opclasses_are(opclasses)',
    'Search path ' || pg_catalog.current_setting('search_path') || ' should have the correct operator classes',
    ''
);

Explanation: SQL assertion from pgTAP test suite for Aretap.


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

Explanation: DML from PostgreSQL core regression test for Triggers.


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

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


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

-- Test tuple returning functions
SELECT * FROM test_table_record_as('dict', null, null, false);

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


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

INSERT INTO itest5 OVERRIDING SYSTEM VALUE VALUES (-5, 'ff'), (DEFAULT, 'gg');

Explanation: DML from PostgreSQL core regression test for Identity.


Question: pgTAP test for Valueset (assertion 293).

SELECT * FROM check_test(
    bag_hasnt( 'anames', 'VALUES (44, ''Anna''), (86, ''Angelina'')' ),
    false,
    'bag_hasnt( prepared, values )',
    '',
    E'    Extra records:
        [(](44,Anna|86,Angelina)[)]
        [(](44,Anna|86,Angelina)[)]',
    true
);

Explanation: SQL assertion from pgTAP test suite for Valueset.


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

CREATE TABLE subtransaction_tbl (
    i integer
);

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


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

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

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


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

select foo.*, unnamed_join.* from
  t1 join t2 using (a) as foo, t3 as unnamed_join
  for update of foo;

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

SELECT count(*) FROM (select foo.*, unnamed_join.* from
  t1 join t2 using (a) as foo, t3 as unnamed_join
  for update of foo) AS _sub;


Question: PL/pgSQL test: Plperl Elog (example 19).

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


Question: Write the DML statement from PostgreSQL regression test 'truncate' (example 168).

Explanation: DML from PostgreSQL core regression test for Truncate.


Question: pgTAP test for Hastap (assertion 94).

SELECT * FROM check_test(
    has_type( 'public', 'myType', 'mydesc' ),
    true,
    'has_type(schema, myType, desc)',
    'mydesc',
    ''
);

Explanation: SQL assertion from pgTAP test suite for Hastap.


Question: Show an example of PostgreSQL CREATE TABLE (example 11).

CREATE TABLE distributors ( did integer, name varchar(40), UNIQUE(name) );

Explanation: PostgreSQL CREATE TABLE command.


Question: Show a SQL definition from the pglogical project (pglogical--2.3.0, item 19).

CREATE TABLE pglogical.replication_set_table (
    set_id oid NOT NULL,
    set_reloid regclass NOT NULL,
    set_att_list text[],
    set_row_filter pg_node_tree,
    set_nsptarget name NOT NULL,
    set_reltarget name NOT NULL,
    PRIMARY KEY(set_id, set_reloid)
) WITH (user_catalog_table=true);

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


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

select id, f_timestamptz, first_value(id) over w, last_value(id) over w
from datetimes
window w as (order by f_timestamptz range between
             '-infinity'::interval following and
             'infinity'::interval following);  -- error, negative offset disallowed

select id, f_timestamp, first_value(id) over w, last_value(id) over w
from datetimes
window w as (order by f_timestamp range between
             '1 year'::interval preceding and '1 year'::interval following);

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

SELECT count(*) FROM (select id, f_timestamptz, first_value(id) over w, last_value(id) over w
from datetimes
window w as (order by f_timestamptz range between
             '-infinity'::interval following and
             'infinity'::interval following);  -- error, negative offset disallowed

select id, f_timestamp, first_value(id) over w, last_value(id) over w
from datetimes
window w as (order by f_timestamp range between
             '1 year'::interval preceding and '1 year'::interval following)) AS _sub;


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

INSERT INTO money_data VALUES ('$123.459');

Explanation: DML from PostgreSQL core regression test for Money.


Question: Write the DDL statement from PostgreSQL regression test 'enum' (example 112).

CREATE FUNCTION echo_me(rainbow) RETURNS text AS $$
BEGIN
RETURN $1::text || 'wtf';
END
$$ LANGUAGE plpgsql;

Explanation: DDL from PostgreSQL core regression test for Enum.


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

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

SELECT count(*) FROM (SELECT '[[1,2,2]]'::jsonb <@ '[[1,2]]'::jsonb) AS _sub;


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

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

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


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

SELECT btrim('xxxxxtrimxxxx'::citext, 'x'::citext ) = 'trim' AS t;

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


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

CREATE OR REPLACE FUNCTION has_index ( NAME, NAME, NAME, NAME, text )
RETURNS TEXT AS $$
    SELECT has_index( $1, $2, $3, ARRAY[$4], $5 );
$$ LANGUAGE sql;

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


Question: Show an example of PostgreSQL SET SESSION AUTH (example 1).

SELECT SESSION_USER, CURRENT_USER; session_user | current_user --------------+-------------- peter | peter SET SESSION AUTHORIZATION 'paul'; SELECT SESSION_USER, CURRENT_USER; session_user | current_user --------------+-------------- paul | paul;

Explanation: PostgreSQL SET SESSION AUTH command.


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

--
-- SECURITY DEFINER | INVOKER
--
CREATE FUNCTION functest_C_1(int) RETURNS bool LANGUAGE 'sql'
       AS 'SELECT $1 > 0';

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


Question: Show a SQL definition from the pg_partman project (pg_partman--1.1.0--1.2.0, item 5).

/*
 * Function to re-apply ownership & privileges on all child tables in a partition set using parent table as reference
 */
CREATE OR REPLACE FUNCTION reapply_privileges(p_parent_table text) RETURNS void
    LANGUAGE plpgsql SECURITY DEFINER
    AS $$
DECLARE

v_all               text[] := ARRAY['SELECT', 'INSERT', 'UPDATE', 'DELETE', 'TRUNCATE', 'REFERENCES', 'TRIGGER'];
v_child_owner       text;
v_child_table       text;
v_child_grant       record;
v_count             int;
v_grant             text;
v_grantees          text[];
v_job_id            bigint;
v_jobmon_schema     text;
v_match             boolean;
v_old_search_path   text;
v_parent_owner      text;
v_owner_sql         text;
v_revoke            text[];
v_parent_grant      record;
v_sql               text;
v_step_id           bigint;

BEGIN

SELECT count(*) INTO v_count FROM @extschema@.part_config WHERE parent_table = p_parent_table;
IF v_count = 0 THEN
    RAISE EXCEPTION 'Given table is not managed by this extention: %', p_parent_table;
END IF;

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

IF v_jobmon_schema IS NOT NULL THEN
    v_job_id := add_job('PARTMAN RE-APPLYING PRIVILEGES TO ALL CHILD TABLES OF: '||p_parent_table);
    v_step_id := add_step(v_job_id, 'Setting new child table privileges');
END IF;

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

FOR v_child_table IN
    SELECT n.nspname||'.'||c.relname FROM pg_inherits i join pg_class c ON i.inhrelid = c.oid join pg_namespace n ON c.relnamespace = n.oid WHERE i.inhparent::regclass = p_parent_table::regclass ORDER BY i.inhrelid ASC
LOOP
    IF v_jobmon_schema IS NOT NULL THEN
        PERFORM update_step(v_step_id, 'PENDING', 'Currently on child partition in ascending order: '||v_child_table);
    END IF;
    v_grantees := NULL;
    FOR v_parent_grant IN
        SELECT array_agg(DISTINCT privilege_type::text ORDER BY privilege_type::text) AS types, grantee
        FROM information_schema.table_privileges
        WHERE table_schema ||'.'|| table_name = p_parent_table
        GROUP BY grantee
    LOOP
        -- Compare parent & child grants. Don't re-apply if it already exists
        v_match := false;
        FOR v_child_grant IN
            SELECT array_agg(DISTINCT privilege_type::text ORDER BY privilege_type::text) AS types, grantee
            FROM information_schema.table_privileges
            WHERE table_schema ||'.'|| table_name = v_child_table
            GROUP BY grantee
        LOOP
            IF v_parent_grant.types = v_child_grant.types AND v_parent_grant.grantee = v_child_grant.grantee THEN
                v_match := true;
            END IF;
        END LOOP;

        IF v_match = false THEN
            EXECUTE 'GRANT '||array_to_string(v_parent_grant.types, ',')||' ON '||v_child_table||' TO '||v_parent_grant.grantee;
            SELECT array_agg(r) INTO v_revoke FROM (SELECT unnest(v_all) AS r EXCEPT SELECT unnest(v_parent_grant.types)) x;
            IF v_revoke IS NOT NULL THEN
                EXECUTE 'REVOKE '||array_to_string(v_revoke, ',')||' ON '||v_child_table||' FROM '||v_parent_grant.grantee||' CASCADE';
            END IF;
        END IF;

        v_grantees := array_append(v_grantees, v_parent_grant.grantee::text);

    END LOOP;

    -- Revoke all privileges from roles that have none on the parent
    IF v_grantees IS NOT NULL THEN
        SELECT array_agg(r) INTO v_revoke FROM (
            SELECT DISTINCT grantee::text AS r FROM information_schema.table_privileges WHERE table_schema ||'.'|| table_name = v_child_table
            EXCEPT
            SELECT unnest(v_grantees)) x;
        IF v_revoke IS NOT NULL THEN
            EXECUTE 'REVOKE ALL ON '||v_child_table||' FROM '||array_to_string(v_revoke, ',');
        END IF;
    END IF;

    SELECT tableowner INTO v_child_owner FROM pg_tables WHERE schemaname ||'.'|| tablename = v_child_table;
    IF v_parent_owner <> v_child_owner THEN
        EXECUTE 'ALTER TABLE '||v_child_table||' OWNER TO '||v_parent_owner;
    END IF;

END LOOP;

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

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

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


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

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


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

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

SELECT count(*) FROM (SELECT '{[1,9)}' @> '{[1,5), [6,9)}'::nummultirange) AS _sub;


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

-- user-defined operator class in partition key
CREATE FUNCTION my_int4_sort(int4,int4) RETURNS int LANGUAGE sql
  AS $$ SELECT CASE WHEN $1 = $2 THEN 0 WHEN $1 > $2 THEN 1 ELSE -1 END; $$;
CREATE OPERATOR CLASS test_int4_ops FOR TYPE int4 USING btree AS
  OPERATOR 1 < (int4,int4), OPERATOR 2 <= (int4,int4),
  OPERATOR 3 = (int4,int4), OPERATOR 4 >= (int4,int4),
  OPERATOR 5 > (int4,int4), FUNCTION 1 my_int4_sort(int4,int4);
CREATE TABLE partkey_t (a int4) PARTITION BY RANGE (a test_int4_ops);
CREATE TABLE partkey_t_1 PARTITION OF partkey_t FOR VALUES FROM (0) TO (1000);
INSERT INTO partkey_t VALUES (100);
INSERT INTO partkey_t VALUES (200);

-- cleanup
DROP TABLE parted, list_parted, range_parted, list_parted2, range_parted2, range_parted3;
DROP TABLE partkey_t, hash_parted, hash_parted2;
DROP OPERATOR CLASS test_int4_ops USING btree;
DROP FUNCTION my_int4_sort(int4,int4);

-- comments on partitioned tables columns
CREATE TABLE parted_col_comment (a int, b text) PARTITION BY LIST (a);
COMMENT ON TABLE parted_col_comment IS 'Am partitioned table';
COMMENT ON COLUMN parted_col_comment.a IS 'Partition key';
SELECT obj_description('parted_col_comment'::regclass);
\d+ parted_col_comment
DROP TABLE parted_col_comment;

-- specifying storage parameters for partitioned tables is not supported
CREATE TABLE parted_col_comment (a int, b text) PARTITION BY LIST (a) WITH (fillfactor=100);

-- list partitioning on array type column
CREATE TABLE arrlp (a int[]) PARTITION BY LIST (a);
CREATE TABLE arrlp12 PARTITION OF arrlp FOR VALUES IN ('{1}', '{2}');
\d+ arrlp12
DROP TABLE arrlp;

-- partition on boolean column
create table boolspart (a bool) partition by list (a);
create table boolspart_t partition of boolspart for values in (true);
create table boolspart_f partition of boolspart for values in (false);
\d+ boolspart
drop table boolspart;

-- partitions mixing temporary and permanent relations
create table perm_parted (a int) partition by list (a);
create temporary table temp_parted (a int) partition by list (a);
create table perm_part partition of temp_parted default; -- error
create temp table temp_part partition of perm_parted default; -- error
create temp table temp_part partition of temp_parted default; -- ok
drop table perm_parted cascade;
drop table temp_parted cascade;

-- check that adding partitions to a table while it is being used is prevented
create table tab_part_create (a int) partition by list (a);
create or replace function func_part_create() returns trigger
  language plpgsql as $$
  begin
    execute 'create table tab_part_create_1 partition of tab_part_create for values in (1)';

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


Question: PostgreSQL regression test 'misc_functions': Write the SELECT query (example 126).

SELECT segment_number > 0 AS ok_segment_number, timeline_id
  FROM pg_split_walfile_name('ffffffFF00000001000000af');

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

SELECT count(*) FROM (SELECT segment_number > 0 AS ok_segment_number, timeline_id
  FROM pg_split_walfile_name('ffffffFF00000001000000af')) AS _sub;


Question: pgTAP test for Usergroup (assertion 26).

SELECT * FROM check_test(
    isnt_member_of('meanies', ARRAY[current_user] ),
    true,
    'isnt_member_of(meanies, [current_user])',
    'Should not have members of role meanies',
    ''
);

Explanation: SQL assertion from pgTAP test suite for Usergroup.


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

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

SELECT count(*) FROM (SELECT U&'wrong: \db99xy') AS _sub;


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

Explanation: DML from PostgreSQL core regression test for Numeric.


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

CREATE TABLE i_am_a_failure() USING "I do not exist AM";

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


Question: pgTAP test for Aretap (assertion 50).

SELECT * FROM check_test(
    tables_are( ARRAY['bar', 'baz'] ),
    false,
    'tables_are(tables) extra and missing',
    'Search path ' || pg_catalog.current_setting('search_path') || ' should have the correct tables',
    '    Extra tables:' || '
        fo[ou]
        fo[ou]
    Missing tables:' || '
        ba[rz]
        ba[rz]',
    true
);

Explanation: SQL assertion from pgTAP test suite for Aretap.


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

select ROW('ABC','DEF') ~~ ROW('DEF','ABC') as fail;

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

SELECT count(*) FROM (select ROW('ABC','DEF') ~~ ROW('DEF','ABC') as fail) AS _sub;


Question: PostgreSQL regression test 'transactions': Write the SELECT query (example 149).

SELECT a FROM savepoints WHERE a BETWEEN 18 AND 22;

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

SELECT count(*) FROM (SELECT a FROM savepoints WHERE a BETWEEN 18 AND 22) AS _sub;


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

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


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

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

SELECT count(*) FROM (SELECT '0'::numeric / '0') AS _sub;


Question: pgTAP test for Partitions (assertion 1).

\unset ECHO
\i test/setup.sql

SELECT plan(102);

Explanation: SQL assertion from pgTAP test suite for Partitions.


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

SELECT power(float8 '1', float8 '-inf');

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

SELECT count(*) FROM (SELECT power(float8 '1', float8 '-inf')) AS _sub;


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

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


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

select ceiling(f1) as ceiling_f1 from float8_tbl f;

SELECT count(*) FROM (select ceiling(f1) as ceiling_f1 from float8_tbl f) AS _sub;


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

create view numeric_view as
  select
    f1, f1::numeric(16,4) as f1164, f1::numeric as f1n,
    f2, f2::numeric(16,4) as f2164, f2::numeric as f2n
  from numeric_tbl;

Explanation: DDL from PostgreSQL core regression test for Expressions.


Question: pgTAP test for Functap (assertion 236).

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

Explanation: SQL assertion from pgTAP test suite for Functap.


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

SELECT nummultirange() &< 'empty'::numrange;

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

SELECT count(*) FROM (SELECT nummultirange() &< 'empty'::numrange) AS _sub;


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

SELECT 'test_prepared_1' AS relation, locktype, mode
FROM pg_locks
WHERE locktype = 'relation'
  AND relation = 'test_prepared1'::regclass;

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


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

CREATE FUNCTION isneq(isbn13, isbn)
	RETURNS boolean
	AS 'int8eq'
	LANGUAGE 'internal'
	IMMUTABLE STRICT
	PARALLEL SAFE;

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


Question: pgTAP test for Aretap (assertion 78).

SELECT * FROM check_test(
    functions_are( ___myfunk('') ),
    true,
    'functions_are(functions)',
    'Search path ' || pg_catalog.current_setting('search_path') || ' should have the correct functions',
    ''
);


Question: PL/pgSQL test: Plpython Global (example 3).

CREATE FUNCTION static_test() returns int4
    AS
'if "call" in SD:
	SD["call"] = SD["call"] + 1
else:
	SD["call"] = 1
return SD["call"]
'
    LANGUAGE plpython3u;

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


Question: PostgreSQL Ddl: show example 44.

CREATE TABLE variants ( id integer, product_no integer, name text, valid_at daterange, PRIMARY KEY (id, valid_at WITHOUT OVERLAPS) );

Explanation: Example from PostgreSQL documentation on Ddl.


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

CREATE VIEW vw_getrngfunc AS SELECT * FROM getrngfunc1(1);

Explanation: DDL from PostgreSQL core regression test for Rangefuncs.


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

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

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


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

select generate_series(1,3)+1 order by generate_series(1,3);

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

SELECT count(*) FROM (select generate_series(1,3)+1 order by generate_series(1,3)) AS _sub;


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

create unique index Room_rno on Room using btree (roomno bpchar_ops);

Explanation: DDL from PostgreSQL core regression test for Plpgsql.


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

CREATE VIEW rls_view AS SELECT * FROM z1 WHERE f_leak(b);

Explanation: DDL from PostgreSQL core regression test for Rowsecurity.


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

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

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


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

CREATE VIEW rw_view1 AS SELECT * FROM base_tbl WHERE a>0 OFFSET 0; -- not updatable without rules/triggers
CREATE VIEW rw_view2 AS SELECT * FROM rw_view1 WHERE a<10;

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


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

CREATE TABLE testpub_tbl2 (id serial primary key, data text);

Explanation: DDL from PostgreSQL core regression test for Publication.


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

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


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

SELECT extract(epoch from '5000-01-01 00:00:00'::timestamp);

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

SELECT count(*) FROM (SELECT extract(epoch from '5000-01-01 00:00:00'::timestamp)) AS _sub;


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

select row(1, -2)::testtype1 = row(1, -3)::testtype1;

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

SELECT count(*) FROM (select row(1, -2)::testtype1 = row(1, -3)::testtype1) AS _sub;


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

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

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


Question: pgTAP test for Functap (assertion 165).

-- is_normal_function ( NAME, NAME, TEXT )
-- isnt_normal_function ( NAME, NAME, TEXT )
SELECT * FROM check_test(
    is_normal_function( 'someschema', 'huh', 'whatever' ),
    true,
    'is_normal_function(schema, func, desc)',
    'whatever',
    ''
);

Explanation: SQL assertion from pgTAP test suite for Functap.


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

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


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

select * from test2 where t ~* '[abc]{3}[def]{3}';

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


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

create table part_gg2 partition of part_gg for values from (1) to (10) partition by range (b);

Explanation: DDL from PostgreSQL core regression test for Insert.


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

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

SELECT count(*) FROM (select jsonb_delete('{"a":1 , "b":2, "c":3}'::jsonb, 'b')) AS _sub;


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

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

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

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


Question: Write the DML statement from PostgreSQL regression test 'partition_prune' (example 266).

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


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

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


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

SELECT * FROM check_estimated_rows('SELECT * FROM mcv_lists WHERE a IN (1, 2, 51, 52) AND b IN ( ''1'', ''2'')');

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

SELECT count(*) FROM (SELECT * FROM check_estimated_rows('SELECT * FROM mcv_lists WHERE a IN (1, 2, 51, 52) AND b IN ( ''1'', ''2'')')) AS _sub;


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

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

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


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

create table ec0 (ff int8 primary key, f1 int8, f2 int8);

Explanation: DDL from PostgreSQL core regression test for Equivclass.


Question: PL/pgSQL test: Plpython Schema (example 3).

CREATE INDEX users_fname_idx ON users(fname);

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


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

create table fktable(ftest1 int, ftest2 inet, foreign key(ftest2, ftest1) references pktable);

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


Question: PostgreSQL Rules: show example 50.

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

Explanation: Example from PostgreSQL documentation on Rules.


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

SELECT timestamp with time zone '1996-03-01' - interval '1 second' AS "Feb 29";

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

SELECT count(*) FROM (SELECT timestamp with time zone '1996-03-01' - interval '1 second' AS "Feb 29") AS _sub;


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

create table part_abc_3 partition of part_abc for values in (3, 4) partition by range (d);

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


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

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

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


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

SELECT * FROM check_estimated_rows('SELECT * FROM functional_dependencies WHERE (a * 2) IN (2, 4, 102, 104) AND upper(b) IN (''1'', ''2'')');

SELECT count(*) FROM (SELECT * FROM check_estimated_rows('SELECT * FROM functional_dependencies WHERE (a * 2) IN (2, 4, 102, 104) AND upper(b) IN (''1'', ''2'')')) AS _sub;


Question: pgTAP test for Throwtap (assertion 10).

SELECT * FROM check_test(
    throws_ok( 'EXECUTE mytest', 'P0001'),
    true,
    'execute & errcode',
    'threw P0001'
    ''
);

Explanation: SQL assertion from pgTAP test suite for Throwtap.


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

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


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

SELECT DISTINCT p1.proargtypes[7]::regtype, p2.proargtypes[7]::regtype
FROM pg_proc AS p1, pg_proc AS p2
WHERE p1.oid != p2.oid AND
    p1.prosrc = p2.prosrc AND
    p1.prolang = 12 AND p2.prolang = 12 AND
    p1.prokind != 'a' AND p2.prokind != 'a' AND
    (p1.proargtypes[7] < p2.proargtypes[7])
ORDER BY 1, 2;

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

SELECT count(*) FROM (SELECT DISTINCT p1.proargtypes[7]::regtype, p2.proargtypes[7]::regtype
FROM pg_proc AS p1, pg_proc AS p2
WHERE p1.oid != p2.oid AND
    p1.prosrc = p2.prosrc AND
    p1.prolang = 12 AND p2.prolang = 12 AND
    p1.prokind != 'a' AND p2.prokind != 'a' AND
    (p1.proargtypes[7] < p2.proargtypes[7])
ORDER BY 1, 2) AS _sub;