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

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

SELECT count(*) FROM (SELECT sqrt('-1'::numeric)) AS _sub;


Question: PL/pgSQL test: Pltcl Trigger (example 5).

--
-- Function to check key existence in T_pkey1
--
create function check_pkey1_exists(int4, bpchar) returns bool as E'
    if {![info exists GD]} {
        set GD(plan) [spi_prepare				\\
	    "select 1 from T_pkey1				\\
	        where key1 = \\$1 and key2 = \\$2"		\\
	    {int4 bpchar}]
    }

    set n [spi_execp -count 1 $GD(plan) [list $1 $2]]

    if {$n > 0} {
        return "t"
    }
    return "f"
' language pltcl;

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


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

Explanation: DML from PostgreSQL core regression test for Rules.


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

create table idxpart1 partition of idxpart for values from (1) to (1000) partition by range (a);

Explanation: DDL from PostgreSQL core regression test for Indexing.


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

SELECT sum(unique1) over (partition by ten
	order by four groups between 0 preceding and 0 following exclude current row), unique1, four, ten
FROM tenk1 WHERE unique1 < 10;

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

SELECT count(*) FROM (SELECT sum(unique1) over (partition by ten
	order by four groups between 0 preceding and 0 following exclude current row), unique1, four, ten
FROM tenk1 WHERE unique1 < 10) AS _sub;


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

CREATE TABLE alpha_neg_p1 PARTITION OF alpha_neg FOR VALUES FROM (100) TO (200);

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


Question: pgTAP test for Resultset (assertion 35).

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

Explanation: SQL assertion from pgTAP test suite for Resultset.


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

SELECT * FROM onek_copy EXCEPT ALL SELECT * FROM onek;

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

SELECT count(*) FROM (SELECT * FROM onek_copy EXCEPT ALL SELECT * FROM onek) AS _sub;


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

Explanation: DML from PostgreSQL core regression test for Copyselect.


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

SELECT * FROM INT8_TBL WHERE q2 <= '456'::int2;

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

SELECT count(*) FROM (SELECT * FROM INT8_TBL WHERE q2 <= '456'::int2) AS _sub;


Question: pgTAP test for Proctap (assertion 69).

-- is_procedure( NAME )
-- isnt_procedure( NAME )
SELECT * FROM check_test(
    is_procedure( 'argpubproc' ),
    true,
    'is_procedure(proc)',
    'Function argpubproc() should be a procedure',
    ''
);

Explanation: SQL assertion from pgTAP test suite for Proctap.


Question: Show a SQL definition from the pgaudit project (pgaudit, item 34).

--
-- Setup role-based tests
CREATE TABLE test2
(
	id INT
);

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


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

SELECT levenshtein('GUMBO', 'GAMBOL', 2, 1, 1);

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


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

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

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

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


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

SELECT range_length_histogram, range_empty_frac, range_bounds_histogram
   FROM pg_stats_ext_exprs
   WHERE statistics_name = 'stats_ext_range';

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

SELECT count(*) FROM (SELECT range_length_histogram, range_empty_frac, range_bounds_histogram
   FROM pg_stats_ext_exprs
   WHERE statistics_name = 'stats_ext_range') AS _sub;


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

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


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

CREATE POLICY p4 ON r2 FOR DELETE USING (false);

Explanation: DDL from PostgreSQL core regression test for Rowsecurity.


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

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


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

SELECT relfilenode = :main_filenode AS is_same_main_filenode
  FROM pg_class WHERE relname = 'vac_option_tab';

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

SELECT count(*) FROM (SELECT relfilenode = :main_filenode AS is_same_main_filenode
  FROM pg_class WHERE relname = 'vac_option_tab') AS _sub;


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

$$ language plpgsql;
create trigger aaa after insert on parted_trig
   for each row execute procedure trigger_notice('quirky', 1);

-- Verify propagation of trigger arguments to partitions attached after creating trigger
create table parted_trig2 partition of parted_trig for values in (2);
create table parted_trig3 (like parted_trig);
alter table parted_trig attach partition parted_trig3 for values in (3);
insert into parted_trig values (1), (2), (3);
drop table parted_trig;

-- test irregular partitions (i.e., different column definitions),
-- including that the WHEN clause works
create function bark(text) returns bool language plpgsql immutable
  as $$ begin raise notice '% <- woof!', $1; return true; end; $$;

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


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

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

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


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

SELECT casefold('AbCd 123 #$% ıiIİ ẞ ß Ǆǅǆ Σσς' COLLATE "en-x-icu");

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

SELECT count(*) FROM (SELECT casefold('AbCd 123 #$% ıiIİ ẞ ß Ǆǅǆ Σσς' COLLATE "en-x-icu")) AS _sub;


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

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

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


Question: pgTAP test for Resultset (assertion 393).

-- Fail with invalid column counts.
SELECT * FROM check_test(
    bag_ne(
        'anames',
        ARRAY['Andrew', 'Anna', 'Anthony', 'Antonio', 'Angelina', 'Andrea', 'Angel' ]
    ),
    false,
    'bag_ne(sql, array) incompatible types',
    '',
    '    Columns differ between queries:
        have: (integer,text)
        want: (text)'
);

Explanation: SQL assertion from pgTAP test suite for Resultset.


Question: pgTAP test for Matching (assertion 6).

-- Check doesnt_match.
SELECT doesnt_match( 'foo'::text, 'a', 'doesnt_match() should work' );

Explanation: SQL assertion from pgTAP test suite for Matching.


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

create domain weirdfloat float8 check((1 / value) < 10);

Explanation: DDL from PostgreSQL core regression test for Domain.


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

-- error in cursor loop with commit
TRUNCATE test1;

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


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

CREATE OR REPLACE FUNCTION _timescaledb_internal.show_chunk(chunk regclass) RETURNS TABLE(chunk_id INTEGER, hypertable_id INTEGER, schema_name NAME, table_name NAME, relkind "char", slices JSONB) LANGUAGE PLPGSQL AS $$
BEGIN
  IF current_setting('timescaledb.enable_deprecation_warnings', true)::bool THEN
    RAISE WARNING 'function _timescaledb_internal.show_chunk(regclass) is deprecated and has been moved to _timescaledb_functions schema. this compatibility function will be removed in a future version.';
  END IF;
  RETURN QUERY SELECT * FROM _timescaledb_functions.show_chunk($1);
END$$
SET search_path TO pg_catalog,pg_temp;

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


Question: pgTAP test for Pgtap--0.93.0--0.94.0 (assertion 7).

-- hasnt_foreign_table( schema, table )
CREATE OR REPLACE FUNCTION hasnt_foreign_table ( NAME, NAME )
RETURNS TEXT AS $$
    SELECT ok(
        NOT _rexists( 'f', $1, $2 ),
        'Foreign table ' || quote_ident($1) || '.' || quote_ident($2) || ' not should exist'
    );
$$ LANGUAGE SQL;

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


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

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

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


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

INSERT INTO few VALUES(1, 'a', 'foo'),(2, 'a', 'bar'),(3, 'b', 'bar');

Explanation: DML from PostgreSQL core regression test for Tsrf.


Question: pgTAP test for Moretap (assertion 6).

-- Make sure that false and NULL work as well
SELECT is( _set('plan', 6), 6, 'Increase internal plan value after testing finish' );

Explanation: SQL assertion from pgTAP test suite for Moretap.


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

