Question: PostgreSQL Perform: show example 3.

SELECT * FROM zipcodes WHERE city = 'San Francisco' AND zip = '94105';

Explanation: Example from PostgreSQL documentation on Perform.


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

INSERT INTO shoelace_data VALUES ('sl6', 0, 'brown', 0.9 , 'm');

Explanation: DML from PostgreSQL core regression test for Rules.


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

SELECT * FROM y2 JOIN test_qual_pushdown ON (b = abc) WHERE f_leak(abc);

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

SELECT count(*) FROM (SELECT * FROM y2 JOIN test_qual_pushdown ON (b = abc) WHERE f_leak(abc)) AS _sub;


Question: Write the DML statement from PostgreSQL regression test 'misc' (example 8).

UPDATE tmp
   SET stringu1 = reverse_name(onek.stringu1)
   FROM onek
   WHERE onek.stringu1 = 'JBAAAA' and
	  onek.stringu1 = tmp.stringu1;

Explanation: DML from PostgreSQL core regression test for Misc.


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

SELECT cashsmaller(m, '$124.00') FROM money_data;

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

SELECT count(*) FROM (SELECT cashsmaller(m, '$124.00') FROM money_data) AS _sub;


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

SELECT to_timestamp('  2000 +JUN', 'YYYY/MON');

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

SELECT count(*) FROM (SELECT to_timestamp('  2000 +JUN', 'YYYY/MON')) AS _sub;


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

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

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

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


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

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

SELECT count(*) FROM (SELECT to_number('.-01', 'S99.99')) AS _sub;


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

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

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


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

CREATE INDEX iprt1_e_p2_ab2 on prt1_e_p2(((a+b)/2));

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


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

CREATE USER regress_test_user_canlogin WITH NOLOGIN;

Explanation: DDL from PostgreSQL core regression test for Roleattributes.


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

-- single argument jsonb functions as jsonb_function(jsonb) and jsonb.jsonb_function
select jsonb_typeof('{"a":1}'::jsonb);

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


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

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

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

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


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

SELECT f1 AS two, (max(f3) + 1) AS max_plus_1, (min(f3) - 1) AS min_minus_1
  FROM TEMP_GROUP
  GROUP BY f1
  ORDER BY two, min_minus_1;

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

SELECT count(*) FROM (SELECT f1 AS two, (max(f3) + 1) AS max_plus_1, (min(f3) - 1) AS min_minus_1
  FROM TEMP_GROUP
  GROUP BY f1
  ORDER BY two, min_minus_1) AS _sub;


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

SELECT COUNT(*) FROM brin_test_multi_1 WHERE a >= 63;

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

SELECT count(*) FROM (SELECT COUNT(*) FROM brin_test_multi_1 WHERE a >= 63) AS _sub;


Question: Show a SQL definition from the pg_partman project (pg_partman--4.5.1--4.6.0, item 24).

CREATE OR REPLACE FUNCTION @extschema@.create_partition_id(p_parent_table text, p_partition_ids bigint[], p_analyze boolean DEFAULT true, p_start_partition text DEFAULT NULL) RETURNS boolean
    LANGUAGE plpgsql
    AS $$
DECLARE

ex_context              text;
ex_detail               text;
ex_hint                 text;
ex_message              text;
v_all                   text[] := ARRAY['SELECT', 'INSERT', 'UPDATE', 'DELETE', 'TRUNCATE', 'REFERENCES', 'TRIGGER'];
v_analyze               boolean := FALSE;
v_control               text;
v_control_type          text;
v_exists                text;
v_grantees              text[];
v_hasoids               boolean;
v_id                    bigint;
v_inherit_fk            boolean;
v_inherit_privileges    boolean;
v_job_id                bigint;
v_jobmon                boolean;
v_jobmon_schema         text;
v_new_search_path       text := '@extschema@,pg_temp';
v_old_search_path       text;
v_parent_grant          record;
v_parent_schema         text;
v_parent_tablename      text;
v_parent_tablespace     text;
v_partition_interval    bigint;
v_partition_created     boolean := false;
v_partition_name        text;
v_partition_type        text;
v_publications          text[];
v_revoke                text;
v_row                   record;
v_sql                   text;
v_step_id               bigint;
v_sub_control           text;
v_sub_partition_type    text;
v_sub_id_max            bigint;
v_sub_id_min            bigint;
v_template_table        text;
v_unlogged              char;

BEGIN
/*
 * Function to create id partitions
 */

SELECT control
    , partition_type
    , partition_interval
    , inherit_fk
    , jobmon
    , template_table
    , publications
    , inherit_privileges
INTO v_control
    , v_partition_type
    , v_partition_interval
    , v_inherit_fk
    , v_jobmon
    , v_template_table
    , v_publications
    , v_inherit_privileges
