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

-- Should fail. Procedure should be mandatorily specified
CREATE OPERATOR #@%# (
   rightarg = int8
);

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


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

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

SELECT count(*) FROM (select interval 'PT2562047788:00:54.775807') AS _sub;


Question: Write the DDL statement from PostgreSQL regression test 'create_role' (example 46).

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


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

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


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

CREATE FUNCTION isnne(issn, issn13)
	RETURNS boolean
	AS 'int8ne'
	LANGUAGE 'internal'
	IMMUTABLE STRICT
	PARALLEL SAFE;

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


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

CREATE OR REPLACE VIEW cake.cake_summary AS
SELECT brand.pk_brand_id,
       brand.brand_name,
       (SELECT json_agg(row_to_json(cj.*)) AS json_agg
        FROM (SELECT flavor.pk_flavor,
                     flavor.flv_name,
                     flavor.flv_color
              FROM cake.flavor
              WHERE (brand.pk_brand_id = flavor.fk_flv_to_bd)) cj)::json AS flavor_data,
       cake.zdb_cake_bd_to_flavor(brand.*)                               AS zdb
FROM cake.brand;

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


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

SELECT sum(unique1) over (w range between unbounded preceding and current row exclude current row),
	unique1, four
FROM tenk1 WHERE unique1 < 10 WINDOW w AS (order by four);

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

SELECT count(*) FROM (SELECT sum(unique1) over (w range between unbounded preceding and current row exclude current row),
	unique1, four
FROM tenk1 WHERE unique1 < 10 WINDOW w AS (order by four)) AS _sub;


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

CREATE TABLE self_referencing_table(id int, ref_id int, PRIMARY KEY (id, ref_id));

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


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

create function int8alias2out(int8alias2) returns cstring
  strict immutable language internal as 'int8out';

Explanation: DDL from PostgreSQL core regression test for Equivclass.


Question: Show a SQL definition from the pg_partman project (pg_partman--1.8.0--1.8.1, item 1).

/*
 * Apply constraints managed by partman extension
 */
CREATE OR REPLACE FUNCTION apply_constraints(p_parent_table text, p_child_table text DEFAULT NULL, p_analyze boolean DEFAULT FALSE, p_debug boolean DEFAULT FALSE) RETURNS void
    LANGUAGE plpgsql
    AS $$
DECLARE

v_child_table                   text;
v_child_tablename               text;
v_col                           text;
v_constraint_cols               text[];
v_constraint_col_type           text;
v_constraint_name               text;
v_datetime_string               text;
v_existing_constraint_name      text;
v_job_id                        bigint;
v_jobmon                        boolean;
v_jobmon_schema                 text;
v_last_partition                text;
v_last_partition_id             int;
v_last_partition_timestamp      timestamp;
v_constraint_values             record;
v_old_search_path               text;
v_parent_schema                 text;
v_parent_tablename              text;
v_part_interval                 text;
v_partition_suffix              text;
v_premake                       int;
v_sql                           text;
v_step_id                       bigint;
v_suffix_position               int;
v_type                          text;

BEGIN

SELECT type
    , part_interval
    , premake
    , datetime_string
    , constraint_cols
    , jobmon
INTO v_type
    , v_part_interval
    , v_premake
    , v_datetime_string
    , v_constraint_cols
    , v_jobmon
FROM @extschema@.part_config
WHERE parent_table = p_parent_table;

IF v_constraint_cols IS NULL THEN
    IF p_debug THEN
        RAISE NOTICE 'Given parent table (%) not set up for constraint management (constraint_cols is NULL)', p_parent_table;
    END IF;
    -- Returns silently to allow this function to be simply called by maintenance processes without having to check if config options are set.
    RETURN;
END IF;

SELECT show_partitions INTO v_last_partition FROM @extschema@.show_partitions(p_parent_table, 'DESC') LIMIT 1;

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

IF v_jobmon_schema IS NOT NULL THEN
    v_job_id := add_job('PARTMAN CREATE CONSTRAINT: '||p_parent_table);
END IF;

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

-- If p_child_table is null, figure out the partition that is the one right before the premake value backwards.
IF p_child_table IS NULL THEN

    IF v_jobmon_schema IS NOT NULL THEN
        v_step_id := add_step(v_job_id, 'Automatically determining most recent child on which to apply constraints');
    END IF;

    v_suffix_position := (length(v_last_partition) - position('p_' in reverse(v_last_partition))) + 2;

    IF v_type IN ('time-static', 'time-dynamic') THEN
        v_last_partition_timestamp := to_timestamp(substring(v_last_partition from v_suffix_position), v_datetime_string);
        v_partition_suffix := to_char(v_last_partition_timestamp - (v_part_interval::interval * ((v_premake * 2)+1) ), v_datetime_string);
    ELSIF v_type IN ('id-static', 'id-dynamic') THEN
        v_last_partition_id := substring(v_last_partition from v_suffix_position)::int;
        v_partition_suffix := (v_last_partition_id - (v_part_interval::int * ((v_premake * 2)+1) ))::text;
    END IF;

    v_child_table := @extschema@.check_name_length(v_parent_tablename, v_parent_schema, v_partition_suffix, TRUE);

    IF v_jobmon_schema IS NOT NULL THEN
        PERFORM update_step(v_step_id, 'OK', 'Target child table: '||v_child_table);
    END IF;
ELSE
    v_child_table := p_child_table;
END IF;

IF v_jobmon_schema IS NOT NULL THEN
    v_step_id := add_step(v_job_id, 'Checking if target child table exists');
END IF;