SELECT '[{"attributes" : {"a": 1}, "ndistinct" : 1}]'::pg_ndistinct;

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

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


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

CREATE INDEX ctlt1_fnidx ON ctlt1 ((a || b));

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


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

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

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


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

create statistics stts_s1.stts_foo on col1, col2 from stts_t3;

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


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

CREATE FUNCTION dblink_open (text, text, text)
RETURNS text
AS 'MODULE_PATHNAME','dblink_open'
LANGUAGE C STRICT PARALLEL RESTRICTED;


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

create table notnull_tbl_fail (a int generated by default as identity, constraint foo not null a no inherit);

Explanation: DDL from PostgreSQL core regression test for Constraints.


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

SELECT * FROM test_macaddr8 WHERE i>'22:00:5c:08:55:08:01:02'::macaddr8 ORDER BY i;

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


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

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


Question: pgTAP test for Proctap (assertion 12).

SELECT * FROM check_test(
    isnt_procedure( 'procschema', 'aproc', '{}'::name[], 'whatever' ),
    false,
    'isnt_procedure(schema, proc, noargs, desc)',
    'whatever',
    ''
);

Explanation: SQL assertion from pgTAP test suite for Proctap.


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

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

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


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

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

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

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


Question: pgTAP test for Aretap (assertion 18).

CREATE DOMAIN public."myDomain" AS text CHECK ( TRUE );

Explanation: SQL assertion from pgTAP test suite for Aretap.


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

CREATE TABLE test_hyper (i bigint, j double precision, k bigint, ts timestamp);


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

CREATE OR REPLACE FUNCTION _timescaledb_internal.test_status_ssl(int) RETURNS JSONB
    AS :MODULE_PATHNAME, 'ts_test_status_ssl' LANGUAGE C IMMUTABLE STRICT PARALLEL SAFE;


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

CREATE OR REPLACE FUNCTION plan( integer )
RETURNS TEXT AS $$
DECLARE
    rcount INTEGER;