FROM @extschema@.part_config
WHERE parent_table = p_parent_table;

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

SELECT n.nspname, c.relname, t.spcname
INTO v_parent_schema, v_parent_tablename, v_parent_tablespace
FROM pg_catalog.pg_class c
JOIN pg_catalog.pg_namespace n ON c.relnamespace = n.oid
LEFT OUTER JOIN pg_catalog.pg_tablespace t ON c.reltablespace = t.oid
WHERE n.nspname = split_part(p_parent_table, '.', 1)::name

AND c.relname = split_part(p_parent_table, '.', 2)::name;

SELECT general_type INTO v_control_type FROM @extschema@.check_control_type(v_parent_schema, v_parent_tablename, v_control);
IF v_control_type <> 'id' THEN
    RAISE EXCEPTION 'ERROR: Given parent table is not set up for id/serial partitioning';
END IF;

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

-- Determine if this table is a child of a subpartition parent. If so, get limits of what child tables can be created based on parent suffix
SELECT sub_min::bigint, sub_max::bigint INTO v_sub_id_min, v_sub_id_max FROM @extschema@.check_subpartition_limits(p_parent_table, 'id');

IF v_jobmon_schema IS NOT NULL THEN
    v_job_id := add_job(format('PARTMAN CREATE TABLE: %s', p_parent_table));
END IF;