SELECT tablename INTO v_child_tablename FROM pg_catalog.pg_tables WHERE schemaname ||'.'|| tablename = v_child_table;
IF v_child_tablename IS NULL THEN
    IF v_jobmon_schema IS NOT NULL THEN
        PERFORM update_step(v_step_id, 'NOTICE', 'Target child table ('||v_child_table||') does not exist. Skipping constraint creation.');
        PERFORM close_job(v_job_id);
        EXECUTE 'SELECT set_config(''search_path'','''||v_old_search_path||''',''false'')';
    END IF;
    IF p_debug THEN
        RAISE NOTICE 'Target child table (%) does not exist. Skipping constraint creation.', v_child_table;
    END IF;
    RETURN;
ELSE
    IF v_jobmon_schema IS NOT NULL THEN
        PERFORM update_step(v_step_id, 'OK', 'Done');
    END IF;
END IF;

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

    IF v_jobmon_schema IS NOT NULL THEN
        v_step_id := add_step(v_job_id, 'Applying new constraint on column: '||v_col);
    END IF;

    IF v_existing_constraint_name IS NOT NULL THEN
        IF v_jobmon_schema IS NOT NULL THEN
            PERFORM update_step(v_step_id, 'NOTICE', 'Partman managed constraint already exists on this table ('||v_child_table||') and column ('||v_col||'). Skipping creation.');
        END IF;
        RAISE WARNING 'Partman managed constraint already exists on this table (%) and column (%). Skipping creation.', v_child_table, v_col ;
        CONTINUE;
    END IF;

    -- Ensure column name gets put on end of constraint name to help avoid naming conflicts
    v_constraint_name := @extschema@.check_name_length('partmanconstr_'||v_child_tablename, p_suffix := '_'||v_col);

    EXECUTE 'SELECT min('||v_col||')::text AS min, max('||v_col||')::text AS max FROM '||v_child_table INTO v_constraint_values;

    IF v_constraint_values IS NOT NULL THEN
        v_sql := concat('ALTER TABLE ', v_child_table, ' ADD CONSTRAINT ', v_constraint_name
            , ' CHECK (', v_col, ' >= ', quote_literal(v_constraint_values.min), ' AND '
            , v_col, ' <= ', quote_literal(v_constraint_values.max), ')' );
        IF p_debug THEN
            RAISE NOTICE 'Constraint creation query: %', v_sql;
        END IF;
        EXECUTE v_sql;

        IF v_jobmon_schema IS NOT NULL THEN
            PERFORM update_step(v_step_id, 'OK', 'New constraint created: '||v_sql);
        END IF;
    ELSE
        IF p_debug THEN
            RAISE NOTICE 'Given column (%) contains all NULLs. No constraint created', v_col;
        END IF;
        IF v_jobmon_schema IS NOT NULL THEN
            PERFORM update_step(v_step_id, 'NOTICE', 'Given column ('||v_col||') contains all NULLs. No constraint created');
        END IF;
    END IF;

END LOOP;

IF p_analyze THEN
    IF v_jobmon_schema IS NOT NULL THEN
        v_step_id := add_step(v_job_id, 'Running analyze on partition set: '||p_parent_table);
    END IF;
    IF p_debug THEN
        RAISE NOTICE 'Running analyze on partition set: %', p_parent_table;
    END IF;

    EXECUTE 'ANALYZE '||p_parent_table;

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

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

EXCEPTION
    WHEN OTHERS THEN
        IF v_jobmon_schema IS NOT NULL THEN
            IF v_job_id IS NULL THEN
                EXECUTE 'SELECT '||v_jobmon_schema||'.add_job(''PARTMAN CREATE CONSTRAINT: '||p_parent_table||''')' INTO v_job_id;
                EXECUTE 'SELECT '||v_jobmon_schema||'.add_step('||v_job_id||', ''EXCEPTION before job logging started'')' INTO v_step_id;
            ELSIF v_step_id IS NULL THEN
                EXECUTE 'SELECT '||v_jobmon_schema||'.add_step('||v_job_id||', ''EXCEPTION before first step logged'')' INTO v_step_id;
            END IF;
            EXECUTE 'SELECT '||v_jobmon_schema||'.update_step('||v_step_id||', ''CRITICAL'', ''ERROR: '||coalesce(SQLERRM,'unknown')||''')';
            EXECUTE 'SELECT '||v_jobmon_schema||'.fail_job('||v_job_id||')';
        END IF;
        RAISE EXCEPTION '%', SQLERRM;
END
$$;

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


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

Explanation: DML from PostgreSQL core regression test for Truncate.


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

CREATE OR REPLACE TEMP VIEW v_window AS
	SELECT i, sum(i) over (order by i groups between 1 preceding and 1 following) as sum_rows FROM generate_series(1, 10) i;

Explanation: DDL from PostgreSQL core regression test for Window.


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

SELECT normalize(U&'\0061\0308\24D1c', NFC) = U&'\00E4\24D1c' COLLATE "C" AS test_nfc;

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

SELECT count(*) FROM (SELECT normalize(U&'\0061\0308\24D1c', NFC) = U&'\00E4\24D1c' COLLATE "C" AS test_nfc) AS _sub;


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

SELECT count(*) FROM int4tmp WHERE a >= 237::int4;

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


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

create unique index ec1_expr1 on ec1((ff + 1));


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

create domain dcomptype as comptype check ((value).cf1 > 0);

Explanation: DDL from PostgreSQL core regression test for Domain.


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

CREATE TABLE FKTABLE ( ftest1 int, ftest2 int, ftest3 int, ftest4 int,  CONSTRAINT constrname3
			FOREIGN KEY(ftest1, ftest2, ftest3) REFERENCES PKTABLE (ptest1, ptest2, ptest3));

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


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

CREATE SCHEMA regress_schema_1 AUTHORIZATION CURRENT_ROLE
  CREATE VIEW schema_not_existing.view AS SELECT 1;

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


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

SELECT relname, spcname FROM pg_catalog.pg_tablespace t, pg_catalog.pg_class c
    where c.reltablespace = t.oid AND c.relname = 'foo_idx';

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

SELECT count(*) FROM (SELECT relname, spcname FROM pg_catalog.pg_tablespace t, pg_catalog.pg_class c
    where c.reltablespace = t.oid AND c.relname = 'foo_idx') AS _sub;


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

select relname from pg_class where relname ~ '^temp_parted_oncommit_test';

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

SELECT count(*) FROM (select relname from pg_class where relname ~ '^temp_parted_oncommit_test') AS _sub;


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

-- Should expect an error when creating a hypertable from a partition
\set ON_ERROR_STOP 0
CREATE TABLE partitioned_ht_create(time timestamptz, temp float, device int) PARTITION BY RANGE (time);

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


Question: PostgreSQL Ddl: show example 81.

REVOKE CREATE ON SCHEMA public FROM PUBLIC;

Explanation: Example from PostgreSQL documentation on Ddl.


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

-- There is a syntactic ambiguity in the SQL standard.  Since
-- UNBOUNDED is a non-reserved word, it could be the name of a
-- function parameter and be used as an expression.  There is a
-- grammar hack to resolve such cases as the keyword.  The following
-- tests record this behavior.

CREATE FUNCTION unbounded_syntax_test1a(x int) RETURNS TABLE (a int, b int, c int)
LANGUAGE SQL
BEGIN ATOMIC
  SELECT sum(unique1) over (rows between x preceding and x following),
         unique1, four
  FROM tenk1 WHERE unique1 < 10;

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


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

Explanation: DML from PostgreSQL core regression test for Numeric.


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

SELECT reltuples, relhassubclass
  FROM pg_class WHERE oid = 'past_inh_parent'::regclass;

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

SELECT count(*) FROM (SELECT reltuples, relhassubclass
  FROM pg_class WHERE oid = 'past_inh_parent'::regclass) AS _sub;


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

INSERT INTO sequences (sequence, eid, product) VALUES ('ABCDEF', 5, 'env') ;

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


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

CREATE OR REPLACE FUNCTION _timescaledb_internal.attach_osm_table_chunk(hypertable regclass, chunk regclass) RETURNS boolean LANGUAGE PLPGSQL AS $$
BEGIN
  IF current_setting('timescaledb.enable_deprecation_warnings', true)::bool THEN
    RAISE WARNING 'function _timescaledb_internal.attach_osm_table_chunk(regclass,regclass) 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.attach_osm_table_chunk($1,$2);
END$$
SET search_path TO pg_catalog,pg_temp;


Question: pgTAP test for Functap (assertion 284).

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

Explanation: SQL assertion from pgTAP test suite for Functap.


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

INSERT INTO entry (accession, txid) VALUES ('A00006', '3') ;


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

select jsonb_to_tsvector('english', '{"a": "aaa in bbb", "b": 123, "c": 456, "d": true, "f": false, "g": null}'::jsonb, '"boolean"');

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

SELECT count(*) FROM (select jsonb_to_tsvector('english', '{"a": "aaa in bbb", "b": 123, "c": 456, "d": true, "f": false, "g": null}'::jsonb, '"boolean"')) AS _sub;


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

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

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


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

create table hp1 partition of hp for values with (modulus 4, remainder 1);

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


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

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

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


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

SELECT count(*) FROM testjsonb WHERE j @? '$.public';

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


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

SELECT time without time zone 'T040506.07';

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

SELECT count(*) FROM (SELECT time without time zone 'T040506.07') AS _sub;


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

$$;
alter function whoami() owner to regress_fn_owner;

create table defer_trig (id integer);
grant insert on defer_trig to public;
create constraint trigger whoami after insert on defer_trig
  deferrable initially deferred
  for each row
  execute function whoami();

-- deferred triggers must run as the user that queued the trigger
begin;
set role regress_caller;
insert into defer_trig values (1);
reset role;
set role regress_fn_owner;
insert into defer_trig values (2);
reset role;
commit;

-- security definer functions override the user who queued the trigger
alter function whoami() security definer;
begin;
set role regress_caller;
insert into defer_trig values (3);
reset role;
commit;
alter function whoami() security invoker;

-- make sure the current user is restored after error
create or replace function whoami() returns trigger language plpgsql
as $$
begin
  raise notice 'I am %', current_user;

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


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

Explanation: DML from PostgreSQL core regression test for Subselect.


Question: Write the DML statement from PostgreSQL regression test 'jsonb' (example 431).

Explanation: DML from PostgreSQL core regression test for Jsonb.


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


Question: PostgreSQL Queries: show example 30.

SELECT a + b AS sum, c FROM table1 ORDER BY sum; SELECT a, max(b) FROM table1 GROUP BY a ORDER BY 1;

Explanation: Example from PostgreSQL documentation on Queries.


Question: Show a SQL definition from the postgrest project (schema, item 7).

CREATE TABLE items AS SELECT x AS id FROM generate_series(1,5) x;

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


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

select * from
  int8_tbl x left join (select q1,coalesce(q2,0) q2 from int8_tbl) y on x.q2 = y.q1,
  lateral (select x.q1,y.q1,y.q2) v(xq1,yq1,yq2);

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

SELECT count(*) FROM (select * from
  int8_tbl x left join (select q1,coalesce(q2,0) q2 from int8_tbl) y on x.q2 = y.q1,
  lateral (select x.q1,y.q1,y.q2) v(xq1,yq1,yq2)) AS _sub;


Question: Write the DML statement from PostgreSQL regression test 'rowsecurity' (example 352).

UPDATE t2 t2_1 SET b = t2_2.b FROM t2 t2_2
WHERE t2_1.a = 3 AND t2_2.a = t2_1.a AND t2_2.b = t2_1.b
AND f_leak(t2_1.b) AND f_leak(t2_2.b) RETURNING *, t2_1, t2_2;

Explanation: DML from PostgreSQL core regression test for Rowsecurity.


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

SELECT count(*)
FROM pg_foreign_server
WHERE srvname = 'fetch101'
AND srvoptions @> array['fetch_size=202'];

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


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

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


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

insert into insertconflictv values (1,'foo')
  on conflict (f1) do update set f2 = excluded.f2;

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


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

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

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


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

CREATE TABLE fk (id int, a int DEFAULT 50) PARTITION BY RANGE (a);

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


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

INSERT INTO fk VALUES (1);		-- should fail
BEGIN;

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


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

SELECT pg_stat_have_stats('database', :dboid, 0);

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

SELECT count(*) FROM (SELECT pg_stat_have_stats('database', :dboid, 0)) AS _sub;


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

insert into rtest_t9 values (28, 'Record should go to rtest_t4 and t8');

Explanation: DML from PostgreSQL core regression test for Rules.


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

ALTER EXTENSION pgtap ADD FUNCTION has_index ( NAME, NAME, text );

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


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

CREATE INDEX ON test_jsonb_mutability (JSON_QUERY(js, '$.datetime("YY-MM-DD") ? (@ == $x)' PASSING '2020-07-14'::date AS x));

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


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

$$ language plpgsql;

select raise_test();

create or replace function raise_test() returns void as $$
begin
  raise division_by_zero;

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


Question: Show a SQL definition from the pg_partman project (pg_partman--2.3.1--2.3.2, item 14).

/*
 * Check if parent table is a subpartition of an already existing partition set managed by pg_partman
 *  If so, return the limits of what child tables can be created under the given parent table based on its own suffix
 */
CREATE OR REPLACE FUNCTION check_subpartition_limits(p_parent_table text, p_type text, OUT sub_min text, OUT sub_max text) RETURNS record
    LANGUAGE plpgsql
    AS $$
DECLARE

v_datetime_string       text;
v_id_position           int;
v_parent_schema         text;
v_parent_tablename      text;
v_partition_interval    interval;
v_quarter               text;
v_sub_id_max            bigint;
v_sub_id_min            bigint;
v_sub_timestamp_max     timestamp;
v_sub_timestamp_min     timestamp;
v_time_position         int;
v_top_datetime_string   text;
v_top_interval          text;
v_top_parent            text;
v_top_type              text;
v_year                  text;

BEGIN

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

-- CTE query is done individually for each type (time, id) because it should return NULL if the top parent is not the same type in a subpartition set (id->time or time->id)

IF p_type = 'id' THEN

    WITH top_oid AS (
        SELECT i.inhparent AS top_parent_oid
        FROM pg_catalog.pg_class c
        JOIN pg_catalog.pg_inherits i ON c.oid = i.inhrelid
        JOIN pg_catalog.pg_namespace n ON n.oid = c.relnamespace
        WHERE n.nspname = v_parent_schema
        AND c.relname = v_parent_tablename
    ) SELECT n.nspname||'.'||c.relname, p.datetime_string, p.partition_interval, p.partition_type
      INTO v_top_parent, v_top_datetime_string, v_top_interval, v_top_type
      FROM pg_catalog.pg_class c
      JOIN top_oid t ON c.oid = t.top_parent_oid
      JOIN pg_catalog.pg_namespace n ON n.oid = c.relnamespace
      JOIN @extschema@.part_config p ON p.parent_table = n.nspname||'.'||c.relname
      WHERE c.oid = t.top_parent_oid
      AND p.partition_type = 'id';

    IF v_top_parent IS NOT NULL THEN
        SELECT child_start_id::text, child_end_id::text
        INTO sub_min, sub_max
        FROM @extschema@.show_partition_info(p_parent_table, v_top_interval, v_top_parent);
    END IF;

ELSIF p_type = 'time' THEN

    WITH top_oid AS (
        SELECT i.inhparent AS top_parent_oid
        FROM pg_catalog.pg_class c
        JOIN pg_catalog.pg_inherits i ON c.oid = i.inhrelid
        JOIN pg_catalog.pg_namespace n ON n.oid = c.relnamespace
        WHERE n.nspname = v_parent_schema
        AND c.relname = v_parent_tablename
    ) SELECT n.nspname||'.'||c.relname, p.datetime_string, p.partition_interval, p.partition_type
      INTO v_top_parent, v_top_datetime_string, v_top_interval, v_top_type
      FROM pg_catalog.pg_class c
      JOIN top_oid t ON c.oid = t.top_parent_oid
      JOIN pg_catalog.pg_namespace n ON n.oid = c.relnamespace
      JOIN @extschema@.part_config p ON p.parent_table = n.nspname||'.'||c.relname
      WHERE c.oid = t.top_parent_oid
      AND p.partition_type = 'time' OR p.partition_type = 'time-custom';

    IF v_top_parent IS NOT NULL THEN
        SELECT child_start_time::text, child_end_time::text
        INTO sub_min, sub_max
        FROM @extschema@.show_partition_info(p_parent_table, v_top_interval, v_top_parent);
    END IF;

ELSE
    RAISE EXCEPTION 'Invalid type given as parameter to check_subpartition_limits()';
END IF;

RETURN;

END
$$;

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


Question: pgTAP test for Hastap (assertion 121).

Explanation: SQL assertion from pgTAP test suite for Hastap.


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

CREATE FUNCTION gin_extract_query_oid(oid, internal, int2, internal, internal)
RETURNS internal
AS 'MODULE_PATHNAME'
LANGUAGE C STRICT IMMUTABLE;

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


Question: pgTAP test for Pgtap--1.2.0--1.3.0 (assertion 1).

CREATE OR REPLACE FUNCTION _runner( text[], text[], text[], text[], text[] )
RETURNS SETOF TEXT AS $$
DECLARE
    startup  ALIAS FOR $1;
    shutdown ALIAS FOR $2;
    setup    ALIAS FOR $3;
    teardown ALIAS FOR $4;
    tests    ALIAS FOR $5;
    tap      TEXT;
    tfaild   INTEGER := 0;
    ffaild   INTEGER := 0;
    tnumb    INTEGER := 0;
    fnumb    INTEGER := 0;
    tok      BOOLEAN := TRUE;
BEGIN
    BEGIN
        -- No plan support.
        PERFORM * FROM no_plan();
        FOR tap IN SELECT * FROM _runem(startup, false) LOOP RETURN NEXT tap; END LOOP;
    EXCEPTION
        -- Catch all exceptions and simply rethrow custom exceptions. This
        -- will roll back everything in the above block.
        WHEN raise_exception THEN RAISE EXCEPTION '%', SQLERRM;
    END;

    -- Record how startup tests have failed.
    tfaild := num_failed();

    FOR i IN 1..COALESCE(array_upper(tests, 1), 0) LOOP

        -- What subtest are we running?
        RETURN NEXT diag_test_name('Subtest: ' || tests[i]);

        -- Reset the results.
        tok := TRUE;
        tnumb := COALESCE(_get('curr_test'), 0);

        IF tnumb > 0 THEN
            EXECUTE 'ALTER SEQUENCE __tresults___numb_seq RESTART WITH 1';
            PERFORM _set('curr_test', 0);
            PERFORM _set('failed', 0);
        END IF;

        DECLARE
            errstate text;
            errmsg   text;
            detail   text;
            hint     text;
            context  text;
            schname  text;
            tabname  text;
            colname  text;
            chkname  text;
            typname  text;
        BEGIN
            BEGIN
                -- Run the setup functions.
                FOR tap IN SELECT * FROM _runem(setup, false) LOOP
                    RETURN NEXT regexp_replace(tap, '^', '    ', 'gn');
                END LOOP;

                -- Run the actual test function.
                FOR tap IN EXECUTE 'SELECT * FROM ' || tests[i] || '()' LOOP
                    RETURN NEXT regexp_replace(tap, '^', '    ', 'gn');
                END LOOP;

                -- Run the teardown functions.
                FOR tap IN SELECT * FROM _runem(teardown, false) LOOP
                    RETURN NEXT regexp_replace(tap, '^', '    ', 'gn');
                END LOOP;

                -- Emit the plan.
                fnumb := COALESCE(_get('curr_test'), 0);
                RETURN NEXT '    1..' || fnumb;

                -- Emit any error messages.
                IF fnumb = 0 THEN
                    RETURN NEXT '    # No tests run!';
                    tok = false;
                ELSE
                    -- Report failures.
                    ffaild := num_failed();
                    IF ffaild > 0 THEN
                        tok := FALSE;
                        RETURN NEXT '    ' || diag(
                            'Looks like you failed ' || ffaild || ' test' ||
                             CASE ffaild WHEN 1 THEN '' ELSE 's' END
                             || ' of ' || fnumb
                        );
                    END IF;
                END IF;

            EXCEPTION WHEN OTHERS THEN
                -- Something went wrong. Record that fact.
                errstate := SQLSTATE;
                errmsg := SQLERRM;
                GET STACKED DIAGNOSTICS
                    detail  = PG_EXCEPTION_DETAIL,
                    hint    = PG_EXCEPTION_HINT,
                    context = PG_EXCEPTION_CONTEXT,
                    schname = SCHEMA_NAME,
                    tabname = TABLE_NAME,
                    colname = COLUMN_NAME,
                    chkname = CONSTRAINT_NAME,
                    typname = PG_DATATYPE_NAME;
            END;

            -- Always raise an exception to rollback any changes.
            RAISE EXCEPTION '__TAP_ROLLBACK__';

        EXCEPTION WHEN raise_exception THEN
            IF errmsg IS NOT NULL THEN
                -- Something went wrong. Emit the error message.
                tok := FALSE;
               RETURN NEXT regexp_replace( diag('Test died: ' || _error_diag(
                   errstate, errmsg, detail, hint, context, schname, tabname, colname, chkname, typname
               )), '^', '    ', 'gn');
                errmsg := NULL;
            END IF;
        END;

        -- Restore the sequence.
        EXECUTE 'ALTER SEQUENCE __tresults___numb_seq RESTART WITH ' || tnumb + 1;
        PERFORM _set('curr_test', tnumb);
        PERFORM _set('failed', tfaild);

        -- Record this test.
        RETURN NEXT ok(tok, tests[i]);
        IF NOT tok THEN tfaild := tfaild + 1; END IF;

    END LOOP;

    -- Run the shutdown functions.
    FOR tap IN SELECT * FROM _runem(shutdown, false) LOOP RETURN NEXT tap; END LOOP;

    -- Finish up.
    FOR tap IN SELECT * FROM _finish( COALESCE(_get('curr_test'), 0), 0, tfaild ) LOOP
        RETURN NEXT tap;
    END LOOP;

    -- Clean up and return.
    PERFORM _cleanup();
    RETURN;
END;
$$ LANGUAGE plpgsql;

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


Question: pgTAP test for Policy (assertion 62).

SELECT * FROM check_test(
    policy_cmd_is( 'passwd', 'user_mod', 'all' ),
    false,
    'policy_cmd_is(table, policy, command) for UPDATE should fail',
    'Policy user_mod for table passwd should apply to ALL command',
    '        have: UPDATE
        want: ALL'
);

Explanation: SQL assertion from pgTAP test suite for Policy.


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

SELECT count(*) FROM numerictmp WHERE a >  -1890.0;


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

CREATE FUNCTION gbt_enum_same(gbtreekey8, gbtreekey8, internal)
RETURNS internal
AS 'MODULE_PATHNAME'
LANGUAGE C IMMUTABLE STRICT;


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

SELECT JSON_QUERY(jsonb '"[3,4]"', '$[*]' RETURNING bigint[] EMPTY OBJECT ON ERROR);

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

SELECT count(*) FROM (SELECT JSON_QUERY(jsonb '"[3,4]"', '$[*]' RETURNING bigint[] EMPTY OBJECT ON ERROR)) AS _sub;


Question: Show a SQL definition from the pg_partman project (pg_partman--2.3.2--2.3.3, item 4).

/*
 * Apply constraints managed by partman extension
 */
CREATE OR REPLACE FUNCTION apply_constraints(p_parent_table text, p_child_table text DEFAULT NULL, p_analyze boolean DEFAULT FALSE, p_job_id bigint DEFAULT NULL, p_debug boolean DEFAULT FALSE) RETURNS void
    LANGUAGE plpgsql
    AS $$
DECLARE

ex_context                      text;
ex_detail                       text;
ex_hint                         text;
ex_message                      text;
v_child_exists                  text;
v_child_tablename               text;
v_col                           text;
v_constraint_cols               text[];
v_constraint_col_type           text;
v_constraint_name               text;
v_constraint_values             record;
v_control                       text;
v_datetime_string               text;
v_existing_constraint_name      text;
v_job_id                        bigint;
v_jobmon                        boolean;
v_jobmon_schema                 text;
v_last_partition                text;
v_last_partition_id             bigint;
v_last_partition_timestamp      timestamp;
v_max_id                        bigint;
v_max_timestamp                 timestamp;
v_old_search_path               text;
v_optimize_constraint           int;
v_parent_schema                 text;
v_parent_table                  text;
v_parent_tablename              text;
v_partition_interval            text;
v_partition_suffix              text;
v_premake                       int;
v_sql                           text;
v_step_id                       bigint;
v_suffix_position               int;
v_type                          text;

BEGIN

SELECT parent_table
    , partition_type
    , control
    , premake
    , partition_interval
    , optimize_constraint
    , datetime_string
    , constraint_cols
    , jobmon
INTO v_parent_table
    , v_type
    , v_control
    , v_premake
    , v_partition_interval
    , v_optimize_constraint
    , v_datetime_string
    , v_constraint_cols
    , v_jobmon
FROM @extschema@.part_config
WHERE parent_table = p_parent_table
AND constraint_cols IS NOT NULL;

IF v_constraint_cols IS NULL THEN
    IF p_debug THEN
        RAISE NOTICE 'Given parent table (%) not set up for constraint management (constraint_cols is NULL)', p_parent_table;
    END IF;
    -- Returns silently to allow this function to be simply called by maintenance processes without having to check if config options are set.
    RETURN;
END IF;

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

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

IF v_jobmon_schema IS NOT NULL THEN
    IF p_job_id IS NULL THEN
        v_job_id := add_job(format('PARTMAN CREATE CONSTRAINT: %s', v_parent_table));
    ELSE
        v_job_id = p_job_id;
    END IF;
END IF;

-- If p_child_table is null, figure out the partition that is the one right before the optimize_constraint value backwards.
IF p_child_table IS NULL THEN
    IF v_jobmon_schema IS NOT NULL THEN
        v_step_id := add_step(v_job_id, 'Applying additional constraints: Automatically determining most recent child on which to apply constraints');
    END IF;

    SELECT partition_tablename INTO v_last_partition FROM @extschema@.show_partitions(v_parent_table, 'DESC') LIMIT 1;

    IF v_type IN ('time', 'time-custom') THEN
        SELECT child_start_time INTO v_last_partition_timestamp FROM @extschema@.show_partition_info(v_parent_schema||'.'||v_last_partition, v_partition_interval, v_parent_table);
        v_partition_suffix := to_char(v_last_partition_timestamp - (v_partition_interval::interval * (v_optimize_constraint + v_premake + 1) ), v_datetime_string);
    ELSIF v_type = 'id' THEN
        SELECT child_start_id INTO v_last_partition_id FROM @extschema@.show_partition_info(v_parent_schema||'.'||v_last_partition, v_partition_interval, v_parent_table);
        v_partition_suffix := (v_last_partition_id - (v_partition_interval::int * (v_optimize_constraint + v_premake + 1) ))::text;
    END IF;

    v_child_tablename := @extschema@.check_name_length(v_parent_tablename, v_partition_suffix, TRUE);

    IF p_debug THEN
        RAISE NOTICE 'apply_constraint: v_parent_tablename: % , v_partition_suffix: %', v_parent_tablename, v_partition_suffix;
    END IF;

    IF v_jobmon_schema IS NOT NULL THEN
        PERFORM update_step(v_step_id, 'OK', format('Target child table: %s.%s', v_parent_schema, v_child_tablename));
    END IF;
ELSE
    v_child_tablename = split_part(p_child_table, '.', 2);
END IF;

IF v_jobmon_schema IS NOT NULL THEN
    v_step_id := add_step(v_job_id, 'Applying additional constraints: Checking if target child table exists');
END IF;

SELECT tablename FROM pg_catalog.pg_tables INTO v_child_exists WHERE schemaname = v_parent_schema::name AND tablename = v_child_tablename::name;
IF v_child_exists IS NULL THEN
    IF v_jobmon_schema IS NOT NULL THEN
        PERFORM update_step(v_step_id, 'NOTICE', format('Target child table (%s) does not exist. Skipping constraint creation.', v_child_tablename));
        IF p_job_id IS NULL THEN
            PERFORM close_job(v_job_id);
        END IF;
        EXECUTE format('SELECT set_config(%L, %L, %L)', 'search_path', v_old_search_path, 'false');
    END IF;
    IF p_debug THEN
        RAISE NOTICE 'Target child table (%) does not exist. Skipping constraint creation.', v_child_tablename;
    END IF;
    RETURN;
ELSE
    IF v_jobmon_schema IS NOT NULL THEN
        PERFORM update_step(v_step_id, 'OK', 'Done');
    END IF;
END IF;

FOREACH v_col IN ARRAY v_constraint_cols
LOOP
    SELECT con.conname
    INTO v_existing_constraint_name
    FROM pg_catalog.pg_constraint con
    JOIN pg_class c ON c.oid = con.conrelid
    JOIN pg_catalog.pg_namespace n ON c.relnamespace = n.oid
    JOIN pg_catalog.pg_attribute a ON con.conrelid = a.attrelid
    WHERE c.relname = v_child_tablename
        AND n.nspname = v_parent_schema
        AND con.conname LIKE 'partmanconstr_%'
        AND con.contype = 'c'
        AND a.attname = v_col
        AND ARRAY[a.attnum] OPERATOR(pg_catalog.<@) con.conkey
        AND a.attisdropped = false;

    IF v_jobmon_schema IS NOT NULL THEN
        v_step_id := add_step(v_job_id, format('Applying additional constraints: Applying new constraint on column: %s', v_col));
    END IF;

    IF v_existing_constraint_name IS NOT NULL THEN
        IF v_jobmon_schema IS NOT NULL THEN
            PERFORM update_step(v_step_id, 'NOTICE', format('Partman managed constraint already exists on this table (%s) and column (%s). Skipping creation.', v_child_tablename, v_col));
        END IF;
        IF p_debug THEN
            RAISE NOTICE 'Partman managed constraint already exists on this table (%) and column (%). Skipping creation.', v_child_tablename, v_col ;
        END IF;
        CONTINUE;
    END IF;

    -- Ensure column name gets put on end of constraint name to help avoid naming conflicts
    v_constraint_name := @extschema@.check_name_length('partmanconstr_'||v_child_tablename, p_suffix := '_'||v_col);

    EXECUTE format('SELECT min(%I)::text AS min, max(%I)::text AS max FROM %I.%I', v_col, v_col, v_parent_schema, v_child_tablename) INTO v_constraint_values;

    IF v_constraint_values IS NOT NULL THEN
        v_sql := format('ALTER TABLE %I.%I ADD CONSTRAINT %I CHECK (%I >= %L AND %I <= %L)'
                            , v_parent_schema
                            , v_child_tablename
                            , v_constraint_name
                            , v_col
                            , v_constraint_values.min
                            , v_col
                            , v_constraint_values.max);
        IF p_debug THEN
            RAISE NOTICE 'Constraint creation query: %', v_sql;
        END IF;
        EXECUTE v_sql;

        IF v_jobmon_schema IS NOT NULL THEN
            PERFORM update_step(v_step_id, 'OK', format('New constraint created: %s', v_sql));
        END IF;
    ELSE
        IF p_debug THEN
            RAISE NOTICE 'Given column (%) contains all NULLs. No constraint created', v_col;
        END IF;
        IF v_jobmon_schema IS NOT NULL THEN
            PERFORM update_step(v_step_id, 'NOTICE', format('Given column (%s) contains all NULLs. No constraint created', v_col));
        END IF;
    END IF;

END LOOP;

IF p_analyze THEN
    IF v_jobmon_schema IS NOT NULL THEN
        v_step_id := add_step(v_job_id, format('Applying additional constraints: Running analyze on partition set: %s', v_parent_table));
    END IF;
    IF p_debug THEN
        RAISE NOTICE 'Running analyze on partition set: %', v_parent_table;
    END IF;

    EXECUTE format('ANALYZE %I.%I', v_parent_schema, v_parent_tablename);

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

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

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


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

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

SELECT count(*) FROM (select f1, f4 from tt14v) AS _sub;


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

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


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

CREATE TABLE clstr_tst_inh () INHERITS (clstr_tst);

Explanation: DDL from PostgreSQL core regression test for Cluster.


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

SELECT 'ltree.awdfg'::ltree @ '!tree & aWdf@*'::ltxtquery;

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


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

SELECT xmlserialize(document 'bad' as text);

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

SELECT count(*) FROM (SELECT xmlserialize(document 'bad' as text)) AS _sub;


Question: pgTAP test for Hastap (assertion 204).

SELECT * FROM check_test(
  has_leftop( '+', 'int8' ),
  true,
  'has_leftop( name, right )',
  'Left operator +(NONE,int8) should exist',
  ''
);


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

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

SELECT count(*) FROM (select 'null'::jsonb::bool) AS _sub;


Question: PostgreSQL Xfunc: show example 1.

Explanation: Example from PostgreSQL documentation on Xfunc.


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

SELECT * FROM test_int2 WHERE i<=32768::int4 ORDER BY i;

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


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

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

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


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

CREATE TABLE trigger_test_generated (
    i int,
    j int GENERATED ALWAYS AS (i * 2) STORED,
    k int GENERATED ALWAYS AS (i * 3) VIRTUAL
);

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


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

SELECT xmlelement(name foo, xmlattributes('<>&"''' as funny, xml 'b<a/>r' as funnier));