BEGIN
    BEGIN
        EXECUTE '
            CREATE TEMP SEQUENCE __tcache___id_seq;
            CREATE TEMP TABLE __tcache__ (
                id    INTEGER NOT NULL DEFAULT nextval(''__tcache___id_seq''),
                label TEXT    NOT NULL,
                value INTEGER NOT NULL,
                note  TEXT    NOT NULL DEFAULT ''''
            );
            CREATE UNIQUE INDEX __tcache___key ON __tcache__(id);
            GRANT ALL ON TABLE __tcache__ TO PUBLIC;
            GRANT ALL ON TABLE __tcache___id_seq TO PUBLIC;

            CREATE TEMP SEQUENCE __tresults___numb_seq;
            GRANT ALL ON TABLE __tresults___numb_seq TO PUBLIC;
        ';

    EXCEPTION WHEN duplicate_table THEN
        -- Raise an exception if there's already a plan.
        EXECUTE 'SELECT TRUE FROM __tcache__ WHERE label = ''plan''';
      GET DIAGNOSTICS rcount = ROW_COUNT;
        IF rcount > 0 THEN
           RAISE EXCEPTION 'You tried to plan twice!';
        END IF;
    END;

    -- Save the plan and return.
    PERFORM _set('plan', $1 );
    PERFORM _set('failed', 0 );
    RETURN '1..' || $1;
END;
$$ LANGUAGE plpgsql strict;

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


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

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

SELECT count(*) FROM (SELECT d1 FROM TIMESTAMPTZ_TBL) AS _sub;


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

CREATE VIEW jsonb_table_view6 AS
SELECT * FROM
	JSON_TABLE(
		jsonb 'null', 'lax $[*]' PASSING 1 + 2 AS a, json '"foo"' AS "b c"
		COLUMNS (
			js2 json PATH '$',
			jsb2w jsonb PATH '$' WITH WRAPPER,
			jsb2q jsonb PATH '$' OMIT QUOTES,
			ia int[] PATH '$',
			ta text[] PATH '$',
			jba jsonb[] PATH '$'));

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


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

DROP FUNCTION testpub_rf_func1(integer, integer);

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


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

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

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

BEGIN

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

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

FOREACH v_time IN ARRAY p_partition_times LOOP

    v_partition_name := p_parent_table || '_p';

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

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

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

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

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

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

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

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

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

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

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

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

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

END LOOP;

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

RETURN v_partition_name;

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

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


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

\set ON_ERROR_STOP 1
CREATE TABLE truncate_nested (color int);

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


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

INSERT INTO notnull_part1_3_upg values(NULL,1);

Explanation: DML from PostgreSQL core regression test for Constraints.


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

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


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

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


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

SELECT relname, a.* FROM ONLY a, pg_class where a.tableoid = pg_class.oid;

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

SELECT count(*) FROM (SELECT relname, a.* FROM ONLY a, pg_class where a.tableoid = pg_class.oid) AS _sub;


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

\set TEST_DBNAME_EXTRA :TEST_DBNAME _extra

\o /dev/null
\ir include/insert_two_partitions.sql
\o
\c :TEST_DBNAME :ROLE_SUPERUSER

CREATE OR REPLACE FUNCTION bgw_wait(database TEXT, timeout INT, raise_error BOOLEAN DEFAULT TRUE)
RETURNS VOID
AS :MODULE_PATHNAME, 'ts_bgw_wait'
LANGUAGE C VOLATILE;


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

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


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

SELECT count(*) FROM (select interval 'P2147483647M0.1Y') AS _sub;


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

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

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


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

/* src/pl/tcl/pltcl--1.0.sql */

CREATE FUNCTION pltcl_call_handler() RETURNS language_handler
  LANGUAGE c AS 'MODULE_PATHNAME';

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


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

SELECT * FROM connectby('connectby_int', '1::int, NULL::int; --', 'parent_keyid', '2', 0) AS t(keyid int, parent_keyid int, level int);

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


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

SELECT overlay(B'0101011100' placing '001' from 11);

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

SELECT count(*) FROM (SELECT overlay(B'0101011100' placing '001' from 11)) AS _sub;


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

INSERT INTO TIMESTAMPTZ_TBL VALUES ('Mon Feb 10 17:32:01.6 1997 PST');

Explanation: DML from PostgreSQL core regression test for Timestamptz.


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

select * from
  int8_tbl a left join
  lateral (select *, a.q2 as x from int8_tbl b) ss on a.q2 = ss.q1;

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

SELECT count(*) FROM (select * from
  int8_tbl a left join
  lateral (select *, a.q2 as x from int8_tbl b) ss on a.q2 = ss.q1) AS _sub;


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

INSERT INTO spill_test SELECT 'serialize-topbig--1:'||g.i FROM generate_series(1, 5000) g(i);

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


Question: pgTAP test for Resultset (assertion 198).

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

Explanation: SQL assertion from pgTAP test suite for Resultset.


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

Explanation: DDL from PostgreSQL core regression test for Rules.


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

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

SELECT count(*) FROM (select make_date(2013, 2, 30)) AS _sub;


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

CREATE TABLE t1(a int PRIMARY KEY, b int, c int);

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


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

SELECT '2011-03-27 01:00:00'::timestamp AT TIME ZONE 'MSK';

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

SELECT count(*) FROM (SELECT '2011-03-27 01:00:00'::timestamp AT TIME ZONE 'MSK') AS _sub;


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

Explanation: DML from PostgreSQL core regression test for Numeric.


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

CREATE INDEX dupindexcols_i ON dupindexcols (f1, id, f1 text_pattern_ops);

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


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

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


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

SELECT test_json -> 9 FROM test_jsonb WHERE json_type = 'array';

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

SELECT count(*) FROM (SELECT test_json -> 9 FROM test_jsonb WHERE json_type = 'array') AS _sub;


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

SELECT t1.a, t1.c, t2.b, t2.c FROM prt1 t1 RIGHT JOIN prt2 t2 ON t1.a = t2.b WHERE t2.a = 0 ORDER BY t1.a, t2.b;

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

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


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

insert into shoelace values ('sl10', 1000, 'magenta', 40.0, 'inch', 0.0)
  on conflict do nothing;

Explanation: DML from PostgreSQL core regression test for Rules.


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

CREATE VIEW shoe AS
	SELECT sh.shoename,
		   sh.sh_avail,
		   sh.slcolor,
		   sh.slminlen,
		   sh.slminlen * un.un_fact AS slminlen_cm,
		   sh.slmaxlen,
		   sh.slmaxlen * un.un_fact AS slmaxlen_cm,
		   sh.slunit
	  FROM shoe_data sh, unit un
	 WHERE sh.slunit = un.un_name;


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

select count(*) from t_test_trgm where t like '%99%' and t like '%qwerty%';

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


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


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

select version, tree_level,
    index_size / current_setting('block_size')::int as index_size,
    root_block_no, internal_pages, leaf_pages, empty_pages, deleted_pages,
    avg_leaf_density, leaf_fragmentation
    from pgstatindex('test_pkey'::name);

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


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

INSERT INTO TIMESTAMP_TBL VALUES ('19970210 173201 America/New_York');

Explanation: DML from PostgreSQL core regression test for Timestamp.


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

-- test hstore[] -> python
CREATE FUNCTION test1arr(val hstore[]) RETURNS int
LANGUAGE plpython3u
TRANSFORM FOR TYPE hstore
AS $$
assert(val == [{'aa': 'bb', 'cc': None}, {'dd': 'ee'}])
return len(val)
$$;

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


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

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

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


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

select * from boolpart where a is not true;

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

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


Question: Write the DDL statement from PostgreSQL regression test 'incremental_sort' (example 122).

create table prt_tbl_1 partition of prt_tbl for values from (0) to (100);

Explanation: DDL from PostgreSQL core regression test for Incremental Sort.


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

ALTER EXTENSION pgtap ADD FUNCTION _cast_exists ( NAME, 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 283).

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

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


Question: PL/pgSQL test: Pltcl Trigger (example 21).

create trigger pkey2_after after update or delete on T_pkey2
	for each row execute procedure
	trig_pkey2_after();

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


Question: pgTAP test for Index (assertion 3).

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

Explanation: SQL assertion from pgTAP test suite for Index.


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

create domain d_fail as int4 not null null;

Explanation: DDL from PostgreSQL core regression test for Domain.


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

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

Explanation: DML from PostgreSQL core regression test for Subselect.


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

SELECT ts_rank_cd(' a:1 sa:2A sb:2D g'::tsvector, 'a <-> s:*');

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

SELECT count(*) FROM (SELECT ts_rank_cd(' a:1 sa:2A sb:2D g'::tsvector, 'a <-> s:*')) AS _sub;


Question: PostgreSQL Advanced: show example 7.

SELECT depname, empno, salary, avg(salary) OVER (PARTITION BY depname) FROM empsalary;

Explanation: Example from PostgreSQL documentation on Advanced.


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

SELECT xmlserialize(CONTENT  '<?xml version="1.0" encoding="UTF-8"?><foo><bar><val>73</val></bar></foo>' AS text INDENT);

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

SELECT count(*) FROM (SELECT xmlserialize(CONTENT  '<?xml version="1.0" encoding="UTF-8"?><foo><bar><val>73</val></bar></foo>' AS text INDENT)) AS _sub;


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

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


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

select websearch_to_tsquery('english', 'this is ----fine');

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

SELECT count(*) FROM (select websearch_to_tsquery('english', 'this is ----fine')) AS _sub;


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

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


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

SELECT * FROM foo_ordered_set();  -- fail

--
-- Check passing a tuple argument
--

CREATE OR REPLACE FUNCTION perl_get_field(footype, text) RETURNS integer AS $$
    return $_[0]->{$_[1]};
$$ LANGUAGE plperl;

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


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

select description, inbytes, (test_conv(inbytes, 'utf8', 'latin5')).* from utf8_inputs;

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

SELECT count(*) FROM (select description, inbytes, (test_conv(inbytes, 'utf8', 'latin5')).* from utf8_inputs) AS _sub;


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

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


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

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


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

INSERT INTO stxdinp SELECT 1, a/100, a/100 FROM generate_series(1, 999) a;

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


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

SELECT *
FROM pg_stats
WHERE schemaname = 'stats_import'
AND tablename = 'test'
AND inherited = false
AND attname = 'arange';

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

SELECT count(*) FROM (SELECT *
FROM pg_stats
WHERE schemaname = 'stats_import'
AND tablename = 'test'
AND inherited = false
AND attname = 'arange') AS _sub;


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

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

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

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


Question: pgTAP test for Hastap (assertion 151).

SELECT * FROM check_test(
    has_cast( 'INT4', 'BIGINT', 'foo', 'desc' ),
    false,
    'has_cast( src, targ, func, desc ) fail',
    'desc',
    ''
);

Explanation: SQL assertion from pgTAP test suite for Hastap.


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

SELECT sum(unique1) over (order by four groups between unbounded preceding and unbounded following),
	unique1, four
FROM tenk1 WHERE unique1 < 10;

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

SELECT count(*) FROM (SELECT sum(unique1) over (order by four groups between unbounded preceding and unbounded following),
	unique1, four
FROM tenk1 WHERE unique1 < 10) AS _sub;


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

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

SELECT count(*) FROM (SELECT ARRAY[ARRAY['hello'],ARRAY['world']]) AS _sub;


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

select tcl_cdomain_arg(row('tkey', -1, 'ref2'));  -- fail

-- Test argisnull primitive
select tcl_argisnull('foo');

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


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

SELECT count(*) FROM (select '{foo{}}'::text[]) AS _sub;


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

INSERT INTO temporal_fk_mltrng2mltrng (id, valid_at, parent_id) VALUES
  ('[5,6)', datemultirange(daterange('2018-01-15', '2018-02-01')), '[2,3)');

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


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

select * from pg_input_error_info('(4,1)', 'int4range');

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

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


Question: pgTAP test for Functap (assertion 334).

SELECT * FROM check_test(
    isnt_strict( 'public', 'yay', '{}'::name[] ),
    false,
    'isnt_strict(schema, func, 0 args)',
    'Function public.yay() should not be strict',
    ''
);

Explanation: SQL assertion from pgTAP test suite for Functap.


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

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

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

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


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

SELECT to_timestamp('2011-12-18 11:38 PM', 'YYYY-MM-DD HH12:MI PM');

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

SELECT count(*) FROM (SELECT to_timestamp('2011-12-18 11:38 PM', 'YYYY-MM-DD HH12:MI PM')) AS _sub;


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


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

SELECT 'init' FROM pg_create_logical_replication_slot('regression_slot', 'test_decoding', false, true);

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


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

end$$ language plpgsql;

select f1(array[2,4]) as int, f1(array[4.5, 7.7]) as num;

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

drop function f1(x anyarray);

-- fail, can't infer type:
create function f1(x anyelement) returns anyrange as $$
begin
  return array[x + 1, x + 2];

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


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

select v #= hstore('d', '3.45') from testhstore1 v;

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


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

SELECT * FROM pg_input_error_info('[{"attributes" : [2,"a"], "dependency" : 4, "degree": 1.000}]', 'pg_dependencies');

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

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


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

SELECT octet_length(get_raw_page('xxx', 'main', 0));

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


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

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

SELECT count(*) FROM (SELECT to_char(val, 'FM9999999990999999.099999999999999') 	FROM num_data) AS _sub;


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

INSERT INTO num_exp_sub VALUES (5,1,'16397.038491');

Explanation: DML from PostgreSQL core regression test for Numeric.


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

SELECT length(to_tsvector('english', '345 qwe@efd.r '' http://www.com/ http://aew.werc.ewr/?ad=qwe&dw 1aew.werc.ewr/?ad=qwe&dw 2aew.werc.ewr http://3aew.werc.ewr/?ad=qwe&dw http://4aew.werc.ewr http://5aew.werc.ewr:8100/?  ad=qwe&dw 6aew.werc.ewr:8100/?ad=qwe&dw 7aew.werc.ewr:8100/?ad=qwe&dw=%20%32 +4.0e-10 qwe qwe qwqwe 234.435 455 5.005 teodor@stack.net teodor@123-stack.net 123_teodor@stack.net 123-teodor@stack.net qwe-wer asdf <fr>qwer jf sdjk<we hjwer <werrwe> ewr1> ewri2 <a href="qwe<qwe>">
/usr/local/fff /awdf/dwqe/4325 rewt/ewr wefjn /wqe-324/ewr gist.h gist.h.c gist.c. readline 4.2 4.2. 4.2, readline-4.2 readline-4.2. 234
<i <b> wow  < jqw <> qwerty'));

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

SELECT count(*) FROM (SELECT length(to_tsvector('english', '345 qwe@efd.r '' http://www.com/ http://aew.werc.ewr/?ad=qwe&dw 1aew.werc.ewr/?ad=qwe&dw 2aew.werc.ewr http://3aew.werc.ewr/?ad=qwe&dw http://4aew.werc.ewr http://5aew.werc.ewr:8100/?  ad=qwe&dw 6aew.werc.ewr:8100/?ad=qwe&dw 7aew.werc.ewr:8100/?ad=qwe&dw=%20%32 +4.0e-10 qwe qwe qwqwe 234.435 455 5.005 teodor@stack.net teodor@123-stack.net 123_teodor@stack.net 123-teodor@stack.net qwe-wer asdf <fr>qwer jf sdjk<we hjwer <werrwe> ewr1> ewri2 <a href="qwe<qwe>">
/usr/local/fff /awdf/dwqe/4325 rewt/ewr wefjn /wqe-324/ewr gist.h gist.h.c gist.c. readline 4.2 4.2. 4.2, readline-4.2 readline-4.2. 234
<i <b> wow  < jqw <> qwerty'))) AS _sub;


Question: PL/pgSQL test: Plpython Newline (example 1).

CREATE OR REPLACE FUNCTION newline_lf() RETURNS integer AS
E'x = 100\ny = 23\nreturn x + y\n'
LANGUAGE plpython3u;

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


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

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


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

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

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


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

Explanation: DML from PostgreSQL core regression test for Transactions.


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

select populate_record(v, hstore('c', '3.45')) from testhstore1 v;


Question: pgTAP test for Privs (assertion 29).

SELECT * FROM check_test(
    table_privs_are( 'sometab', '__nonesuch', '{}'::text[] ),
    false,
    'table_privs_are(tab, role, no privs)',
    'Role __nonesuch should be granted no privileges on table sometab' ,
    '    Role __nonesuch does not exist'
);

Explanation: SQL assertion from pgTAP test suite for Privs.


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

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


Question: pgTAP test for Ownership (assertion 16).

Explanation: SQL assertion from pgTAP test suite for Ownership.


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

\getenv libdir PG_LIBDIR
\getenv dlsuffix PG_DLSUFFIX

\set regresslib :libdir '/regress' :dlsuffix

CREATE FUNCTION test_translation()
    RETURNS void
    AS :'regresslib'
    LANGUAGE C;

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


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

select count(*) from test_multirange_gist where mr @> 'empty'::int4range;

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

SELECT count(*) FROM (select count(*) from test_multirange_gist where mr @> 'empty'::int4range) AS _sub;


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

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


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

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

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


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

CREATE INDEX brin_large_range_idx ON brin_large_range USING brin (a int4_minmax_multi_ops);

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


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

SELECT local_id, external_id,
       remote_lsn <> '0/0' AS valid_remote_lsn,
       local_lsn <> '0/0' AS valid_local_lsn
       FROM pg_replication_origin_status;

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


Question: PostgreSQL Indices: show example 28.

CREATE UNIQUE INDEX tab_x_y ON tab(x) INCLUDE (y);

Explanation: Example from PostgreSQL documentation on Indices.


Question: pgTAP test for Privs (assertion 87).


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

-- Disable tracking of statistics on a column of a hypertable.
--
-- hypertable - OID of the table to remove from
-- column_name - NAME of the column on which the stats are tracked
-- if_not_exists - If set, and the entry does not exist,
-- generate a notice instead of an error. The "disabled" field
-- is set to true if entry is deleted successfully.
CREATE OR REPLACE FUNCTION @extschema@.disable_chunk_skipping(
    hypertable              REGCLASS,
    column_name             NAME,
    if_not_exists           BOOLEAN = FALSE
) RETURNS TABLE(hypertable_id INT, column_name NAME, disabled BOOL)
AS '@MODULE_PATHNAME@', 'ts_chunk_column_stats_disable' LANGUAGE C VOLATILE;

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


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

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


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

select jsonb_path_query('[1,2,3]', '$[last ? (@.type() == "string")]', silent => true);

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

SELECT count(*) FROM (select jsonb_path_query('[1,2,3]', '$[last ? (@.type() == "string")]', silent => true)) AS _sub;


Question: pgTAP test for Functap (assertion 314).

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

Explanation: SQL assertion from pgTAP test suite for Functap.


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

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

SELECT count(*) FROM (SELECT decode('1234567890abcdef00', 'hex')) AS _sub;


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

---------------------------------------------------
-- ISMN13:
CREATE FUNCTION isnlt(ismn13, ismn13)
	RETURNS boolean
	AS 'int8lt'
	LANGUAGE 'internal'
	IMMUTABLE STRICT
	PARALLEL SAFE;

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


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

SELECT pr.snap_ts < pg_stat_get_snapshot_timestamp() as snapshot_newer
FROM prevstats AS pr;

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

SELECT count(*) FROM (SELECT pr.snap_ts < pg_stat_get_snapshot_timestamp() as snapshot_newer
FROM prevstats AS pr) AS _sub;


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

SELECT cube_subset(cube('(6,7,8),(6,7,8)'), array(SELECT 1 as a FROM generate_series(1,101)));

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


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

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


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

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


Question: pgTAP test for Hastap (assertion 129).

Explanation: SQL assertion from pgTAP test suite for Hastap.


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

select timestamp 'infinity' - timestamp '-infinity';

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

SELECT count(*) FROM (select timestamp 'infinity' - timestamp '-infinity') AS _sub;


Question: Show a SQL definition from the pglogical project (att_list, item 5).

\c :subscriber_dsn

CREATE TABLE public.basic_dml (
	id serial primary key,
	data text,
	something interval,
	subonly integer,
	subonly_def integer DEFAULT 99
);

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


Question: PL/pgSQL test: Plpython Populate (example 18).

INSERT INTO sequences (sequence, eid, product) VALUES ('ABCDEF', 4, 'gag') ;

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


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

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


Question: pgTAP test for Index (assertion 40).

SELECT * FROM check_test(
    has_index( 'public', 'sometab', 'blah', ARRAY['numb', 'name'], 'whatever' ),
    false,
    'has_index() missing',
    'whatever',
    'Index blah ON public.sometab not found'
);

Explanation: SQL assertion from pgTAP test suite for Index.


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

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


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

SELECT * FROM test_date WHERE i>'2004-10-26'::timestamptz ORDER BY i;

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


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

CREATE INDEX clstr_tst_b_c ON clstr_tst (b,c);

Explanation: DDL from PostgreSQL core regression test for Cluster.


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

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


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

CREATE INDEX CONCURRENTLY concur_index8 ON concur_heap (f1)
  WHERE predicate_stable();

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


Question: Write the DML statement from PostgreSQL regression test 'cluster' (example 14).

INSERT INTO clstr_tst (b, c) VALUES (11, 'once');

Explanation: DML from PostgreSQL core regression test for Cluster.


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

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

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


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

CREATE FUNCTION subtransaction_exit_twice() RETURNS void
AS $$
plpy.subtransaction().__enter__()
plpy.subtransaction().__exit__(None, None, None)
plpy.subtransaction().__exit__(None, None, None)
$$ LANGUAGE plpython3u;

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


Question: pgTAP test for Hastap (assertion 289).

/****************************************************************************/
-- Test hasnt_relation().

SELECT * FROM check_test(
    hasnt_relation( '__SDFSDFD__' ),
    true,
    'hasnt_relation(non-existent relation)',
    'Relation "__SDFSDFD__" should not exist',
    ''
);


Question: pgTAP test for Resultset (assertion 451).

SELECT * FROM check_test(
    results_ne( 'annames_ord', 'chave'::refcursor ),
    false,
    'results_ne(prepared, cursor)',
    '',
    ''
);

Explanation: SQL assertion from pgTAP test suite for Resultset.


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

SELECT xmlserialize(DOCUMENT '<foo>   <bar></bar>    </foo>' AS text INDENT);

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

SELECT count(*) FROM (SELECT xmlserialize(DOCUMENT '<foo>   <bar></bar>    </foo>' AS text INDENT)) AS _sub;


Question: Write the DDL statement from PostgreSQL regression test 'copydml' (example 19).

create rule qqq as on insert to copydml_test do also delete from copydml_test;

Explanation: DDL from PostgreSQL core regression test for Copydml.


Question: pgTAP test for Functap (assertion 307).

SELECT * FROM check_test(
    isnt_window( 'oww', ARRAY['int', 'text'] ),
    true,
    'isnt_window(func, arg, desc)',
    'Function oww(int, text) should not be a window function',
    ''
);

Explanation: SQL assertion from pgTAP test suite for Functap.


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

INSERT INTO test_having VALUES (7, 4, 'cccc', 'h');

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


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

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

SELECT count(*) FROM (SELECT to_date('-44-02-01','YYYY-MM-DD')) AS _sub;


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

select 'empty'::numrange >> nummultirange();

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

SELECT count(*) FROM (select 'empty'::numrange >> nummultirange()) AS _sub;


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

select count(*) > 0 as ok from (select pg_ls_waldir()) ss;

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

SELECT count(*) FROM (select count(*) > 0 as ok from (select pg_ls_waldir()) ss) AS _sub;


Question: PostgreSQL regression test 'triggers': Write the SELECT query (example 289).

select tgrelid::regclass, count(*) from pg_trigger
  where tgrelid::regclass in ('trg_clone', 'trg_clone1', 'trg_clone2',
	'trg_clone3', 'trg_clone_3_3')
  group by tgrelid::regclass order by tgrelid::regclass;

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

SELECT count(*) FROM (select tgrelid::regclass, count(*) from pg_trigger
  where tgrelid::regclass in ('trg_clone', 'trg_clone1', 'trg_clone2',
	'trg_clone3', 'trg_clone_3_3')
  group by tgrelid::regclass order by tgrelid::regclass) AS _sub;


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

select format('%2$s, %1$s', variadic array[1, 2]);

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

SELECT count(*) FROM (select format('%2$s, %1$s', variadic array[1, 2])) AS _sub;


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

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

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


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

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


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

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

SELECT count(*) FROM (SELECT interval '2' month) AS _sub;


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

create index on parted_index_col_drop (b);

Explanation: DDL from PostgreSQL core regression test for Indexing.


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

SELECT a, coalesce(b, 'foo') FROM collate_test3 ORDER BY 2;

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

SELECT count(*) FROM (SELECT a, coalesce(b, 'foo') FROM collate_test3 ORDER BY 2) AS _sub;


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

SELECT pg_get_object_address('subscription', '{one}', '{}');

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

SELECT count(*) FROM (SELECT pg_get_object_address('subscription', '{one}', '{}')) AS _sub;


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

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


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

SELECT * FROM pg_buffercache_evict_relation('temp_pg_buffercache');

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


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

INSERT INTO PKTABLE VALUES (2, 3, 4, 'test3');

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


Question: pgTAP test for Enumtap (assertion 6).

Explanation: SQL assertion from pgTAP test suite for Enumtap.


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


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

CREATE TYPE test_type2 AS (a int, b text);

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


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

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

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


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

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


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

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

SELECT count(*) FROM (SELECT * FROM box_temp WHERE f1 |&> '(49.99,49.99),(49.99,49.99)') AS _sub;


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

create trigger convslot_test_parent_update
    after update on convslot_test_parent
    referencing old table as old_rows new table as new_rows
    for each statement execute procedure convslot_trig4();

Explanation: DDL from PostgreSQL core regression test for Triggers.


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

SELECT $1 AS a \parse p1
SET plan_cache_mode TO force_generic_plan;

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


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

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


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

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

SELECT count(*) FROM (SELECT a, b, c FROM test_like_4d) AS _sub;


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

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


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

INSERT INTO pitest1_p2 (f1, f2, f3) VALUES ('2016-08-2', 'before attaching', 100);

Explanation: DML from PostgreSQL core regression test for Identity.


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

CREATE USER MAPPING FOR current_user SERVER s9;

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


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

CREATE TABLE distributors ( did integer CONSTRAINT no_null NOT NULL, name varchar(40) NOT NULL );

Explanation: PostgreSQL CREATE TABLE command.


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

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


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

SELECT split_part('abcTdefTghi', 't'::citext, 2) = 'def' AS t;

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


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

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

SELECT count(*) FROM (SELECT '2011-03-27 01:59:59 MSK'::timestamptz) AS _sub;


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

CREATE TABLE fk_partitioned_fk_3_1 PARTITION OF fk_partitioned_fk_3 FOR VALUES WITH (MODULUS 5, REMAINDER 1);

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


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

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

SELECT count(*) FROM (SELECT ' 1'::tsvector) AS _sub;


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

SELECT regr_avgx(b, a), regr_avgy(b, a) FROM aggtest;

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

SELECT count(*) FROM (SELECT regr_avgx(b, a), regr_avgy(b, a) FROM aggtest) AS _sub;


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

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

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


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

UPDATE temporal_partitioned_mltrng SET valid_at = datemultirange(daterange('2016-01-01', '2016-02-01'))
  WHERE id = '[5,6)' AND valid_at = datemultirange(daterange('2018-01-01', '2018-02-01'));

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


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

INSERT INTO macaddr8_data VALUES (19, '0800.2b01.0203.0405');

Explanation: DML from PostgreSQL core regression test for Macaddr8.


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

select v||'a', case when grouping(v||'a') = 1 then 1 else 0 end, count(*)
  from unnest(array[1,1], array['a','b']) u(i,v)
 group by rollup(i, v||'a') order by 1,3;

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

SELECT count(*) FROM (select v||'a', case when grouping(v||'a') = 1 then 1 else 0 end, count(*)
  from unnest(array[1,1], array['a','b']) u(i,v)
 group by rollup(i, v||'a') order by 1,3) AS _sub;


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

SELECT *
  FROM J1_TBL t1 (a, b, c), J2_TBL t2 (d, e);

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

SELECT count(*) FROM (SELECT *
  FROM J1_TBL t1 (a, b, c), J2_TBL t2 (d, e)) AS _sub;


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

SELECT * FROM multiout_record_as('tuple', 'three', 3, false);

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


Question: pgTAP test for Policy (assertion 51).

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

Explanation: SQL assertion from pgTAP test suite for Policy.


Question: PostgreSQL Queries: show example 22.

SELECT product_id, p.name, (sum(s.units) * (p.price - p.cost)) AS profit FROM products p LEFT JOIN sales s USING (product_id) WHERE s.date > CURRENT_DATE - INTERVAL '4 weeks' GROUP BY product_id, p.name, p.price, p.cost HAVING sum(p.price * s.units) > 5000;

Explanation: Example from PostgreSQL documentation on Queries.


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

SELECT * FROM INT8_TBL WHERE q2 > '456'::int2;

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

SELECT count(*) FROM (SELECT * FROM INT8_TBL WHERE q2 > '456'::int2) AS _sub;


Question: pgTAP test for Ownership (assertion 77).

SELECT * FROM check_test(
    composite_owner_is('public', '__not__sometype', current_user, 'mumble'),
	false,
    'composite_owner_is(sch, non-composite, user)',
    'mumble',
    '    Composite type public.__not__sometype does not exist'
);

Explanation: SQL assertion from pgTAP test suite for Ownership.


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

INSERT INTO num_exp_div VALUES (9,0,'NaN');

Explanation: DML from PostgreSQL core regression test for Numeric.


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

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


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

SELECT timestamptz '-infinity infinity';

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

SELECT count(*) FROM (SELECT timestamptz '-infinity infinity') AS _sub;


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

SELECT crypt('a very much longer text to encrypt.  This one even stretches over more'
                 'than one line.', '$6$rounds=1400$anotherlongsaltstring')
           = '$6$rounds=1400$anotherlongsalts$POfYwTEok97VWcjxIiSOjiykti.o/pQs.wPvMxQ6Fm7I6IoYN3CmLs66x9t0oSwbtEW7o7UmJEiDwGqd8p4ur1' AS result;

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


Question: pgTAP test for Coltap (assertion 86).

SELECT * FROM check_test(
    col_default_is( 'public', 'sometab', 'myat', 'now()', 'desc'::text ),
    true,
    'col_default_is( schema, tab, col, expression, desc )',
    'desc',
    ''
);

Explanation: SQL assertion from pgTAP test suite for Coltap.


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

CREATE TABLE ctlt10 (LIKE ctlseq1);  -- fail

CREATE VIEW ctlv1 AS SELECT * FROM ctlt4;

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


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

CREATE TABLE prt2_m_p2 PARTITION OF prt2_m FOR VALUES FROM (250, 250) TO (500, 500);

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


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

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

SELECT count(*) FROM (select * from boolpart where a = false) AS _sub;


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

SELECT hmac(
'Hi There',
'\x0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b'::bytea,
'sha1');


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

CREATE INDEX tbspace_reindex_part_index_0 ON ONLY tbspace_reindex_part_0 (c1);

Explanation: DDL from PostgreSQL core regression test for Tablespace.


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

SELECT o.* FROM OID_TBL o WHERE o.f1 > '1234';

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

SELECT count(*) FROM (SELECT o.* FROM OID_TBL o WHERE o.f1 > '1234') AS _sub;


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

-- create function to filter unstable results of EXPLAIN
CREATE FUNCTION explain_filter(text) RETURNS setof text
LANGUAGE plpgsql AS
$$
declare
    ln text;
begin
    for ln in execute $1
    loop
        -- Remove the path portion of foreign file names
        ln := regexp_replace(ln, 'Foreign File: .*/([a-z.]+)$', 'Foreign File: .../\1');
        return next ln;
    end loop;
end;
$$;

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


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

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

SELECT count(*) FROM (select ('[1, "2", null]'::jsonb)[1.0]) AS _sub;


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

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

SELECT count(*) FROM (select jsonb_path_query('{"g": [{"x": 2}, {"y": 3}]}', 'lax $.g ? (exists (@.x))')) AS _sub;


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

CREATE TABLE gtest_err_7b (a int PRIMARY KEY, b int GENERATED ALWAYS AS (row_number() OVER (ORDER BY a)) VIRTUAL);

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


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

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


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

CREATE TABLE unbounded_range_part PARTITION OF range_parted4 FOR VALUES FROM (MINVALUE, MINVALUE, MINVALUE) TO (MAXVALUE, MAXVALUE, MAXVALUE);

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


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

insert into inserttest (f3.if2[1], f3.if2[2]) select 'bear', 'beer';

Explanation: DML from PostgreSQL core regression test for Insert.


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

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

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


Question: Write the DML statement from PostgreSQL regression test 'rangetypes' (example 140).

INSERT INTO textrange_test VALUES('["a",]');

Explanation: DML from PostgreSQL core regression test for Rangetypes.


Question: Write the DML statement from PostgreSQL regression test 'create_type' (example 57).

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


Question: Write the DML statement from PostgreSQL regression test 'collate.utf8' (example 28).

INSERT INTO test_pg_unicode_fast VALUES
  ('abc DEF 123abc'),
  ('ábc sßs ßss DÉF'),
  ('ǄxxǄ ǆxxǅ ǅxxǆ'),
  (U&'Λλ 1a \FF11a'),
  ('ȺȺȺ'),
  ('ⱥⱥⱥ'),
  ('ⱥȺ');

Explanation: DML from PostgreSQL core regression test for Collate.Utf8.


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

INSERT INTO PG_LSN_TBL VALUES ('FFFFFFFF/FFFFFFFF');

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


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

/*
 * 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() RETURNS void
    LANGUAGE plpgsql SECURITY DEFINER
    AS $$
DECLARE

v_adv_lock                      boolean;
v_create_count                  int := 0;
v_current_partition_timestamp   timestamp;
v_datetime_string               text;
v_drop_count                    int := 0;
v_job_id                        bigint;
v_jobmon_schema                 text;
v_last_partition_timestamp      timestamp;
v_old_search_path               text;
v_premade_count                 int;
v_quarter                       text;
v_step_id                       bigint;
v_row                           record;
v_time_position                 int;
v_year                          text;

BEGIN

v_adv_lock := pg_try_advisory_lock(hashtext('pg_partman run_maintenance'));
IF v_adv_lock = 'false' THEN
    RAISE NOTICE 'Partman maintenance already running.';
    RETURN;
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 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::interval
    , control
    , premake
    , datetime_string
    , last_partition
    , undo_in_progress
FROM @extschema@.part_config WHERE type = 'time-static' OR type = 'time-dynamic'
LOOP

    CONTINUE WHEN v_row.undo_in_progress;

    CASE
        WHEN v_row.part_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 = '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 = '1 hour' THEN
            v_current_partition_timestamp := date_trunc('hour', CURRENT_TIMESTAMP);
         WHEN v_row.part_interval = '1 day' THEN
            v_current_partition_timestamp := date_trunc('day', CURRENT_TIMESTAMP);
        WHEN v_row.part_interval = '1 week' THEN
            v_current_partition_timestamp := date_trunc('week', CURRENT_TIMESTAMP);
        WHEN v_row.part_interval = '1 month' THEN
            v_current_partition_timestamp := date_trunc('month', CURRENT_TIMESTAMP);
        WHEN v_row.part_interval = '3 months' THEN
            v_current_partition_timestamp := date_trunc('quarter', CURRENT_TIMESTAMP);
        WHEN v_row.part_interval = '1 year' THEN
            v_current_partition_timestamp := date_trunc('year', CURRENT_TIMESTAMP);
    END CASE;

    -- Get position of last occurance of '_p' in child partition name
    v_time_position := (length(v_row.last_partition) - position('p_' in reverse(v_row.last_partition))) + 2;
    IF v_row.part_interval != '3 months' 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));
    -- 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
        EXECUTE 'SELECT @extschema@.create_next_time_partition('||quote_literal(v_row.parent_table)||')';
        v_create_count := v_create_count + 1;
        IF v_row.type = 'time-static' THEN
            EXECUTE 'SELECT @extschema@.create_time_function('||quote_literal(v_row.parent_table)||')';
        END IF;
        v_last_partition_timestamp := v_last_partition_timestamp + v_row.part_interval;
        v_premade_count = round(EXTRACT('epoch' FROM age(v_last_partition_timestamp, v_current_partition_timestamp)) / EXTRACT('epoch' FROM v_row.part_interval::interval));
    END LOOP;

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')
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.');
    PERFORM close_job(v_job_id);
    EXECUTE 'SELECT set_config(''search_path'','''||v_old_search_path||''',''false'')';
END IF;

PERFORM pg_advisory_unlock(hashtext('pg_partman run_maintenance'));

EXCEPTION
    WHEN QUERY_CANCELED THEN
        PERFORM pg_advisory_unlock(hashtext('pg_partman run_maintenance'));
        RAISE EXCEPTION '%', SQLERRM;
    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 RUN MAINTENANCE');
                v_step_id := add_step(v_job_id, 'EXCEPTION before job logging started');
            END IF;
            IF v_step_id IS NULL THEN
                v_step_id := add_step(v_job_id, 'EXCEPTION before first step logged');
            END IF;
            PERFORM update_step(v_step_id, 'CRITICAL', 'ERROR: '||coalesce(SQLERRM,'unknown'));
            PERFORM fail_job(v_job_id);
            EXECUTE 'SELECT set_config(''search_path'','''||v_old_search_path||''',''false'')';
        END IF;
        PERFORM pg_advisory_unlock(hashtext('pg_partman run_maintenance'));
        RAISE EXCEPTION '%', SQLERRM;
END
$$;

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


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

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

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


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

CREATE OR REPLACE FUNCTION foo_ordered() RETURNS orderedfootype AS $$
    return {x => 5, y => 4};
$$ LANGUAGE plperl;

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


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


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

INSERT INTO fk_notpartitioned_fk VALUES(100,100), (1000,1000);

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


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

CREATE TABLE concur_reindex_tab2 (c1 int REFERENCES concur_reindex_tab);

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


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

INSERT INTO t1 (SELECT x, md5(x::text) FROM generate_series(1,100) x);

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


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

select * from nestjsonb where j @> '{"a":[[{"x":2}]]}'::jsonb;

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

SELECT count(*) FROM (select * from nestjsonb where j @> '{"a":[[{"x":2}]]}'::jsonb) AS _sub;


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

CREATE OR REPLACE FUNCTION _cexists ( NAME, NAME )
RETURNS BOOLEAN AS $$
    SELECT EXISTS(
        SELECT true
          FROM pg_catalog.pg_class c
          JOIN pg_catalog.pg_attribute a ON c.oid = a.attrelid
         WHERE c.relname = $1
           AND pg_catalog.pg_table_is_visible(c.oid)
           AND a.attnum > 0
           AND NOT a.attisdropped
           AND a.attname = $2
    );
$$ LANGUAGE SQL;

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


Question: pgTAP test for Ownership (assertion 113).

SELECT * FROM check_test(
    index_owner_is('sometab', 'idx_hey', '__no-one', 'mumble'),
	false,
    'index_owner_is(table, index, non-user)',
    'mumble',
    '        have: ' || current_user || '
        want: __no-one'
);

Explanation: SQL assertion from pgTAP test suite for Ownership.


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

SELECT count(*) FROM inettmp WHERE a >= '89.225.196.191'::inet;

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


Question: Write the DML statement from PostgreSQL regression test 'portals' (example 210).

Explanation: DML from PostgreSQL core regression test for Portals.


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

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

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

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


Question: pgTAP test for Resultset (assertion 21).

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

Explanation: SQL assertion from pgTAP test suite for Resultset.


Question: PL/pgSQL test: Plpython Populate (example 10).

INSERT INTO entry (accession, txid) VALUES ('A00003', '1') ;

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


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

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

SELECT count(*) FROM (SELECT '-10e400'::float8) AS _sub;


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

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

SELECT count(*) FROM (SELECT c, d FROM forcetest WHERE a = 2) AS _sub;


Question: pgTAP test for Fktap (assertion 19).

SELECT * FROM check_test(
    has_fk( 'fk' ),
    true,
    'has_fk( table )',
    'Table fk should have a foreign key constraint'
);

Explanation: SQL assertion from pgTAP test suite for Fktap.


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

select textmultirange(textrange('a', 'c'), textrange('f', 'g'));

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

SELECT count(*) FROM (select textmultirange(textrange('a', 'c'), textrange('f', 'g'))) AS _sub;


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

INSERT INTO num_result SELECT id, 0, POWER(numeric '10', LN(ABS(round(val,200))))
    FROM num_data
    WHERE val != '0.0';

Explanation: DML from PostgreSQL core regression test for Numeric.


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


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

SELECT to_timestamp('2011-12-18 11:38 JUNK', 'YYYY-MM-DD HH12:MI TZ');  -- error
SELECT to_timestamp('2011-12-18 11:38 ...', 'YYYY-MM-DD HH12:MI TZ');  -- error

SELECT to_timestamp('2011-12-18 11:38 -05', 'YYYY-MM-DD HH12:MI OF');

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

SELECT count(*) FROM (SELECT to_timestamp('2011-12-18 11:38 JUNK', 'YYYY-MM-DD HH12:MI TZ');  -- error
SELECT to_timestamp('2011-12-18 11:38 ...', 'YYYY-MM-DD HH12:MI TZ');  -- error

SELECT to_timestamp('2011-12-18 11:38 -05', 'YYYY-MM-DD HH12:MI OF')) AS _sub;


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

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

SELECT count(*) FROM (SELECT bool 'test' AS error) AS _sub;


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

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

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


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

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

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

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


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

SELECT 'bıt' ILIKE 'BIT' COLLATE "en_US" AS "false";

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

SELECT count(*) FROM (SELECT 'bıt' ILIKE 'BIT' COLLATE "en_US" AS "false") AS _sub;


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

$$ language plpgsql immutable;

select case_test(1);
select case_test(2);
select case_test(12);
select case_test(13);

-- test line comment between WHEN and THEN
create or replace function case_comment(int) returns text as $$
begin
  case $1
    when 1 -- comment before THEN
      then return 'one';

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


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

CREATE TRIGGER show_trigger_data_trig_before
BEFORE INSERT OR UPDATE OR DELETE ON trigger_test
FOR EACH ROW EXECUTE PROCEDURE trigger_data(23,'skidoo');

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


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

SELECT * FROM tststats.priv_test_tbl WHERE a <<< 0 AND b <<< 0; -- Should not leak
SELECT * FROM tststats.priv_test_tbl WHERE a <<< 0 OR b <<< 0; -- Should not leak
SELECT * FROM tststats.priv_test_tbl t
 WHERE a <<< 0 AND (b <<< 0 OR t.* <<< (1, 1) IS NOT NULL); -- Should not leak
DELETE FROM tststats.priv_test_tbl WHERE a <<< 0 AND b <<< 0; -- Should not leak

-- Create plain inheritance parent table with no access permissions
RESET SESSION AUTHORIZATION;

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

SELECT count(*) FROM (SELECT * FROM tststats.priv_test_tbl WHERE a <<< 0 AND b <<< 0; -- Should not leak
SELECT * FROM tststats.priv_test_tbl WHERE a <<< 0 OR b <<< 0; -- Should not leak
SELECT * FROM tststats.priv_test_tbl t
 WHERE a <<< 0 AND (b <<< 0 OR t.* <<< (1, 1) IS NOT NULL); -- Should not leak
DELETE FROM tststats.priv_test_tbl WHERE a <<< 0 AND b <<< 0; -- Should not leak

-- Create plain inheritance parent table with no access permissions
RESET SESSION AUTHORIZATION) AS _sub;


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

SELECT num_nulls(1, 2, NULL::text, NULL::point, '', int8 '9', 1.0 / NULL);

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

SELECT count(*) FROM (SELECT num_nulls(1, 2, NULL::text, NULL::point, '', int8 '9', 1.0 / NULL)) AS _sub;


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


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

--
-- brin_metapage_info()
--
CREATE FUNCTION brin_metapage_info(IN page bytea, OUT magic text,
	OUT version integer, OUT pagesperrange integer, OUT lastrevmappage bigint)
AS 'MODULE_PATHNAME', 'brin_metapage_info'
LANGUAGE C STRICT PARALLEL SAFE;


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

select * from (x left join y on (x1 = y1)) left join x xx(xx1,xx2)
on (x1 = xx1 and y2 is not null);

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

SELECT count(*) FROM (select * from (x left join y on (x1 = y1)) left join x xx(xx1,xx2)
on (x1 = xx1 and y2 is not null)) AS _sub;


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

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

SELECT count(*) FROM (SELECT pg_size_bytes('++123 kB')) AS _sub;


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

CREATE PUBLICATION testpub_xxx WITH (publish_generated_columns = foo);

Explanation: DDL from PostgreSQL core regression test for Publication.


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

-- has_opclass( name, description )
CREATE OR REPLACE FUNCTION has_opclass( NAME, TEXT )
RETURNS TEXT AS $$
    SELECT ok( _opc_exists( $1 ), $2)
$$ LANGUAGE SQL;

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


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

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

SELECT count(*) FROM (select '1?(2>3)'::jsonpath) AS _sub;


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

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

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


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

---------------------------------------------------
-- ISMN:
CREATE FUNCTION btismncmp(ismn, ismn)
	RETURNS int4
	AS 'btint8cmp'
	LANGUAGE 'internal'
	IMMUTABLE STRICT
	PARALLEL SAFE;


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

UPDATE range_parted set d = d - 10 WHERE d > 10;

Explanation: DML from PostgreSQL core regression test for Update.


Question: PostgreSQL regression test 'without_overlaps': Write the SELECT query (example 234).

SELECT * FROM tp2 ORDER BY id, valid_at;

Explanation: Regression test for Without Overlaps in PostgreSQL core test suite.

SELECT count(*) FROM (SELECT * FROM tp2 ORDER BY id, valid_at) AS _sub;


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

/*
 * Function to ensure a column is dropped in all child tables, no matter when it was created
 */
CREATE FUNCTION drop_partition_column(p_parent_table text, p_column text) RETURNS void
    LANGUAGE plpgsql SECURITY DEFINER
    AS $$
DECLARE

v_child_oid         oid;
v_parent_oid        oid;
v_parent_schema     text;
v_parent_tablename  text;
v_row               record;

BEGIN

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

IF v_parent_oid IS NULL THEN
    RAISE EXCEPTION 'Given parent table does not exist: %', p_parent_table;
END IF;

EXECUTE format('ALTER TABLE %I.%I DROP COLUMN IF EXISTS %I', v_parent_schema, v_parent_tablename, p_column);

FOR v_row IN
    SELECT n.nspname AS child_schema, c.relname AS child_table
    FROM pg_catalog.pg_inherits h
    JOIN pg_catalog.pg_class c ON h.inhrelid = c.oid
    JOIN pg_catalog.pg_namespace n ON c.relnamespace = n.oid
    WHERE inhparent = v_parent_oid
LOOP

    EXECUTE format('ALTER TABLE %I.%I DROP COLUMN IF EXISTS %I', v_row.child_schema, v_row.child_table, p_column);

END LOOP;

END
$$;

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


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

SELECT * FROM test_table_record_as('list', 'three', 3, false);

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


Question: pgTAP test for Aretap (assertion 125).

SELECT * FROM check_test(
    rules_are( 'public', 'fou', ARRAY['ins_me', 'del_me'] ),
    false,
    'rules_are(schema, table, rules) + extra & missing',
    'Relation public.fou should have the correct rules',
    '    Extra rules:
        upd_me
    Missing rules:
        del_me'
);

Explanation: SQL assertion from pgTAP test suite for Aretap.


Question: pgTAP test for Functap (assertion 270).

-- is_window ( NAME, NAME, NAME[] )
-- isnt_window ( NAME, NAME, NAME[] )
SELECT * FROM check_test(
    is_window( 'pg_catalog', 'ntile', ARRAY['int'] ),
    true,
    'is_window(schema, win, arg)',
    'Function pg_catalog.ntile(int) should be a window function',
    ''
);

Explanation: SQL assertion from pgTAP test suite for Functap.


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

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

SELECT count(*) FROM (SELECT EXTRACT(HOUR        FROM TIME '2020-05-26 13:30:25.575401')) AS _sub;


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

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


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

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

SELECT count(*) FROM (SELECT pg_input_is_valid('1234.567', 'numeric(7,4)')) AS _sub;


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

SELECT to_timestamp('  20050302', 'YYYYMMDD');

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

SELECT count(*) FROM (SELECT to_timestamp('  20050302', 'YYYYMMDD')) AS _sub;