FOREACH v_id IN ARRAY p_partition_ids LOOP
-- Do not create the child table if it's outside the bounds of the top parent.
    IF v_sub_id_min IS NOT NULL THEN
        IF v_id < v_sub_id_min OR v_id >= v_sub_id_max THEN
            CONTINUE;
        END IF;
    END IF;

    v_partition_name := @extschema@.check_name_length(v_parent_tablename, v_id::text, TRUE);
    -- If child table already exists, skip creation
    -- Have to check pg_class because if subpartitioned, table will not be in pg_tables
    SELECT c.relname INTO v_exists
    FROM pg_catalog.pg_class c
    JOIN pg_catalog.pg_namespace n ON c.relnamespace = n.oid
    WHERE n.nspname = v_parent_schema::name AND c.relname = v_partition_name::name;
    IF v_exists IS NOT NULL THEN
        CONTINUE;
    END IF;

    -- Ensure analyze is run if a new partition is created. Otherwise if one isn't, will be false and analyze will be skipped
    v_analyze := TRUE;

    IF v_jobmon_schema IS NOT NULL THEN
        v_step_id := add_step(v_job_id, 'Creating new partition '||v_partition_name||' with interval from '||v_id||' to '||(v_id + v_partition_interval)-1);
    END IF;

    v_sql := 'CREATE';

    -- As of PG12, the unlogged/logged status of a native parent table cannot be changed via an ALTER TABLE in order to affect its children.
    -- As of v4.2x, the unlogged state will be managed via the template table
    SELECT relpersistence INTO v_unlogged
    FROM pg_catalog.pg_class c
    JOIN pg_catalog.pg_namespace n ON c.relnamespace = n.oid
    WHERE c.relname = v_parent_tablename::name
    AND n.nspname = v_parent_schema::name;
    IF v_unlogged = 'u' and v_partition_type != 'native'  THEN
        v_sql := v_sql || ' UNLOGGED';
    END IF;

    -- Close parentheses on LIKE are below due to differing requirements of native subpartitioning
    -- Same INCLUDING list is used in create_parent()
    v_sql := v_sql || format(' TABLE %I.%I (LIKE %I.%I INCLUDING DEFAULTS INCLUDING CONSTRAINTS INCLUDING STORAGE INCLUDING COMMENTS '
            , v_parent_schema
            , v_partition_name
            , v_parent_schema
            , v_parent_tablename);

    IF current_setting('server_version_num')::int >= 120000 THEN
        v_sql := v_sql || ' INCLUDING GENERATED ';
    END IF;

    SELECT sub_partition_type, sub_control INTO v_sub_partition_type, v_sub_control
    FROM @extschema@.part_config_sub
    WHERE sub_parent = p_parent_table;
    IF v_sub_partition_type = 'native' THEN
        -- INCLUDING INDEXES isn't necessary for native partitioning. It isn't supported in v10 and
	    --   for v11+ index inheritance is automatically handled when the partition is attached
        v_sql := v_sql || format(') PARTITION BY RANGE (%I) ', v_sub_control);
    ELSE
        v_sql := v_sql || format(' INCLUDING INDEXES) ', v_sub_control);
    END IF;

    IF current_setting('server_version_num')::int < 120000 THEN
        -- column removed from pgclass in pg12
        SELECT relhasoids INTO v_hasoids
        FROM pg_catalog.pg_class c
        JOIN pg_catalog.pg_namespace n ON c.relnamespace = n.oid
        WHERE c.relname = v_parent_tablename::name
        AND n.nspname = v_parent_schema::name;
        IF v_hasoids IS TRUE THEN
            v_sql := v_sql || ' WITH (OIDS)';
        END IF;
    END IF;

    RAISE DEBUG 'create_partition_id v_sql: %', v_sql;
    EXECUTE v_sql;

    IF v_partition_type = 'native' THEN

        IF current_setting('server_version_num')::int >= 120000 THEN
            -- PG12 fixed tablespace marking on the parent of a native partition set
            -- Versions older than 12 handle tablespace setting via inherit_template_properties() call below
            IF v_parent_tablespace IS NOT NULL THEN
                EXECUTE format('ALTER TABLE %I.%I SET TABLESPACE %I', v_parent_schema, v_partition_name, v_parent_tablespace);
            END IF;
        END IF;

        IF v_template_table IS NOT NULL THEN
            PERFORM @extschema@.inherit_template_properties(p_parent_table, v_parent_schema, v_partition_name);
        END IF;

        EXECUTE format('ALTER TABLE %I.%I ATTACH PARTITION %I.%I FOR VALUES FROM (%L) TO (%L)'
            , v_parent_schema
            , v_parent_tablename
            , v_parent_schema
            , v_partition_name
            , v_id
            , v_id + v_partition_interval);

    ELSE -- non-native

        IF v_parent_tablespace IS NOT NULL THEN
            EXECUTE format('ALTER TABLE %I.%I SET TABLESPACE %I', v_parent_schema, v_partition_name, v_parent_tablespace);
        END IF;

        EXECUTE format('ALTER TABLE %I.%I ADD CONSTRAINT %I CHECK (%I >= %s AND %I < %s )'
            , v_parent_schema
            , v_partition_name
            , v_partition_name||'_partition_check'
            , v_control
            , v_id
            , v_control
            , v_id + v_partition_interval);

        EXECUTE format('ALTER TABLE %I.%I INHERIT %I.%I', v_parent_schema, v_partition_name, v_parent_schema, v_parent_tablename);

        -- Indexes cannot be created on the parent, so clustering cannot be used for native yet.
        PERFORM @extschema@.apply_cluster(v_parent_schema, v_parent_tablename, v_parent_schema, v_partition_name);

        -- Foreign keys to other tables not supported on native parent tables
        IF v_inherit_fk THEN
            PERFORM @extschema@.apply_foreign_keys(p_parent_table, v_parent_schema||'.'||v_partition_name, v_job_id);
        END IF;

    END IF;

    -- NOTE: Privileges not automatically inherited for native. Only do so if config flag is set
    IF v_partition_type != 'native' OR (v_partition_type = 'native' AND v_inherit_privileges = TRUE) THEN
        PERFORM @extschema@.apply_privileges(v_parent_schema, v_parent_tablename, v_parent_schema, v_partition_name, v_job_id);
    END IF;

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

    -- Will only loop once and only if sub_partitioning is actually configured
    -- This seemed easier than assigning a bunch of variables then doing an IF condition
    -- This column list must be kept consistent between:
    --   create_parent, check_subpart_sameconfig, create_partition_id, create_partition_time, dump_partitioned_table_definition, and table definition
    FOR v_row IN
        SELECT sub_parent
            , sub_partition_type
            , sub_control
            , sub_partition_interval
            , sub_constraint_cols
            , sub_premake
            , sub_optimize_trigger
            , sub_optimize_constraint
            , sub_epoch
            , sub_inherit_fk
            , sub_retention
            , sub_retention_schema
            , sub_retention_keep_table
            , sub_retention_keep_index
            , sub_infinite_time_partitions
            , sub_automatic_maintenance
            , sub_jobmon
            , sub_trigger_exception_handling
            , sub_upsert
            , sub_trigger_return_null
            , sub_template_table
            , sub_inherit_privileges
            , sub_constraint_valid
            , sub_subscription_refresh
            , sub_date_trunc_interval
        FROM @extschema@.part_config_sub
        WHERE sub_parent = p_parent_table
    LOOP
        IF v_jobmon_schema IS NOT NULL THEN
            v_step_id := add_step(v_job_id, 'Subpartitioning '||v_partition_name);
        END IF;
        v_sql := format('SELECT @extschema@.create_parent(
                 p_parent_table := %L
                , p_control := %L
                , p_type := %L
                , p_interval := %L
                , p_constraint_cols := %L
                , p_premake := %L
                , p_automatic_maintenance := %L
                , p_inherit_fk := %L
                , p_epoch := %L
                , p_template_table := %L
                , p_jobmon := %L
                , p_start_partition := %L
                , p_date_trunc_interval := %L )'
            , v_parent_schema||'.'||v_partition_name
            , v_row.sub_control
            , v_row.sub_partition_type
            , v_row.sub_partition_interval
            , v_row.sub_constraint_cols
            , v_row.sub_premake
            , v_row.sub_automatic_maintenance
            , v_row.sub_inherit_fk
            , v_row.sub_epoch
            , v_row.sub_template_table
            , v_row.sub_jobmon
            , p_start_partition
            , v_row.sub_date_trunc_interval);
        RAISE DEBUG 'create_partition_id (create_parent loop): %', v_sql;
        EXECUTE v_sql;

        UPDATE @extschema@.part_config SET
            retention_schema = v_row.sub_retention_schema
            , retention_keep_table = v_row.sub_retention_keep_table
            , retention_keep_index = v_row.sub_retention_keep_index
            , optimize_trigger = v_row.sub_optimize_trigger
            , optimize_constraint = v_row.sub_optimize_constraint
            , infinite_time_partitions = v_row.sub_infinite_time_partitions
            , trigger_exception_handling = v_row.sub_trigger_exception_handling
            , upsert = v_row.sub_upsert
            , inherit_privileges = v_row.sub_inherit_privileges
            , trigger_return_null = v_row.sub_trigger_return_null
            , constraint_valid = v_row.sub_constraint_valid
            , subscription_refresh = v_row.sub_subscription_refresh
        WHERE parent_table = v_parent_schema||'.'||v_partition_name;

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

    END LOOP; -- end sub partitioning LOOP

    -- Manage additonal constraints if set
    PERFORM @extschema@.apply_constraints(p_parent_table, p_job_id := v_job_id);

    IF v_publications IS NOT NULL THEN
        -- NOTE: Publications currently not supported on parent table, but are supported on the table partitions if individually assigned.
        PERFORM @extschema@.apply_publications(p_parent_table, v_parent_schema, v_partition_name);
    END IF;

    v_partition_created := true;