SELECT count(*) FROM (SELECT xmlelement(name foo, xmlattributes('<>&"''' as funny, xml 'b<a/>r' as funnier))) AS _sub;


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

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


Question: PostgreSQL regression test 'foreign_data': Write the SELECT query (example 243).

SELECT * FROM information_schema.user_mapping_options ORDER BY lower(authorization_identifier), 2, 3, 4;

Explanation: Regression test for Foreign Data in PostgreSQL core test suite.

SELECT count(*) FROM (SELECT * FROM information_schema.user_mapping_options ORDER BY lower(authorization_identifier), 2, 3, 4) AS _sub;


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

CREATE OR REPLACE VIEW lock_view2 AS SELECT * from lock_view3;

Explanation: DDL from PostgreSQL core regression test for Lock.


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

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

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


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

-- Check that all combine functions have signature
-- combine(transtype, transtype) returns transtype

SELECT a.aggfnoid, p.proname
FROM pg_aggregate as a, pg_proc as p
WHERE a.aggcombinefn = p.oid AND
    (p.pronargs != 2 OR
     p.prorettype != p.proargtypes[0] OR
     p.prorettype != p.proargtypes[1] OR
     NOT binary_coercible(a.aggtranstype, p.proargtypes[0]));

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


Question: Show an example of PostgreSQL CREATE TYPE (example 4).

