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

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

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

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

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

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

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

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

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

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

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

    END IF;

END LOOP;
-- End index creation

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

RETURN true;

END
$$;


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

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

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


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

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

Explanation: DML from PostgreSQL core regression test for Numeric.


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

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

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


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

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

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


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

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

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


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

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

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


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

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

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

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


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

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

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

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


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

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

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

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


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

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

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

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


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

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

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


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

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

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

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


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

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


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

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


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

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

Explanation: DML from PostgreSQL core regression test for Rowtypes.


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

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

Explanation: DDL from PostgreSQL core regression test for Publication.


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

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

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

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


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

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

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

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


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

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

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


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

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

Explanation: DML from PostgreSQL core regression test for Arrays.


Question: pgTAP test for Functap (assertion 266).

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

Explanation: SQL assertion from pgTAP test suite for Functap.


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

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


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

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

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

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


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

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

DROP COLLATION mycoll1;

Explanation: DDL from PostgreSQL core regression test for Collate.


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

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

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

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


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

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

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


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

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

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


Question: PostgreSQL Textsearch: show example 62.

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

Explanation: Example from PostgreSQL documentation on Textsearch.


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

Explanation: PostgreSQL DROP ROLE command.


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

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

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


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

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

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


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

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

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

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


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

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

Explanation: DML from PostgreSQL core regression test for Numeric.


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

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

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

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


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

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

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


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

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

Explanation: DDL from PostgreSQL core regression test for Indexing.


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

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

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


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

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


Question: PostgreSQL Rowtypes: show example 18.

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

Explanation: Example from PostgreSQL documentation on Rowtypes.


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

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

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


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

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

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


Question: pgTAP test for Resultset (assertion 73).

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

Explanation: SQL assertion from pgTAP test suite for Resultset.


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

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


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

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

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

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


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

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

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


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

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

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

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


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

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

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


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

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

Explanation: DML from PostgreSQL core regression test for Oid8.


Question: pgTAP test for Enumtap (assertion 25).

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

Explanation: SQL assertion from pgTAP test suite for Enumtap.


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

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

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

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


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

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

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


Question: pgTAP test for Trigger (assertion 30).

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

Explanation: SQL assertion from pgTAP test suite for Trigger.


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

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

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


Question: pgTAP test for Resultset (assertion 331).


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

CREATE TABLE current_check_2 () INHERITS (current_check);

Explanation: DDL from PostgreSQL core regression test for Portals.


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

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

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


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

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

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

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


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

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

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


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

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

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

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


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

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

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


Question: pgTAP test for Resultset (assertion 272).

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


Question: pgTAP test for Resultset (assertion 326).

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


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

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

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

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


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

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

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


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

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


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

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


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

Explanation: DML from PostgreSQL core regression test for Publication.


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

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

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


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

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

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

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


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

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

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


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

SELECT * FROM sj j1, sj j2 WHERE j1.b = j2.b AND j1.a = 2 AND j2.a = 3;

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

SELECT count(*) FROM (SELECT * FROM sj j1, sj j2 WHERE j1.b = j2.b AND j1.a = 2 AND j2.a = 3) AS _sub;


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

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

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

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


Question: pgTAP test for Functap (assertion 158).

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

Explanation: SQL assertion from pgTAP test suite for Functap.


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

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

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

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


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

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

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


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

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

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


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

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

Explanation: DML from PostgreSQL core regression test for Update.


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

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

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

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


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

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


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

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

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

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


Question: pgTAP test for Hastap (assertion 62).

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

Explanation: SQL assertion from pgTAP test suite for Hastap.


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

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


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

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

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


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

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

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


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

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

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


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

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

Explanation: DDL from PostgreSQL core regression test for Identity.


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

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

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


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

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

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

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


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

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

Explanation: DML from PostgreSQL core regression test for Numeric.


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

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

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


Question: pgTAP test for Pktap (assertion 18).

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

Explanation: SQL assertion from pgTAP test suite for Pktap.


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

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

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


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

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

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


Question: pgTAP test for Functap (assertion 99).

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

Explanation: SQL assertion from pgTAP test suite for Functap.


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

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

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

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

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

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

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

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

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

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

   END IF;

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

$$;

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


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

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

Explanation: DDL from PostgreSQL core regression test for Publication.


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

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

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


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

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

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


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

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

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


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

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

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

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


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

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

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


Question: pgTAP test for Aretap (assertion 90).

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

Explanation: SQL assertion from pgTAP test suite for Aretap.


Question: pgTAP test for Functap (assertion 138).

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


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

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

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


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.