END LOOP;

-- v_analyze is a local check if a new table is made.
-- p_analyze is a parameter to say whether to run the analyze at all. Used by create_parent() to avoid long exclusive lock or run_maintenence() to avoid long creation runs.
IF v_analyze AND p_analyze THEN
    IF v_jobmon_schema IS NOT NULL THEN
        v_step_id := add_step(v_job_id, format('Analyzing partition set: %s', p_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
    IF v_partition_created = false THEN
        v_step_id := add_step(v_job_id, format('No partitions created for partition set: %s', p_parent_table));
        PERFORM update_step(v_step_id, 'OK', 'Done');
    END IF;

    PERFORM close_job(v_job_id);
END IF;

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

RETURN v_partition_created;

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 TABLE: %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
$$;

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


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

SELECT * FROM JSON_TABLE(jsonb '{"d1": "foo"}', '$'
    COLUMNS (js1 jsonb_test_domain PATH '$.d1' DEFAULT 'foo2'::jsonb_test_domain ON ERROR));

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

SELECT count(*) FROM (SELECT * FROM JSON_TABLE(jsonb '{"d1": "foo"}', '$'
    COLUMNS (js1 jsonb_test_domain PATH '$.d1' DEFAULT 'foo2'::jsonb_test_domain ON ERROR))) AS _sub;


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

select numrange(1.0, 2.0) + numrange(1.5, 3.0);

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

SELECT count(*) FROM (select numrange(1.0, 2.0) + numrange(1.5, 3.0)) AS _sub;


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

-- hasnt_materialized_view( materialized_view, description )
CREATE OR REPLACE FUNCTION hasnt_materialized_view ( NAME, TEXT )
RETURNS TEXT AS $$
    SELECT ok( NOT _rexists( 'm', $1 ), $2 );
$$ LANGUAGE SQL;

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


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

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

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

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


Question: pgTAP test for Hastap (assertion 24).

SELECT * FROM check_test(
    has_schema( 'someschema', 'lol' ),
    true,
    'has_schema(schema, desc)',
    'lol',
    ''
);

Explanation: SQL assertion from pgTAP test suite for Hastap.


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

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

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


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

select * from generate_series(1::numeric, 3::numeric) i, generate_series(1,5,i) j;

SELECT count(*) FROM (select * from generate_series(1::numeric, 3::numeric) i, generate_series(1,5,i) j) AS _sub;


Question: Rank employees by salary within each department.

CREATE TABLE employees (id serial PRIMARY KEY, name text, department text, salary numeric(10,2));

SELECT name, department, salary, RANK() OVER (PARTITION BY department ORDER BY salary DESC) AS dept_rank FROM employees;

Explanation: RANK() window function partitioned by department, ordered by salary descending. Ties get the same rank.

SELECT department, count(*) FROM employees GROUP BY department;


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

SELECT to_json(a) AS a, JSON_OBJECTAGG(k : v ABSENT ON NULL)
OVER (ORDER BY k RANGE BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING)
FROM (VALUES (1,1), (1,null), (2,2)) a(k,v);

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

SELECT count(*) FROM (SELECT to_json(a) AS a, JSON_OBJECTAGG(k : v ABSENT ON NULL)
OVER (ORDER BY k RANGE BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING)
FROM (VALUES (1,1), (1,null), (2,2)) a(k,v)) AS _sub;


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

INSERT INTO temporal_mltrng (id, valid_at) VALUES ('[1,2)', datemultirange(daterange('2010-01-01', '2020-01-01'))) ON CONFLICT DO NOTHING;

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


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

CREATE TABLE h2part_3 PARTITION OF hash_parted2 FOR VALUES WITH (MODULUS 8, REMAINDER 4);

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


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

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

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


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

Explanation: DDL from PostgreSQL core regression test for Join.


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

INSERT INTO itestv11 OVERRIDING SYSTEM VALUE VALUES (11, 'xyz');

Explanation: DML from PostgreSQL core regression test for Identity.


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

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


Question: Show a SQL definition from the timescaledb project (plan_hypertable_inline, item 10).

-- test with CTE
-- these cases are just to make sure we're everything is alright with
-- the way we identify hypertables to prune chunks - we abuse ctename
-- for this purpose. So double-check if we're not breaking plans
-- with CTEs here.
CREATE OR REPLACE FUNCTION test_f(_ts bigint)
RETURNS SETOF test LANGUAGE SQL STABLE
as $f$
   WITH ct AS MATERIALIZED (
      SELECT DISTINCT ON (a) * FROM test WHERE b >= _ts AND b <= _ts + 2
   )
   SELECT * FROM ct
$f$;

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


Question: Show an example of PostgreSQL ALTER PROCEDURE (example 4).

ALTER PROCEDURE insert_data(integer, integer) DEPENDS ON EXTENSION myext;

Explanation: PostgreSQL ALTER PROCEDURE command.


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

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

SELECT count(*) FROM (select to_oct(-1234) AS "37777775456") AS _sub;


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

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


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

insert into arr_pk_tbl values (1, '{1,2,3}');

Explanation: DML from PostgreSQL core regression test for Arrays.


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

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

SELECT count(*) FROM (SELECT timestamp '1995-08-06 infinity') AS _sub;


Question: Write the DML statement from PostgreSQL regression test 'with' (example 25).

INSERT INTO department VALUES (6, 4, 'F');

Explanation: DML from PostgreSQL core regression test for With.


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

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


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


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

SELECT jsonb_exists('{"a":"null", "b":"qq"}', 'a');

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

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


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

SELECT 'xAb' !~* '[c-d]' COLLATE PG_C_UTF8;

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

SELECT count(*) FROM (SELECT 'xAb' !~* '[c-d]' COLLATE PG_C_UTF8) AS _sub;


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

INSERT INTO temporal_rng (id, valid_at) VALUES ('[1,2)', daterange('2000-01-01', '2010-01-01'));


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

CREATE OR REPLACE FUNCTION _timescaledb_functions.hypertable_local_size(
	schema_name_in name,
	table_name_in name)
RETURNS TABLE (
	table_bytes BIGINT,
	index_bytes BIGINT,
	toast_bytes BIGINT,
	total_bytes BIGINT)
LANGUAGE SQL VOLATILE STRICT AS
$BODY$
    /* get the main hypertable id and sizes */
    WITH _hypertable_sizes AS (
        SELECT
            id,
            COALESCE((relsize).total_size, 0) AS total_bytes,
            COALESCE((relsize).heap_size, 0) AS heap_bytes,
            COALESCE((relsize).index_size, 0) AS index_bytes,
            COALESCE((relsize).toast_size, 0) AS toast_bytes,
            0::BIGINT AS compressed_total_size,
            0::BIGINT AS compressed_index_size,
            0::BIGINT AS compressed_toast_size,
            0::BIGINT AS compressed_heap_size
        FROM
            _timescaledb_catalog.hypertable ht
            JOIN pg_class c ON relname = ht.table_name AND c.relkind = 'r'
            JOIN pg_namespace n ON n.oid = c.relnamespace
            AND n.nspname = ht.schema_name
            JOIN LATERAL _timescaledb_functions.relation_size(c.oid) AS relsize ON TRUE
        WHERE
            schema_name = schema_name_in
            AND table_name = table_name_in
    ),
    /* calculate the size of the hypertable chunks */
    _chunk_sizes AS (
        SELECT
            chunk_id,
            COALESCE(ch.total_bytes, 0) AS total_bytes,
            COALESCE(ch.heap_bytes, 0) AS heap_bytes,
            COALESCE(ch.index_bytes, 0) AS index_bytes,
            COALESCE(ch.toast_bytes, 0) AS toast_bytes,
            COALESCE(ch.compressed_total_size, 0) AS compressed_total_size,
            COALESCE(ch.compressed_index_size, 0) AS compressed_index_size,
            COALESCE(ch.compressed_toast_size, 0) AS compressed_toast_size,
            COALESCE(ch.compressed_heap_size, 0) AS compressed_heap_size
        FROM
            _timescaledb_internal.hypertable_chunk_local_size ch
            JOIN _hypertable_sizes ht ON ht.id = ch.hypertable_id
        WHERE hypertable_schema = schema_name_in
          AND hypertable_name = table_name_in
    )
    /* calculate the SUM of the hypertable and chunk sizes */
	SELECT
		(SUM(heap_bytes)  + SUM(compressed_heap_size))::BIGINT AS heap_bytes,
		(SUM(index_bytes) + SUM(compressed_index_size))::BIGINT AS index_bytes,
		(SUM(toast_bytes) + SUM(compressed_toast_size))::BIGINT AS toast_bytes,
		(SUM(total_bytes) + SUM(compressed_total_size))::BIGINT AS total_bytes
	FROM
		(SELECT * FROM _hypertable_sizes
         UNION ALL
         SELECT * FROM _chunk_sizes) AS sizes;


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

SELECT count(*) from more__int WHERE a @> '{20,23}' or a @> '{50,68}';

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


Question: Show a SQL definition from the citus project (issue_5099, item 3).

CREATE TYPE comp_type AS (
    int_field_1 BIGINT,
    int_field_2 BIGINT
);

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


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

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


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

CREATE TRIGGER indtoasttest_update_indirect
        BEFORE INSERT OR UPDATE
        ON indtoasttest
        FOR EACH ROW
        EXECUTE PROCEDURE update_using_indirect();

Explanation: DDL from PostgreSQL core regression test for Indirect Toast.


Question: Show a SQL definition from the pglogical project (preseed, item 23).

\c :provider1_dsn
CREATE OR REPLACE FUNCTION public.pglogical_regress_variables(
    OUT orig_provider_dsn text,
    OUT provider_dsn text,
    OUT provider1_dsn text,
    OUT subscriber_dsn text
    ) RETURNS record LANGUAGE SQL AS $f$
SELECT
    current_setting('pglogical.orig_provider_dsn'),
    current_setting('pglogical.provider_dsn'),
    current_setting('pglogical.provider1_dsn'),
    current_setting('pglogical.subscriber_dsn')
$f$;

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


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


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

SELECT amname FROM pg_class c, pg_am am
  WHERE c.relam = am.oid AND c.oid = 'heapmv'::regclass;

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

SELECT count(*) FROM (SELECT amname FROM pg_class c, pg_am am
  WHERE c.relam = am.oid AND c.oid = 'heapmv'::regclass) AS _sub;


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

select ('[{"name": "alice"}, {"name": "bob"}]'::jsonb)::name;

SELECT count(*) FROM (select ('[{"name": "alice"}, {"name": "bob"}]'::jsonb)::name) AS _sub;


Question: PL/pgSQL test: Plperl Call (example 3).

CREATE PROCEDURE test_proc2()
LANGUAGE plperl
AS $$
return 5
$$;

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


Question: PostgreSQL Ddl: show example 27.

CREATE TABLE products ( product_no integer UNIQUE NULLS NOT DISTINCT , name text, price numeric );

Explanation: Example from PostgreSQL documentation on Ddl.


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

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

SELECT count(*) FROM (SELECT '0/16AE7F7'::pg_lsn - '0/16AE7F8'::pg_lsn) AS _sub;


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

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

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


Question: Write the DDL statement from PostgreSQL regression test 'merge' (example 443).

CREATE TABLE pa_source (sid integer, delta float)
  WITH (autovacuum_enabled=off);

Explanation: DDL from PostgreSQL core regression test for Merge.


Question: PostgreSQL regression test 'domain': Write the SELECT query (example 103).

select row(0,1)::dcomptype;  -- fail

alter type comptype alter attribute r type varchar;  -- fail
alter type comptype alter attribute r type bigint;

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

SELECT count(*) FROM (select row(0,1)::dcomptype;  -- fail

alter type comptype alter attribute r type varchar;  -- fail
alter type comptype alter attribute r type bigint) AS _sub;


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

CREATE STATISTICS s12 (ndistinct) ON c, d, (c * 10), (d - 1) FROM ndistinct;

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


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

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

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


Question: PostgreSQL regression test 'partition_aggregate': Write the SELECT query (example 78).

SELECT a, sum(b), avg(c), count(*) FROM pagg_tab_m GROUP BY a HAVING avg(c) < 22 ORDER BY 1, 2, 3;

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

SELECT count(*) FROM (SELECT a, sum(b), avg(c), count(*) FROM pagg_tab_m GROUP BY a HAVING avg(c) < 22 ORDER BY 1, 2, 3) AS _sub;


Question: Write the DDL statement from PostgreSQL regression test 'subselect' (example 140).

create temp table tb (id int primary key, aval int);

Explanation: DDL from PostgreSQL core regression test for Subselect.


Question: Write the DML statement from PostgreSQL regression test 'oid' (example 15).

INSERT INTO OID_TBL(f1) VALUES ('    5d');

Explanation: DML from PostgreSQL core regression test for Oid.


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

-- ALL (should not benefit from functional dependencies)
SELECT * FROM check_estimated_rows('SELECT * FROM functional_dependencies WHERE a IN (1, 51) AND b = ALL (ARRAY[''1''])');

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


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

SELECT * FROM pg_input_error_info('[(1,2),(3)]', 'path');

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

SELECT count(*) FROM (SELECT * FROM pg_input_error_info('[(1,2),(3)]', 'path')) AS _sub;


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

SELECT * FROM test_type_conversion_int4(-100);

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


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

CREATE TABLE upsert_test_2 (b TEXT, a INT PRIMARY KEY);

Explanation: DDL from PostgreSQL core regression test for Update.


Question: PL/pgSQL test: Plperl Plperlu (example 15).

-- make sure our overloaded require op gets restored/set correctly
select use_plperlu();

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


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

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


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

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

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


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

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

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


Question: pgTAP test for Aretap (assertion 109).

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

Explanation: SQL assertion from pgTAP test suite for Aretap.


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

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

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

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


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

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

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


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

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

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

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


Question: pgTAP test for Ownership (assertion 93).

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

Explanation: SQL assertion from pgTAP test suite for Ownership.


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

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

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

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


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

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

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

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


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

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

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


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

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

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

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


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

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

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

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


Question: PostgreSQL Plpgsql: show example 67.

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

Explanation: Example from PostgreSQL documentation on Plpgsql.


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

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


Question: pgTAP test for Functap (assertion 280).

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

Explanation: SQL assertion from pgTAP test suite for Functap.


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

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

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


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

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

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


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

INSERT INTO BIT_SHIFT_TABLE VALUES (B'1101100000000000');

Explanation: DML from PostgreSQL core regression test for Bit.


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

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

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

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


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

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

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

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


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

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


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

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


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

ALTER EXTENSION pgtap ADD FUNCTION todo ( how_many int );

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


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

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

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


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

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

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


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

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

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


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

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


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

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

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


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

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


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

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

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

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


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

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

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

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


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

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

Explanation: DDL from PostgreSQL core regression test for Xmlmap.


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

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

Explanation: DDL from PostgreSQL core regression test for Constraints.


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

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

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


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

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

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

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


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

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

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


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

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

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


Question: pgTAP test for Resultset (assertion 52).

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

Explanation: SQL assertion from pgTAP test suite for Resultset.


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

\getenv abs_srcdir PG_ABS_SRCDIR
\getenv abs_builddir PG_ABS_BUILDDIR

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

CREATE TABLE copy1 (a int, b float);

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


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

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

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

BEGIN

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

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

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

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

    CONTINUE WHEN v_row.undo_in_progress;

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

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

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

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

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

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

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

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

END LOOP; -- end of creation loop

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

IF v_jobmon_schema IS NOT NULL THEN
    PERFORM update_step(v_step_id, 'OK', 'Partition maintenance finished. '||v_create_count||' partitions made. '||v_drop_count||' partitions dropped.');
    IF v_step_overflow_id IS NOT NULL OR v_step_serial_id IS NOT NULL THEN
        PERFORM fail_job(v_job_id);
    ELSE
        PERFORM close_job(v_job_id);
    END IF;
    EXECUTE 'SELECT set_config(''search_path'','''||v_old_search_path||''',''false'')';
END IF;

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

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


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

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

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


Question: pgTAP test for Resultset (assertion 285).

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


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

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

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

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


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

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

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


Question: PostgreSQL Ddl: show example 36.

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

Explanation: Example from PostgreSQL documentation on Ddl.


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

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

Explanation: DML from PostgreSQL core regression test for Oid8.


Question: PostgreSQL Plpgsql: show example 73.

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

Explanation: Example from PostgreSQL documentation on Plpgsql.


Question: pgTAP test for Check (assertion 22).

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

Explanation: SQL assertion from pgTAP test suite for Check.


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

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

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


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

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

Explanation: DML from PostgreSQL core regression test for Returning.


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

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

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

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


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

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

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

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


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

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

Explanation: DDL from PostgreSQL core regression test for Psql.


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

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

Explanation: DDL from PostgreSQL core regression test for Tablespace.


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

create unique index fruit_index on insertconflicttest(fruit);

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


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

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

Explanation: DML from PostgreSQL core regression test for Subselect.


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

Explanation: DML from PostgreSQL core regression test for Numeric.


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

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

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


Question: pgTAP test for Inheritance (assertion 135).

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

Explanation: SQL assertion from pgTAP test suite for Inheritance.


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

SELECT xmlserialize(CONTENT  '' AS text INDENT);

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

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


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

Explanation: DDL from PostgreSQL core regression test for Temp.


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

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

Explanation: DDL from PostgreSQL core regression test for Polymorphism.


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

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

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


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

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

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


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

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

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


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

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


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

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


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

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

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


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

INSERT INTO PG_LSN_TBL VALUES ('ABCD/');

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


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

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

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

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


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

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

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


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

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

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


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

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

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

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


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

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

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


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

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

Explanation: DDL from PostgreSQL core regression test for Aggregates.


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

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

Explanation: DML from PostgreSQL core regression test for Subselect.


Question: PostgreSQL Xfunc: show example 42.

Explanation: Example from PostgreSQL documentation on Xfunc.


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

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

Explanation: PostgreSQL MERGE command.


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

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


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

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

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


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

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

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


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

$$;

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

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

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

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

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

ALTER TABLE gtest28a DROP COLUMN a;

CREATE TABLE gtest28b (LIKE gtest28a INCLUDING GENERATED);

\d gtest28*

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

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


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

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

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

BEGIN

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

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

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

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

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

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

END IF;

END
$$;

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


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

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


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

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


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

CREATE UNIQUE INDEX num_exp_sqrt_idx ON num_exp_sqrt (id);

Explanation: DDL from PostgreSQL core regression test for Numeric.


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

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

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


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

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

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

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


Question: pgTAP test for Enumtap (assertion 19).

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

Explanation: SQL assertion from pgTAP test suite for Enumtap.


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

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

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

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


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

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

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


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

SELECT f1
   FROM BOOLTBL1
   WHERE f1 IS FALSE;

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

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


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

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

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


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

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


Question: PostgreSQL Rules: show example 27.

Explanation: Example from PostgreSQL documentation on Rules.


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

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

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

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


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

ALTER TABLESPACE index_space RENAME TO fast_raid;

Explanation: PostgreSQL ALTER TABLESPACE command.


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

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

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


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

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

drop function polyf(x anyarray);

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

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

drop function polyf(x anyarray)) AS _sub;


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

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

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


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

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

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


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

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

Explanation: DDL from PostgreSQL core regression test for Temp.


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


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

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


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

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

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

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


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

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

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


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

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

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

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


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

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


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

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

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


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

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

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

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


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

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

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


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

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


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

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

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


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

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

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


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

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

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


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

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


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

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

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

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


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

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

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


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

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


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

end
$$ language plpgsql;

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

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

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


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

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

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


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

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

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


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

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

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

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


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

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

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


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

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

Explanation: DDL from PostgreSQL core regression test for Plpgsql.


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

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


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

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


Question: pgTAP test for Check (assertion 11).

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

Explanation: SQL assertion from pgTAP test suite for Check.


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

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

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

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


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

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

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

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


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

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

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


Question: pgTAP test for Ownership (assertion 82).

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

Explanation: SQL assertion from pgTAP test suite for Ownership.


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

create index minmaxtesti on minmaxtest(f1);

Explanation: DDL from PostgreSQL core regression test for Aggregates.


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

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

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

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


Question: PostgreSQL Queries: show example 36.

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

Explanation: Example from PostgreSQL documentation on Queries.


Question: pgTAP test for Hastap (assertion 51).

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

Explanation: SQL assertion from pgTAP test suite for Hastap.


Question: PostgreSQL Xfunc: show example 22.

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

Explanation: Example from PostgreSQL documentation on Xfunc.


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

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

Explanation: DML from PostgreSQL core regression test for Timetz.


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

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


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

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

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


Question: pgTAP test for Hastap (assertion 287).

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


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

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

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


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

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

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


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

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

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

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

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


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

select interval '-2147483648 months -0.1 yrs';

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

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


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

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

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


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

select interval '-0.1 yrs -2147483648 months';

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


Question: pgTAP test for Fktap (assertion 21).

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

Explanation: SQL assertion from pgTAP test suite for Fktap.


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

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

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

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


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

Explanation: DML from PostgreSQL core regression test for Numeric.


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

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

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

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


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

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

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

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


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

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

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


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

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

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


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

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

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


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

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

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

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


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

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

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

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


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

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


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

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


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

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

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

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


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

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

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


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

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

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


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

ALTER EXTENSION pgtap ADD FUNCTION _lang ( NAME );

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