CREATE TYPE box; CREATE FUNCTION my_box_in_function(cstring) RETURNS box AS ... ; CREATE FUNCTION my_box_out_function(box) RETURNS cstring AS ... ; CREATE TYPE box ( INTERNALLENGTH = 16, INPUT = my_box_in_function, OUTPUT = my_box_out_function ); CREATE TABLE myboxes ( id integer, description box );

Explanation: PostgreSQL CREATE TYPE command.


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

CREATE POLICY blog_1 ON blog USING (id % 2 = 0);

Explanation: DDL from PostgreSQL core regression test for Rowsecurity.


Question: PostgreSQL regression test 'plpgsql': Write the SELECT query (example 312).

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

SELECT count(*) FROM (select 1,2 into x, y) AS _sub;


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

INSERT INTO serialTest2 (f1, f3)
  VALUES ('bogus', 32768);

Explanation: DML from PostgreSQL core regression test for Sequence.


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

SELECT citext_larger( 'ab'::citext, 'ac'::citext ) = 'ac' AS t;

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


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

select * from pg_input_error_info('[1,2147483647]', 'int4range');

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

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


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

INSERT INTO itest5 OVERRIDING USER VALUE VALUES (DEFAULT, 'ddd'), (-4, 'eee');

Explanation: DML from PostgreSQL core regression test for Identity.


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

Explanation: DML from PostgreSQL core regression test for Numeric.


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

Explanation: DML from PostgreSQL core regression test for Update.


Question: pgTAP test for Resultset (assertion 432).

-- Now when the last row is missing.
SELECT * FROM check_test(
    results_ne(
        'SELECT id, name FROM annames WHERE name <> ''Antonio''',
        'nenames_ord'
    ),
    true,
    'results_ne(select, prepared) missing last row',
    '',
    ''
);

Explanation: SQL assertion from pgTAP test suite for Resultset.


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

select trap_foreign_key_2();  -- detects FK violation
commit;				-- still fails

drop function trap_foreign_key(int);

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


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

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


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

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


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

-- access to call stack from exception
create function inner_func(int)
returns int as $$
declare
  _context text;
  sx int := 5;
begin
  begin
    perform sx / 0;
  exception
    when division_by_zero then
      get diagnostics _context = pg_context;
      raise notice '***%***', _context;
  end;

  -- lets do it again, just for fun..
  get diagnostics _context = pg_context;
  raise notice '***%***', _context;
  raise notice 'lets make sure we didnt break anything';
  return 2 * $1;
end;
$$ language plpgsql;

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


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

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

Explanation: DML from PostgreSQL core regression test for Timestamptz.


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

INSERT INTO cmpart VALUES (repeat('123456789', 1004));

Explanation: DML from PostgreSQL core regression test for Compression Lz4.


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

Explanation: DML from PostgreSQL core regression test for Cluster.


Question: pgTAP test for Pktap (assertion 37).

SELECT * FROM check_test(
    col_isnt_pk( 'sometab', 'id' ),
    false,
    'col_isnt_pk( table, column )',
    'Column sometab(id) should not be a primary key',
    '        have: {id}
        want: anything else'
);

Explanation: SQL assertion from pgTAP test suite for Pktap.


Question: Show a SQL definition from the timescaledb project (util_time, item 8).

-- Time can be represented in a hypertable as an int* (bigint/integer/smallint) or as a timestamp type (
-- with or without timezones). In metatables and other internal systems all time values are stored as bigint.
-- Converting from int* columns to internal representation is a cast to bigint.
-- Converting from timestamps to internal representation is conversion to epoch (in microseconds).

CREATE OR REPLACE FUNCTION _timescaledb_functions.interval_to_usec(
       chunk_interval INTERVAL
)
RETURNS BIGINT LANGUAGE SQL IMMUTABLE PARALLEL SAFE AS
$BODY$
    SELECT (int_sec * 1000000)::bigint from extract(epoch from chunk_interval) as int_sec;

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


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

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

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


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

SELECT * FROM JSON_TABLE(jsonb '"a"', '$' COLUMNS (a float4 EXISTS PATH '$.a'));

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

SELECT count(*) FROM (SELECT * FROM JSON_TABLE(jsonb '"a"', '$' COLUMNS (a float4 EXISTS PATH '$.a'))) AS _sub;


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

Explanation: PostgreSQL DROP TSTEMPLATE command.


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

select count(*) from test_multirange_gist where mr = '{}'::int4multirange;

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

SELECT count(*) FROM (select count(*) from test_multirange_gist where mr = '{}'::int4multirange) AS _sub;


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

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

SELECT count(*) FROM (SELECT lo_import(:'filename')) AS _sub;


Question: pgTAP test for Index (assertion 27).

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

Explanation: SQL assertion from pgTAP test suite for Index.


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

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

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


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

ALTER ROLE davide WITH PASSWORD 'hu8jmn3';

Explanation: PostgreSQL ALTER ROLE command.


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

create table text_hashp1 partition of text_hashp for values with (modulus 2, remainder 1);

Explanation: DDL from PostgreSQL core regression test for Hash Part.


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

-- proretset should only be set for normal functions
SELECT p1.oid, p1.proname
FROM pg_proc AS p1
WHERE proretset AND prokind != 'f';

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


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

SELECT noabort_increasing, noabort_decreasing FROM abbrev_abort_uuids ORDER BY noabort_decreasing NULLS FIRST OFFSET 20000 - 4;

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

SELECT count(*) FROM (SELECT noabort_increasing, noabort_decreasing FROM abbrev_abort_uuids ORDER BY noabort_decreasing NULLS FIRST OFFSET 20000 - 4) AS _sub;


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

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


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

SELECT * FROM JSON_TABLE(jsonb '"world"', '$' COLUMNS (item text PATH '$' OMIT QUOTES ON SCALAR STRING));

SELECT count(*) FROM (SELECT * FROM JSON_TABLE(jsonb '"world"', '$' COLUMNS (item text PATH '$' OMIT QUOTES ON SCALAR STRING))) AS _sub;


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

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


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

create table insertconflicttest(key int4, fruit text);

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


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

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


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

CREATE TRIGGER view_insert INSTEAD OF INSERT ON my_view FOR EACH ROW EXECUTE FUNCTION view_insert_row();

Explanation: PostgreSQL CREATE TRIGGER command.


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

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

Explanation: DML from PostgreSQL core regression test for Timestamp.


Question: pgTAP test for Throwtap (assertion 35).

/****************************************************************************/
-- Test ASSERTs
SELECT lives_ok(
    CASE WHEN pg_version_num() < 90500 THEN $exec$
CREATE FUNCTION check_assert(b boolean) RETURNS void LANGUAGE plpgsql AS $body$
BEGIN
    RAISE EXCEPTION 'this code should never be called!';

Explanation: SQL assertion from pgTAP test suite for Throwtap.


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

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


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

create index gist_pointidx3 on gist_point_tbl using gist(p) with (buffering = off);

Explanation: DDL from PostgreSQL core regression test for Gist.


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

SELECT 'foo & bar'::tsquery || 'asd & fg';

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

SELECT count(*) FROM (SELECT 'foo & bar'::tsquery || 'asd & fg') AS _sub;


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

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

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


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

CREATE POLICY p2 ON x1 FOR INSERT WITH CHECK (a % 2 = 1);

Explanation: DDL from PostgreSQL core regression test for Rowsecurity.


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

-- plain sort not triggering abbreviated abort
SELECT noabort_increasing, noabort_decreasing FROM abbrev_abort_uuids ORDER BY noabort_increasing OFFSET 20000 - 4;

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


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

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

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


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

SELECT count(*) FROM (SELECT round(5e-16383, 16382) = 1e-16382) AS _sub;


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

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


Question: Show a SQL definition from the citus project (coordinator_evaluation, item 7).

CREATE TABLE coordinator_evaluation_table (key int, value int);

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


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

CREATE VIEW tid_view_with_ctid AS SELECT ctid, a FROM tid_tab;

Explanation: DDL from PostgreSQL core regression test for Tid.


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

select jsonb_path_query('{"a": [1, 2]}', 'lax $.a * 3');

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

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


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

Explanation: DML from PostgreSQL core regression test for Arrays.


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

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

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


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

SELECT nummultirange() &> nummultirange(numrange(1,2));

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

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


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

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

SELECT count(*) FROM (SELECT ts_lexize('ispell', 'booking')) AS _sub;


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

select v, v is null as "is null" from string_to_table('1,2,3,4,,6', ',', '') g(v);

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

SELECT count(*) FROM (select v, v is null as "is null" from string_to_table('1,2,3,4,,6', ',', '') g(v)) AS _sub;


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

select max(unique2) from tenk1 order by 1;

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

SELECT count(*) FROM (select max(unique2) from tenk1 order by 1) AS _sub;


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

Explanation: DDL from PostgreSQL core regression test for Transactions.


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

SELECT count(*) FROM (select jsonb_path_query('"12:34"', '$.datetime("HH24:MI")')) AS _sub;


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

SELECT count(*) FROM timestamptztmp WHERE a <  '2018-12-18 10:59:54 GMT+2'::timestamptz;

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


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

Explanation: DML from PostgreSQL core regression test for Rules.


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

SELECT f1 AS "Seven" FROM TIMETZ_TBL WHERE f1 > '05:06:07-07';

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

SELECT count(*) FROM (SELECT f1 AS "Seven" FROM TIMETZ_TBL WHERE f1 > '05:06:07-07') AS _sub;


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

CREATE FUNCTION uuid_generate_v4()
RETURNS uuid
AS 'MODULE_PATHNAME', 'uuid_generate_v4'
VOLATILE STRICT LANGUAGE C PARALLEL SAFE;

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


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

SELECT * FROM test_table_record_as('obj', null, null, true);

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


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

SELECT qq, unique1
  FROM
  ( SELECT COALESCE(q1, 0) AS qq FROM int8_tbl a ) AS ss1
  FULL OUTER JOIN
  ( SELECT COALESCE(q2, -1) AS qq FROM int8_tbl b ) AS ss2
  USING (qq)
  INNER JOIN tenk1 c ON qq = unique2;

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

SELECT count(*) FROM (SELECT qq, unique1
  FROM
  ( SELECT COALESCE(q1, 0) AS qq FROM int8_tbl a ) AS ss1
  FULL OUTER JOIN
  ( SELECT COALESCE(q2, -1) AS qq FROM int8_tbl b ) AS ss2
  USING (qq)
  INNER JOIN tenk1 c ON qq = unique2) AS _sub;


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

UPDATE hash_i4_heap
   SET seqno = 20000
   WHERE hash_i4_heap.random = 1492795354;

Explanation: DML from PostgreSQL core regression test for Hash Index.


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

SELECT '4714-11-24 BC'::date::timestamptz;  -- fail

SELECT '4714-11-24 BC'::date < '2020-10-05'::timestamptz as t;

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

SELECT count(*) FROM (SELECT '4714-11-24 BC'::date::timestamptz;  -- fail

SELECT '4714-11-24 BC'::date < '2020-10-05'::timestamptz as t) AS _sub;


Question: Write the DML statement from PostgreSQL regression test 'float8' (example 4).

INSERT INTO FLOAT8_TBL(f1) VALUES ('   -34.84');

Explanation: DML from PostgreSQL core regression test for Float8.


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

SELECT * FROM pg_input_error_info('[{"attributes" : [2,3], "dependency": 4, "degree": 1.000, "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,3], "dependency": 4, "degree": 1.000, "degree": 1.000}]', 'pg_dependencies')) AS _sub;


Question: pgTAP test for Resultset (assertion 411).

INSERT INTO nord (id, name ) VALUES(183, 'Antonio');

Explanation: SQL assertion from pgTAP test suite for Resultset.


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

select encode(decrypt(encrypt('Lets try a longer message.', '0123456789', 'aes-cfb'), '0123456789', 'aes-cfb'), 'escape');

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


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

SELECT master_create_empty_shard('lineitem') as lineitem_shardid1 \gset
SELECT master_create_empty_shard('lineitem') as lineitem_shardid2 \gset

CREATE TABLE orders (LIKE public.orders);

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


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

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


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

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

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


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

CREATE FUNCTION _int_contains_joinsel(internal, oid, internal, smallint, internal)
RETURNS float8
AS 'MODULE_PATHNAME'
LANGUAGE C STRICT STABLE;


Question: pgTAP test for Pgtap--1.0.0--1.1.0 (assertion 11).

-- _keys( schema, table, constraint_type )
CREATE OR REPLACE FUNCTION _keys ( NAME, NAME, CHAR )
RETURNS SETOF NAME[] AS $$
    SELECT _pg_sv_column_array(x.conrelid,x.conkey) -- name[] doesn't support collation
      FROM pg_catalog.pg_namespace n
      JOIN pg_catalog.pg_class c       ON n.oid = c.relnamespace
      JOIN pg_catalog.pg_constraint x  ON c.oid = x.conrelid
     WHERE n.nspname = $1
       AND c.relname = $2
       AND x.contype = $3
  ORDER BY 1
$$ LANGUAGE sql;

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


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

SELECT '23:59:59.9999999'::time;  -- rounds up
SELECT '23:59:60'::time;  -- rounds up
SELECT '24:00:00'::time;  -- allowed
SELECT '24:00:00.01'::time;  -- not allowed
SELECT '23:59:60.01'::time;  -- not allowed
SELECT '24:01:00'::time;  -- not allowed
SELECT '25:00:00'::time;  -- not allowed

-- Test non-error-throwing API
SELECT pg_input_is_valid('12:00:00', 'time');

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

SELECT count(*) FROM (SELECT '23:59:59.9999999'::time;  -- rounds up
SELECT '23:59:60'::time;  -- rounds up
SELECT '24:00:00'::time;  -- allowed
SELECT '24:00:00.01'::time;  -- not allowed
SELECT '23:59:60.01'::time;  -- not allowed
SELECT '24:01:00'::time;  -- not allowed
SELECT '25:00:00'::time;  -- not allowed

-- Test non-error-throwing API
SELECT pg_input_is_valid('12:00:00', 'time')) AS _sub;


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

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


Question: PostgreSQL Indices: show example 39.

SELECT * FROM test1c WHERE content > constant ;

Explanation: Example from PostgreSQL documentation on Indices.


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

-- behave reasonably if someone tries to modify a transition table
CREATE FUNCTION transition_table_level2_bad_usage_func()
  RETURNS TRIGGER
  LANGUAGE plpgsql
AS $$
  BEGIN
    INSERT INTO dx VALUES (1000000, 1000000, 'x');
    RETURN NULL;
  END;
$$;

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


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

--
-- bt_page_items_bytea()
--
CREATE FUNCTION bt_page_items(IN page bytea,
    OUT itemoffset smallint,
    OUT ctid tid,
    OUT itemlen smallint,
    OUT nulls bool,
    OUT vars bool,
    OUT data text)
RETURNS SETOF record
AS 'MODULE_PATHNAME', 'bt_page_items_bytea'
LANGUAGE C STRICT PARALLEL SAFE;

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


Question: pgTAP test for Policy (assertion 73).

SELECT * FROM check_test(
    policy_cmd_is( 'passwd', 'root_all', 'all', 'whatever' ),
    true,
    'policy_cmd_is(table, policy, command, desc) for ALL',
    'whatever',
    ''
);

Explanation: SQL assertion from pgTAP test suite for Policy.


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

CREATE TABLE beta_neg_p1 PARTITION OF beta_neg FOR VALUES FROM (100) TO (150);

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


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

SELECT * FROM multiout_record_as('obj', null, null, false);

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


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

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

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


Question: Show a SQL definition from the citus project (columnar_data_types, item 4).

-- Test array types
CREATE TABLE test_array_types (int_array int[], bigint_array bigint[],
	text_array text[]) USING columnar;


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

INSERT INTO PKTABLE VALUES (3, 6, 'Test3');

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


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

-- Create the operator class
CREATE OPERATOR CLASS gist_enum_ops
DEFAULT FOR TYPE anyenum USING gist
AS
	OPERATOR	1	<  ,
	OPERATOR	2	<= ,
	OPERATOR	3	=  ,
	OPERATOR	4	>= ,
	OPERATOR	5	>  ,
	FUNCTION	1	gbt_enum_consistent (internal, anyenum, int2, oid, internal),
	FUNCTION	2	gbt_enum_union (internal, internal),
	FUNCTION	3	gbt_enum_compress (internal),
	FUNCTION	4	gbt_decompress (internal),
	FUNCTION	5	gbt_enum_penalty (internal, internal, internal),
	FUNCTION	6	gbt_enum_picksplit (internal, internal),
	FUNCTION	7	gbt_enum_same (gbtreekey8, gbtreekey8, internal),
	STORAGE		gbtreekey8;


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

SELECT b.* FROM b LEFT JOIN a ON (b.a_id = a.id) WHERE (a.id IS NULL OR a.id > 0);

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

SELECT count(*) FROM (SELECT b.* FROM b LEFT JOIN a ON (b.a_id = a.id) WHERE (a.id IS NULL OR a.id > 0)) AS _sub;


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

CREATE TABLE temporal_rng2 (
  CONSTRAINT temporal_rng_pk PRIMARY KEY (id, valid_at WITHOUT OVERLAPS)
) INHERITS (temporal_rng);

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


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


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

SELECT 'a'::citext = 'A'::text AS f;        -- text wins the discussion
SELECT 'a'::citext = 'b'::citext AS f;

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


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

CREATE TABLE varbit_table (a BIT VARYING(16), b BIT VARYING(16));

Explanation: DDL from PostgreSQL core regression test for Bit.


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

SELECT attinhcount, attislocal FROM pg_attribute WHERE attrelid = 'part_3_4'::regclass AND attnum > 0;

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

SELECT count(*) FROM (SELECT attinhcount, attislocal FROM pg_attribute WHERE attrelid = 'part_3_4'::regclass AND attnum > 0) AS _sub;


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

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

SELECT count(*) FROM (SELECT unistr('wrong: \U0000db99\U00000061')) AS _sub;


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

insert into rtest_view3 select * from rtest_vview1 where a < 7;

Explanation: DML from PostgreSQL core regression test for Rules.


Question: Write the DDL statement from PostgreSQL regression test 'drop_if_exists' (example 75).

CREATE OPERATOR @#@
        (leftarg = int8, rightarg = int8, procedure = int8xor);

Explanation: DDL from PostgreSQL core regression test for Drop If Exists.


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

SELECT * FROM test_squash WHERE id IN (1, 2, 3);

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


Question: PostgreSQL regression test 'partition_split': Write the SELECT query (example 206).

SELECT * FROM sales_central WHERE sales_state = 'Warsaw';

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

SELECT count(*) FROM (SELECT * FROM sales_central WHERE sales_state = 'Warsaw') AS _sub;


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

CREATE TABLE prt (a int) PARTITION BY RANGE(a);

Explanation: DDL from PostgreSQL core regression test for Memoize.


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

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


Question: PostgreSQL Plpgsql: show example 23.

Explanation: Example from PostgreSQL documentation on Plpgsql.


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

SELECT unique1, unique2 FROM onek_with_null
  ORDER BY unique2 DESC LIMIT 5;

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

SELECT count(*) FROM (SELECT unique1, unique2 FROM onek_with_null
  ORDER BY unique2 DESC LIMIT 5) AS _sub;


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

CREATE SEQUENCE sequence_test9 AS integer INCREMENT BY -1;

Explanation: DDL from PostgreSQL core regression test for Sequence.


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

ALTER EXTENSION pgtap ADD FUNCTION fail ( text );

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


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

select pg_typeof(array['11 22 33'::oidvector]);

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

SELECT count(*) FROM (select pg_typeof(array['11 22 33'::oidvector])) AS _sub;


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

INSERT INTO vac_truncate_test VALUES (1, NULL), (NULL, NULL);

Explanation: DML from PostgreSQL core regression test for Vacuum.


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

CREATE POLICY p3 ON rls_part USING (a < 0);

Explanation: DDL from PostgreSQL core regression test for Rowsecurity.


Question: PostgreSQL Ddl: show example 53.

ALTER TABLE products ALTER COLUMN product_no DROP NOT NULL;

Explanation: Example from PostgreSQL documentation on Ddl.


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

INSERT INTO caster (text)          VALUES ('((0,0),2)'::circle);

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


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

Explanation: DML from PostgreSQL core regression test for Transactions.


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

SELECT JSON_SERIALIZE('{ "a" : 1 } ' RETURNING varchar);

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

SELECT count(*) FROM (SELECT JSON_SERIALIZE('{ "a" : 1 } ' RETURNING varchar)) AS _sub;


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


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

-- check that function dropped in a subtransaction leaves no stats behind
BEGIN;

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


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

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

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

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


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

SELECT ft5, ft5.c1, ft5.c2, ft5.c3, ft4.c1, ft4.c2 FROM ft5 left join ft4 on ft5.c1 = ft4.c1 WHERE ft4.c1 BETWEEN 10 and 30 ORDER BY ft5.c1, ft4.c1;

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


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

insert into spgist_point_tbl (id, p)
select g+100000, point(g*10+1, g*10+1) from generate_series(1, 10000) g;

Explanation: DML from PostgreSQL core regression test for Spgist.


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

select '"a"'::jsonb #- '{a}'; -- error
select '{}'::jsonb #- '{a}';

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

SELECT count(*) FROM (select '"a"'::jsonb #- '{a}'; -- error
select '{}'::jsonb #- '{a}') AS _sub;


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

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


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

}
spi_exec {select replaceme('foe') as inner}
return "fee $1 $inner"
$p$ language pltcl;

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


Question: PostgreSQL regression test 'rowsecurity': Write the SELECT query (example 246).

SELECT * FROM part_document_satire ORDER by did;

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

SELECT count(*) FROM (SELECT * FROM part_document_satire ORDER by did) AS _sub;


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

CREATE FUNCTION seg_upper(seg)
RETURNS float4
AS 'MODULE_PATHNAME'
LANGUAGE C STRICT IMMUTABLE PARALLEL SAFE;

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


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

Explanation: DML from PostgreSQL core regression test for Domain.


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

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

SELECT count(*) FROM (SELECT regclass('pg_catalog.pg_class')) AS _sub;


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

create table part_xx_yy partition of list_parted for values in ('xx', 'yy') partition by list (a);

Explanation: DDL from PostgreSQL core regression test for Insert.


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

SELECT count(*) FROM quad_point_tbl WHERE p <<| '(5000, 4000)';

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

SELECT count(*) FROM (SELECT count(*) FROM quad_point_tbl WHERE p <<| '(5000, 4000)') AS _sub;


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

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

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

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


Question: PostgreSQL regression test 'partition_merge': Write the SELECT query (example 227).

SELECT tablename, indexname, tablespace FROM pg_indexes
  WHERE tablename IN ('t', 'tp_0_2') AND schemaname = 'partitions_merge_schema'
  ORDER BY tablename COLLATE "C", indexname COLLATE "C", tablespace COLLATE "C";

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

SELECT count(*) FROM (SELECT tablename, indexname, tablespace FROM pg_indexes
  WHERE tablename IN ('t', 'tp_0_2') AND schemaname = 'partitions_merge_schema'
  ORDER BY tablename COLLATE "C", indexname COLLATE "C", tablespace COLLATE "C") AS _sub;


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

SELECT * FROM test_type_conversion_int4(null);

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


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

create table minmaxtest2() inherits (minmaxtest);

Explanation: DDL from PostgreSQL core regression test for Aggregates.


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

CREATE TYPE gbtreekey_var (
	INTERNALLENGTH = VARIABLE,
	INPUT  = gbtreekey_var_in,
	OUTPUT = gbtreekey_var_out,
	STORAGE = EXTENDED
);


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

select * from inttest where a not in (1::myint,2::myint,3::myint,4::myint,5::myint, null);

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

SELECT count(*) FROM (select * from inttest where a not in (1::myint,2::myint,3::myint,4::myint,5::myint, null)) AS _sub;


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

CREATE TABLE collate_test23 (f1 text collate mycoll2);

Explanation: DDL from PostgreSQL core regression test for Collate.


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

CREATE VIEW lock_view4 AS SELECT (select a from lock_tbl1a limit 1) from lock_tbl1;

Explanation: DDL from PostgreSQL core regression test for Lock.


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

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


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

Explanation: DML from PostgreSQL core regression test for Numeric.


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

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

SELECT count(*) FROM (select jsonb_path_match('[[1, true], [2, false]]', 'strict $[*] ? (@[0] < $x) [1]', '{"x": 2}')) AS _sub;


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

select ts_headline('{}'::jsonb, tsquery('aaa & bbb'));

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

SELECT count(*) FROM (select ts_headline('{}'::jsonb, tsquery('aaa & bbb'))) AS _sub;


Question: Show a SQL definition from the citus project (multi_partitioning, item 33).

-- 3-) Attaching non distributed table to a distributed table
CREATE TABLE partitioning_test_2012(id int, time date);


Question: pgTAP test for Coltap (assertion 24).

SELECT * FROM check_test(
    col_type_is( 'public', 'sometab', 'ctstz', 'pg_catalog'::name, 'timestamptz' ),
    true,
    'col_type_is( sch, tab, col, sch, type, desc )',
    'Column public.sometab.ctstz should be type pg_catalog.timestamptz',
    ''
);

Explanation: SQL assertion from pgTAP test suite for Coltap.


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

CREATE TABLE ATACC1 (a int, NOT NULL a NO INHERIT) PARTITION BY LIST (a);

Explanation: DDL from PostgreSQL core regression test for Constraints.


Question: Write the DDL statement from PostgreSQL regression test 'copy2' (example 193).

Explanation: DDL from PostgreSQL core regression test for Copy2.


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

SELECT JSON_VALUE(jsonb '1234', '$' RETURNING queryfuncs_d_varbit3  DEFAULT '111111' ON ERROR);

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

SELECT count(*) FROM (SELECT JSON_VALUE(jsonb '1234', '$' RETURNING queryfuncs_d_varbit3  DEFAULT '111111' ON ERROR)) AS _sub;


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

SELECT * FROM test_int2 WHERE i>1::int8 ORDER BY i;

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


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

INSERT INTO origin_tbl(data) VALUES ('no_lsn, commit');

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


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

INSERT INTO plt2_adv SELECT i, i, to_char(i % 10, 'FM0000') FROM generate_series(1, 299) i WHERE i % 10 IN (7, 9);

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


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

INSERT INTO bttest_multi SELECT i, i%2  FROM generate_series(1, 100000) as i;

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


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

-- gist key
CREATE FUNCTION gtrgm_in(cstring)
RETURNS gtrgm
AS 'MODULE_PATHNAME'
LANGUAGE C STRICT IMMUTABLE PARALLEL SAFE;

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


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

SELECT * FROM pg_input_error_info('6874898-01-01', 'date');

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

SELECT count(*) FROM (SELECT * FROM pg_input_error_info('6874898-01-01', 'date')) AS _sub;


Question: Write the DML statement from PostgreSQL regression test 'create_index' (example 202).

INSERT INTO func_index_heap VALUES('AB','CDEFG');

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