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

SELECT encrypt('\xffffffffffffffff', '\x0000000000000000', 'bf-ecb/pad:none');

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


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

SELECT * FROM pg_input_error_info('no_such_dictionary', 'regdictionary');

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

SELECT count(*) FROM (SELECT * FROM pg_input_error_info('no_such_dictionary', 'regdictionary')) AS _sub;


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

Explanation: DML from PostgreSQL core regression test for Rules.


Question: PostgreSQL regression test 'geometry': Write the SELECT query (example 161).

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

SELECT count(*) FROM (SELECT pg_input_is_valid('(1,2),-1', 'circle')) AS _sub;


Question: Show an example of PostgreSQL ALTER FOREIGN DATA WRAPPER (example 2).

ALTER FOREIGN DATA WRAPPER dbi VALIDATOR bob.myvalidator;

Explanation: PostgreSQL ALTER FOREIGN DATA WRAPPER command.


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

SELECT count(*) FROM int2tmp WHERE a >= 237;

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


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

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

SELECT count(*) FROM (SELECT regexp_split_to_array('123456','')) AS _sub;


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

CREATE UNIQUE INDEX unique_idx1 ON unique_tbl (i) NULLS DISTINCT;

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


Question: Show a SQL definition from the timescaledb project (gapfill, item 11).

CREATE OR REPLACE FUNCTION @extschema@.interpolate(value BIGINT,prev RECORD=NULL,next RECORD=NULL) RETURNS BIGINT
	AS '@MODULE_PATHNAME@', 'ts_gapfill_marker' LANGUAGE C VOLATILE PARALLEL SAFE;

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


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

SELECT i AS interval, date_trunc('ago', i)
    FROM INFINITE_INTERVAL_TBL
    WHERE NOT isfinite(i);

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

SELECT count(*) FROM (SELECT i AS interval, date_trunc('ago', i)
    FROM INFINITE_INTERVAL_TBL
    WHERE NOT isfinite(i)) AS _sub;


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

SELECT * FROM pg_input_error_info('{"a": 1}', 'pg_dependencies');

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

SELECT count(*) FROM (SELECT * FROM pg_input_error_info('{"a": 1}', 'pg_dependencies')) AS _sub;


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

select(select (select grouping(a,b) from (values (1)) v2(c)) from (values (1,2)) v1(a,b) group by (a,b)) from (values(6,7)) v3(e,f) GROUP BY ROLLUP((e+1),(f+1));

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

SELECT count(*) FROM (select(select (select grouping(a,b) from (values (1)) v2(c)) from (values (1,2)) v1(a,b) group by (a,b)) from (values(6,7)) v3(e,f) GROUP BY ROLLUP((e+1),(f+1))) AS _sub;


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

ALTER FUNCTION foo_from_bar(TEXT, TEXT, TEXT)
  SUPPORT test_inline_in_from_support_func;

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


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

select array_agg(nullif(ten, 4)) from (select ten from tenk1 where unique1 < 15 order by unique1) ss;

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

SELECT count(*) FROM (select array_agg(nullif(ten, 4)) from (select ten from tenk1 where unique1 < 15 order by unique1) ss) AS _sub;


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

SELECT JSON_VALUE(jsonb '1', 'lax $.a' DEFAULT '2' ON EMPTY);

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

SELECT count(*) FROM (SELECT JSON_VALUE(jsonb '1', 'lax $.a' DEFAULT '2' ON EMPTY)) AS _sub;


Question: PL/pgSQL test: Plperl Array (example 14).

CREATE OR REPLACE FUNCTION plperl_array_of_rows(foo[]) RETURNS TEXT AS $$
	my $array_arg = shift;
	my $result = "";

	for my $row_ref (@$array_arg) {
		die "not a hash reference" unless (ref $row_ref eq "HASH");
			$result .= $row_ref->{bar}." items of ".$row_ref->{baz}.";";
	}
	return $result .' '. $array_arg;
$$ LANGUAGE plperl;

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


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

DELETE FROM foo WHERE f1 = 4 RETURNING old.*,new.*, *;

Explanation: DML from PostgreSQL core regression test for Returning.


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

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

SELECT count(*) FROM (SELECT 'infinity'::float4) AS _sub;


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

SELECT relispopulated FROM pg_class WHERE oid = 'mvtest_tm'::regclass;

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

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


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

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


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

Explanation: Regression test for Generated Stored in PostgreSQL core test suite.

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


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

Explanation: DML from PostgreSQL core regression test for Numeric.


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

end $$
language plpgsql
set work_mem = '1MB';

select myfunc(0), current_setting('work_mem');

alter function myfunc(int) reset all;

select myfunc(0), current_setting('work_mem');

set work_mem = '3MB';

-- but SET isn't
create or replace function myfunc(int) returns text as $$
begin
  set work_mem = '2MB';

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


Question: Write the DDL statement from PostgreSQL regression test 'brin' (example 96).

CREATE FUNCTION brintest_func() RETURNS int LANGUAGE sql IMMUTABLE RETURN 0;

Explanation: DDL from PostgreSQL core regression test for Brin.


Question: PostgreSQL regression test 'btree_index': Write the SELECT query (example 80).

select * from btree_bpchar where f1 like 'foo';

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

SELECT count(*) FROM (select * from btree_bpchar where f1 like 'foo') AS _sub;


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

SELECT '2014-10-26 02:00:00'::timestamp AT TIME ZONE 'Europe/Moscow';

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

SELECT count(*) FROM (SELECT '2014-10-26 02:00:00'::timestamp AT TIME ZONE 'Europe/Moscow') AS _sub;


Question: PostgreSQL Plpgsql: show example 85.

SELECT * FROM cs_parse_url('http://foobar.com/query.cgi?baz');

Explanation: Example from PostgreSQL documentation on Plpgsql.


Question: PL/pgSQL test: Plpython Void (example 4).

-- Tests for functions returning void
SELECT test_void_func1(), test_void_func1() IS NULL AS "is null";

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


Question: pgTAP test for Resultset (assertion 287).

SELECT * FROM check_test(
    results_eq(
        'SELECT id, name FROM dupes LIMIT 2',
        'SELECT id, name FROM dupes LIMIT 2'
    ),
    true,
    'results_eq(nulls, nulls)',
    '',
    ''
);

Explanation: SQL assertion from pgTAP test suite for Resultset.


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

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

SELECT count(*) FROM (select pg_get_viewdef('tt201v', true)) AS _sub;


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

-- we still do not support update/delete operations through foreign constraints if the foreign key includes the distribution column
-- All should fail
CREATE TABLE referencing_table(id int, ref_id int);

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


Question: pgTAP test for Proctap (assertion 13).

SELECT * FROM check_test(
    is_procedure( 'procschema', 'afunc', '{}'::name[], 'whatever' ),
    false,
    'is_procedure(schema, func, noargs, desc)',
    'whatever',
    ''
);

Explanation: SQL assertion from pgTAP test suite for Proctap.


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

insert into rem1(f2) values('hi remote');

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


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

create view v3 as select * from tt2 join tt3 using (b,c) full join tt4 using (b);

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


Question: Show a SQL definition from the postgrest project (jwt, item 9).

CREATE OR REPLACE FUNCTION jwt.sign(payload json, secret text, algorithm text DEFAULT 'HS256')
RETURNS text LANGUAGE sql AS $$
WITH
  header AS (
    SELECT jwt.url_encode(convert_to('{"alg":"' || algorithm || '","typ":"JWT"}', 'utf8'))
    ),
  payload AS (
    SELECT jwt.url_encode(convert_to(payload::text, 'utf8'))
    ),
  signables AS (
    SELECT (SELECT * FROM header) || '.' || (SELECT * FROM payload)
    )
SELECT
    (SELECT * FROM signables)
    || '.' ||
    jwt.algorithm_sign((SELECT * FROM signables), secret, algorithm);
$$;

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


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

/*
 * Function to list all child partitions in a set in logical order.
 */
CREATE OR REPLACE 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_quarter               text;
v_type                  text;
v_year                  text;

BEGIN

IF upper(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 = split_part(p_parent_table, '.', 1)::name
AND tablename = split_part(p_parent_table, '.', 2)::name;

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

    IF v_partition_interval::interval <> '3 months' OR (v_partition_interval::interval = '3 months' AND v_type = '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);
    ELSE
        -- For quarterly, to_timestamp() doesn't recognize "Q" in datetime string.
        -- First order by just the year, then order by the quarter number (should be last character in table name)
        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) for 4), ''YYYY'') %s
            , substring(reverse(c.relname) from 1 for 1) %s'
            , v_parent_schema
            , v_parent_tablename
            , p_order
            , p_order);
    END IF;

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: PostgreSQL regression test 'case': Write the SELECT query (example 25).

SELECT i AS "Value",
  CASE WHEN (i < 0) THEN 'small'
       WHEN (i = 0) THEN 'zero'
       WHEN (i = 1) THEN 'one'
       WHEN (i = 2) THEN 'two'
       ELSE 'big'
  END AS "Category"
  FROM CASE_TBL;

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

SELECT count(*) FROM (SELECT i AS "Value",
  CASE WHEN (i < 0) THEN 'small'
       WHEN (i = 0) THEN 'zero'
       WHEN (i = 1) THEN 'one'
       WHEN (i = 2) THEN 'two'
       ELSE 'big'
  END AS "Category"
  FROM CASE_TBL) AS _sub;


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

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

SELECT count(*) FROM (select jsonb_set_lax('{"a":1,"b":2}','{d}','6', true) ) AS _sub;


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

SELECT * FROM ts1;		-- ok
SELECT * FROM ts2;		-- failed (relation not found)
SELECT * FROM my_schema_2.ts2;	-- failed (policy violation)

--
-- Clean up
--
-- @SECURITY-CONTEXT=unconfined_u:unconfined_r:sepgsql_regtest_superuser_t:s0-s0:c0.c255
DROP TABLE IF EXISTS t1 CASCADE;

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


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

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

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


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

CREATE OPERATOR !~ (
    PROCEDURE = texticregexne,
    LEFTARG   = citext,
    RIGHTARG  = text,
    NEGATOR   = ~,
    RESTRICT  = icregexnesel,
    JOIN      = icregexnejoinsel
);

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


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

SELECT * FROM my_property_secure WHERE f_leak(passwd);

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

SELECT count(*) FROM (SELECT * FROM my_property_secure WHERE f_leak(passwd)) AS _sub;


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

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

SELECT count(*) FROM (select '$ ? (@.a < -0.1e-1)'::jsonpath) AS _sub;


Question: Write the DML statement from PostgreSQL regression test 'predicate' (example 116).

INSERT INTO bool_tab VALUES (1, true,  true);

Explanation: DML from PostgreSQL core regression test for Predicate.


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

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

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


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

SELECT table_name, column_name, dependent_column FROM information_schema.column_column_usage WHERE table_schema = 'generated_stored_tests' ORDER BY 1, 2, 3;

Explanation: Regression test for Generated Stored in PostgreSQL core test suite.

SELECT count(*) FROM (SELECT table_name, column_name, dependent_column FROM information_schema.column_column_usage WHERE table_schema = 'generated_stored_tests' ORDER BY 1, 2, 3) AS _sub;


Question: Write the DML statement from PostgreSQL regression test 'window' (example 239).

DELETE FROM empsalary RETURNING rank() OVER (ORDER BY random());

Explanation: DML from PostgreSQL core regression test for Window.


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

CREATE TABLE tgt (a int, b int, c int, d int);

Explanation: DDL from PostgreSQL core regression test for Merge.


Question: PostgreSQL Perform: show example 36.

EXPLAIN ANALYZE SELECT * FROM tenk1 WHERE thousand IN (1, 2, 3, 4); QUERY PLAN -------------------------------------------------------------------&zwsp;--------------------------------------------------------------- Bitmap Heap Scan on tenk1 (cost=9.45..73.44 rows=40 width=244) (actual time=0.009..0.019 rows=40.00 loops=1) Recheck Cond: (thousand = ANY ('{1,2,3,4}'::integer[])) Heap Blocks: exact=38 Buffers: shared hit=40 -> Bitmap Index Scan on tenk1_thous_tenthous (cost=0.00..9.44 rows=40 width=0) (actual time=0.005..0.005 rows=40.00 loops=1) Index Cond: (thousand = ANY ('{1,2,3,4}'::integer[])) Index Searches: 1 Buffers: shared hit=2 Planning Time: 0.029 ms Execution Time: 0.026 ms;

Explanation: Example from PostgreSQL documentation on Perform.


Question: Show a SQL definition from the pg_partman project (pg_partman--0.4.2--1.0.0, item 8).

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

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

BEGIN

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

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

FOREACH v_time IN ARRAY p_partition_times LOOP

    v_partition_name := p_parent_table || '_p';

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

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

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

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

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

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

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

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

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

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

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

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

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

END LOOP;

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

RETURN v_partition_name;

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


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

create view alter1.v1 as select * from alter1.t1;

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


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

insert into selfconflict values (12,1), (12,2) on conflict(f1) do select for update returning *;

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


Question: Show a query using PostgreSQL contrib extension 'file_fdw' (example 36).

SELECT * FROM agg_csv c JOIN agg_text t ON (t.a = c.a) ORDER BY c.a;

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


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

insert into parted values (1, 1, 'uno uno v1');    -- works
create trigger t before insert or update or delete on parted
  for each row execute function parted_trigfunc();

Explanation: DML from PostgreSQL core regression test for Triggers.


Question: Show a SQL definition from the pg_partman project (pg_partman--5.1.0--5.2.0, item 19).

CREATE OR REPLACE FUNCTION @extschema@.create_partition_id(
    p_parent_table text
    , p_partition_ids bigint[]
    , 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_control                       text;
v_control_type                  text;
v_exists                        text;
v_id                            bigint;
v_inherit_privileges            boolean;
v_job_id                        bigint;
v_jobmon                        boolean;
v_jobmon_schema                 text;
v_new_search_path               text;
v_old_search_path               text;
v_parent_oid                    oid;
v_parent_schema                 text;
v_parent_tablename              text;
v_parent_tablespace             name;
v_partition_interval            bigint;
v_partition_created             boolean := false;
v_partition_name                text;
v_partition_type                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;

BEGIN
/*
 * Function to create id partitions
 */

SELECT control
    , partition_interval::bigint -- this shared field also used in partition_time as interval
    , partition_type
    , jobmon
    , template_table
    , inherit_privileges
INTO v_control
    , v_partition_interval
    , v_partition_type
    , v_jobmon
    , v_template_table
    , 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
    , c.oid
    , t.spcname
INTO v_parent_schema
    , v_parent_tablename
    , v_parent_oid
    , 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 length(v_old_search_path) > 0 THEN
   v_new_search_path := '@extschema@,pg_temp,'||v_old_search_path;
ELSE
    v_new_search_path := '@extschema@,pg_temp';
END IF;
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 := format('%s,%s',v_jobmon_schema, v_new_search_path);
    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;

    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;

    -- Same INCLUDING list is used in create_parent()
    v_sql := format('CREATE TABLE %I.%I (LIKE %I.%I  INCLUDING COMMENTS INCLUDING COMPRESSION INCLUDING CONSTRAINTS INCLUDING DEFAULTS INCLUDING GENERATED INCLUDING STATISTICS INCLUDING STORAGE) '
            , v_parent_schema
            , v_partition_name
            , v_parent_schema
            , v_parent_tablename);

    IF v_parent_tablespace IS NOT NULL THEN
        v_sql := format('%s TABLESPACE %I ', v_sql, v_parent_tablespace);
    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 = 'range' THEN
        v_sql :=  format('%s PARTITION BY RANGE (%I) ', v_sql, v_sub_control);
    ELSIF v_sub_partition_type = 'list' THEN
        v_sql :=  format('%s PARTITION BY LIST (%I) ', v_sql, v_sub_control);
    END IF;

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

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

    IF v_partition_type = 'range' THEN
        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);
    ELSIF v_partition_type = 'list' THEN
        EXECUTE format('ALTER TABLE %I.%I ATTACH PARTITION %I.%I FOR VALUES IN (%L)'
            , v_parent_schema
            , v_parent_tablename
            , v_parent_schema
            , v_partition_name
            , v_id);
    ELSE
        RAISE EXCEPTION 'create_partition_id: Unexpected partition type (%) encountered in part_config table for parent table %', v_partition_type, p_parent_table;
    END IF;

    -- NOTE: Privileges not automatically inherited. Only do so if config flag is set
    IF 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_control
            , sub_time_encoder
            , sub_time_decoder
            , sub_partition_interval
            , sub_partition_type
            , sub_premake
            , sub_automatic_maintenance
            , sub_template_table
            , sub_retention
            , sub_retention_schema
            , sub_retention_keep_index
            , sub_retention_keep_table
            , sub_epoch
            , sub_constraint_cols
            , sub_optimize_constraint
            , sub_infinite_time_partitions
            , sub_jobmon
            , sub_inherit_privileges
            , sub_constraint_valid
            , sub_date_trunc_interval
            , sub_ignore_default_data
            , sub_default_table
            , sub_maintenance_order
            , sub_retention_keep_publication
            , sub_control_not_null
        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_time_encoder := %L
                , p_time_decoder := %L
                , p_type := %L
                , p_interval := %L
                , p_default_table := %L
                , p_constraint_cols := %L
                , p_premake := %L
                , p_automatic_maintenance := %L
                , p_epoch := %L
                , p_template_table := %L
                , p_jobmon := %L
                , p_start_partition := %L
                , p_date_trunc_interval := %L
                , p_control_not_null := %L )'
            , v_parent_schema||'.'||v_partition_name
            , v_row.sub_control
            , v_row.sub_time_encoder
            , v_row.sub_time_decoder
            , v_row.sub_partition_type
            , v_row.sub_partition_interval
            , v_row.sub_default_table
            , v_row.sub_constraint_cols
            , v_row.sub_premake
            , v_row.sub_automatic_maintenance
            , v_row.sub_epoch
            , v_row.sub_template_table
            , v_row.sub_jobmon
            , p_start_partition
            , v_row.sub_date_trunc_interval
            , v_row.sub_control_not_null);
        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
            , optimize_constraint = v_row.sub_optimize_constraint
            , infinite_time_partitions = v_row.sub_infinite_time_partitions
            , inherit_privileges = v_row.sub_inherit_privileges
            , constraint_valid = v_row.sub_constraint_valid
            , ignore_default_data = v_row.sub_ignore_default_data
            , maintenance_order = v_row.sub_maintenance_order
            , retention_keep_publication = v_row.sub_retention_keep_publication
        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

    -- NOTE: Replication identity not automatically inherited as of PG16 (revisit in future versions)
    PERFORM @extschema@.inherit_replica_identity(v_parent_schema, v_parent_tablename, v_partition_name);

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

    v_partition_created := true;

END LOOP;

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: Show a query using PostgreSQL contrib extension 'fuzzystrmatch' (example 13).

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


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

CREATE TABLE itest15 (id integer NOT NULL GENERATED ALWAYS AS IDENTITY);

Explanation: DDL from PostgreSQL core regression test for Identity.


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

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

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


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

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


Question: PostgreSQL Ddl: show example 21.

CREATE TABLE products ( product_no integer NOT NULL, name text NOT NULL, price numeric NOT NULL CHECK (price > 0) );

Explanation: Example from PostgreSQL documentation on Ddl.


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

SELECT COUNT(*)
FROM pg_foreign_table
WHERE ftrelid = 'table30'::regclass
AND ftoptions @> array['batch_size=30'];

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


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

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

Explanation: Regression test for Maintain Every in PostgreSQL core test suite.

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


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

drop table parted_referenced, parted_trigger, unparted_trigger;

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


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

SELECT t4.*
FROM (SELECT t1.*, t2.a AS a1 FROM sj t1, sj t2 WHERE t1.b = t2.b) AS t3
JOIN sj t4 ON (t4.a = t3.a) WHERE t3.a1 = 42;

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

SELECT count(*) FROM (SELECT t4.*
FROM (SELECT t1.*, t2.a AS a1 FROM sj t1, sj t2 WHERE t1.b = t2.b) AS t3
JOIN sj t4 ON (t4.a = t3.a) WHERE t3.a1 = 42) AS _sub;


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

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

Explanation: DML from PostgreSQL core regression test for Timestamptz.


Question: Write the DDL statement from PostgreSQL regression test 'truncate' (example 165).

CREATE TABLE trunc_a3 PARTITION OF trunc_a FOR VALUES FROM (20) TO (30);

Explanation: DDL from PostgreSQL core regression test for Truncate.


Question: PL/pgSQL test: Plpgsql Transaction (example 54).

BEGIN
    FOR r IN SELECT a FROM test1 FOR UPDATE LOOP
      UPDATE test1 SET b = b || ' ' || b WHERE a = r.a;

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


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

INSERT INTO foo VALUES (999999, NULL, 'bar');

Explanation: DML from PostgreSQL core regression test for Jsonb.


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

ALTER EXTENSION pgtap ADD FUNCTION row_eq( TEXT, anyelement );

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


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

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

SELECT count(*) FROM (SELECT INTERVAL 'today') AS _sub;


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

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

SELECT count(*) FROM (select '[{"b": "c"}, {"b": "cc"}]'::jsonb -> 1) AS _sub;


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

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


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

-- bucketing with timezone
CREATE OR REPLACE FUNCTION @extschema@.time_bucket(bucket_width INTERVAL, ts TIMESTAMPTZ, timezone TEXT, origin TIMESTAMPTZ DEFAULT NULL, "offset" INTERVAL DEFAULT NULL) RETURNS TIMESTAMPTZ
	AS '@MODULE_PATHNAME@', 'ts_timestamptz_timezone_bucket' LANGUAGE C IMMUTABLE PARALLEL SAFE;

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


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

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

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


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

select interval '-9223372036854775.808 milliseconds';

SELECT count(*) FROM (select interval '-9223372036854775.808 milliseconds') AS _sub;


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

CREATE OR REPLACE FUNCTION perl_int(int) RETURNS INTEGER AS $$
return undef;
$$ LANGUAGE plperl;

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


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

SELECT * FROM pg_input_error_info('{}', 'pg_ndistinct');

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

SELECT count(*) FROM (SELECT * FROM pg_input_error_info('{}', 'pg_ndistinct')) AS _sub;


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

create table idxpart1pk partition of idxpart (a primary key) for values from (0) to (100);

Explanation: DDL from PostgreSQL core regression test for Indexing.


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

SELECT (timestamp with time zone 'tomorrow' > 'now') as "True";

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

SELECT count(*) FROM (SELECT (timestamp with time zone 'tomorrow' > 'now') as "True") AS _sub;


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

CREATE FUNCTION gbt_macad8_union(internal, internal)
RETURNS gbtreekey16
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 'create_table' (example 55).

CREATE TABLE partitioned (
	a int
) PARTITION BY RANGE (const_func());

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


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

SELECT d1 FROM TIMESTAMPTZ_TBL
   WHERE d1 <= timestamp with time zone '1997-01-02';

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

SELECT count(*) FROM (SELECT d1 FROM TIMESTAMPTZ_TBL
   WHERE d1 <= timestamp with time zone '1997-01-02') AS _sub;


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

Explanation: DML from PostgreSQL core regression test for Polygon.


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

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


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

select string_to_array(NULL, '|') IS NULL;

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

SELECT count(*) FROM (select string_to_array(NULL, '|') IS NULL) AS _sub;


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

CREATE OR REPLACE FUNCTION rngfunc(in f1 int, out f2 int) RETURNS float
AS 'select $1+1' LANGUAGE sql;

Explanation: DDL from PostgreSQL core regression test for Rangefuncs.


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

CREATE OR REPLACE FUNCTION _have_index( NAME, NAME, NAME)
RETURNS BOOLEAN AS $$
    SELECT EXISTS (
    SELECT TRUE
      FROM pg_catalog.pg_index x
      JOIN pg_catalog.pg_class ct    ON ct.oid = x.indrelid
      JOIN pg_catalog.pg_class ci    ON ci.oid = x.indexrelid
      JOIN pg_catalog.pg_namespace n ON n.oid = ct.relnamespace
     WHERE n.nspname  = $1
       AND ct.relname = $2
       AND ci.relname = $3
    );
$$ LANGUAGE sql;

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


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

-- Check that aggregates which have the same transition function also have
-- the same combine, serialization, and deserialization functions.
-- While that isn't strictly necessary, it's fishy if they don't.

SELECT a.aggfnoid, a.aggcombinefn, a.aggserialfn, a.aggdeserialfn,
       b.aggfnoid, b.aggcombinefn, b.aggserialfn, b.aggdeserialfn
FROM
    pg_aggregate a, pg_aggregate b
WHERE
    a.aggfnoid < b.aggfnoid AND a.aggtransfn = b.aggtransfn AND
    (a.aggcombinefn != b.aggcombinefn OR a.aggserialfn != b.aggserialfn
     OR a.aggdeserialfn != b.aggdeserialfn);

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


Question: PostgreSQL Textsearch: show example 39.

SELECT to_tsquery('''supernovae stars'' & !crab'); to_tsquery --------------- 'sn' & !'crab';

Explanation: Example from PostgreSQL documentation on Textsearch.


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

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

SELECT count(*) FROM (SELECT * FROM collate_test3 ORDER BY b) AS _sub;


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

CREATE OR REPLACE FUNCTION _get_index_owner( NAME, NAME, NAME )
RETURNS NAME AS $$
    SELECT pg_catalog.pg_get_userbyid(ci.relowner)
      FROM pg_catalog.pg_index x
      JOIN pg_catalog.pg_class ct    ON ct.oid = x.indrelid
      JOIN pg_catalog.pg_class ci    ON ci.oid = x.indexrelid
      JOIN pg_catalog.pg_namespace n ON n.oid = ct.relnamespace
     WHERE n.nspname  = $1
       AND ct.relname = $2
       AND ci.relname = $3;
$$ LANGUAGE sql;


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

CREATE OR REPLACE FUNCTION @extschema@.show_tablespaces(hypertable REGCLASS) RETURNS SETOF NAME
AS '@MODULE_PATHNAME@', 'ts_tablespace_show' LANGUAGE C VOLATILE STRICT;

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


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

SELECT has_foreign_data_wrapper_privilege(
    (SELECT oid FROM pg_foreign_data_wrapper WHERE fdwname='foo'), 'USAGE');

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

SELECT count(*) FROM (SELECT has_foreign_data_wrapper_privilege(
    (SELECT oid FROM pg_foreign_data_wrapper WHERE fdwname='foo'), 'USAGE')) AS _sub;


Question: PL/pgSQL test: Plpython Error (example 30).

CREATE OR REPLACE FUNCTION sql_error() RETURNS void AS $$
begin
  select 1/0;
end
$$ LANGUAGE plpgsql;

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


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

INSERT INTO insert_tbl (SELECT * FROM local_tbl UNION ALL SELECT * FROM remote_tbl);

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


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

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

SELECT count(*) FROM (select jsonb_set_lax('{"a":1,"b":2}','{d}',null,true)) AS _sub;


Question: Use pg_stat_statements to find the slowest queries.

SELECT query, calls, mean_exec_time AS avg_ms, total_exec_time AS total_ms,
       rows, shared_blks_hit, shared_blks_read
FROM pg_stat_statements
ORDER BY mean_exec_time DESC
LIMIT 20;

Explanation: pg_stat_statements extension tracks execution statistics for all queries. Ordering by mean_exec_time surfaces the slowest individual query patterns.


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

INSERT INTO nulltest values ('a', 'b', 'c', 'd', 'c');  -- Good
insert into nulltest values ('a', 'b', 'c', 'd', NULL);

Explanation: DML from PostgreSQL core regression test for Domain.


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

INSERT INTO PATH_TBL VALUES (' ( ( 1 , 2 ) , ( 3 , 4 ) ) ');

Explanation: DML from PostgreSQL core regression test for Path.


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

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

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


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

CREATE TABLE collate_test_fail (
    a int COLLATE "en-x-icu",
    b text
);

Explanation: DDL from PostgreSQL core regression test for Collate.Icu.Utf8.


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

SELECT * FROM pg_input_error_info('[null]', 'pg_ndistinct');

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

SELECT count(*) FROM (SELECT * FROM pg_input_error_info('[null]', 'pg_ndistinct')) AS _sub;


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

INSERT INTO money_data VALUES ('$123.455');

Explanation: DML from PostgreSQL core regression test for Money.


Question: Show an example of PostgreSQL PSQL-REF (example 6).

SELECT $1 \parse stmt1 \close_prepared stmt1;

Explanation: PostgreSQL PSQL-REF command.


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

INSERT INTO functional_dependencies_multi (a, b, c, d)
    SELECT
         mod(i,7),
         mod(i,7),
         mod(i,11),
         mod(i,11)
    FROM generate_series(1,5000) s(i);

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


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


Question: pgTAP test for Index (assertion 82).

SELECT * FROM check_test(
    index_is_partial( 'public', 'sometab', 'idx_baz' ),
    false,
    'index_is_partial() fail no desc',
    'Index idx_baz should be partial',
    ''
);

Explanation: SQL assertion from pgTAP test suite for Index.


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

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

SELECT count(*) FROM (SELECT pg_get_triggerdef(0)) AS _sub;


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

CREATE FOREIGN DATA WRAPPER extstats_dummy_fdw;

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


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

select description, inbytes, (test_conv(inbytes, 'iso8859-5', 'koi8r')).* from iso8859_5_inputs;

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

SELECT count(*) FROM (select description, inbytes, (test_conv(inbytes, 'iso8859-5', 'koi8r')).* from iso8859_5_inputs) AS _sub;


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

CREATE FUNCTION gc_to_sec(float8)
RETURNS float8
LANGUAGE SQL
IMMUTABLE STRICT
PARALLEL SAFE
AS 'SELECT CASE WHEN $1 < 0 THEN 0::float8 WHEN $1/earth() > pi() THEN 2*earth() ELSE 2*earth()*sin($1/(2*earth())) END';

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


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

Explanation: DML from PostgreSQL core regression test for Numeric.


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

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


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

SELECT COUNT(*) FROM (VALUES (1::INT, 2::INT)) AS t(a, b) GROUP BY b;

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


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

INSERT INTO temporal_mltrng (id, valid_at) VALUES ('[2,3)', datemultirange(daterange('2005-01-01', '2006-01-01'))) ON CONFLICT (id, valid_at) DO NOTHING;

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


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

INSERT INTO test VALUES ('Top.Hobbies');

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


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

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


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

select * from jsonb_path_query('[1, "2", null]', '$[*] ? (@ != null)');

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

SELECT count(*) FROM (select * from jsonb_path_query('[1, "2", null]', '$[*] ? (@ != null)')) AS _sub;


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

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


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

SELECT xmltable.* FROM xmltest2, LATERAL xmltable(('/d/r/' || lower(_path) || 'c') PASSING x COLUMNS a int PATH '.');

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

SELECT count(*) FROM (SELECT xmltable.* FROM xmltest2, LATERAL xmltable(('/d/r/' || lower(_path) || 'c') PASSING x COLUMNS a int PATH '.')) AS _sub;


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

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

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

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


Question: PostgreSQL regression test 'create_misc': Write the SELECT query (example 70).

SELECT class, sum(a) FROM a_star* GROUP BY class ORDER BY class;

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

SELECT count(*) FROM (SELECT class, sum(a) FROM a_star* GROUP BY class ORDER BY class) AS _sub;


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

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

SELECT count(*) FROM (select jsonb_insert('{"a": [0,1,2]}', '{a, 1}', '{"b": "value"}')) AS _sub;


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

SELECT JSON_ARRAY(SELECT i FROM (VALUES (NULL::int[]), ('{1,2}'), (NULL), (NULL), ('{3,4}'), (NULL)) foo(i) RETURNING jsonb);

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

SELECT count(*) FROM (SELECT JSON_ARRAY(SELECT i FROM (VALUES (NULL::int[]), ('{1,2}'), (NULL), (NULL), ('{3,4}'), (NULL)) foo(i) RETURNING jsonb)) AS _sub;


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

SELECT DISTINCT ON (y, x) x, y FROM (select * from distinct_on_tbl order by x, z, y) s ORDER BY y, x, z;

Explanation: Regression test for Select Distinct On in PostgreSQL core test suite.

SELECT count(*) FROM (SELECT DISTINCT ON (y, x) x, y FROM (select * from distinct_on_tbl order by x, z, y) s ORDER BY y, x, z) AS _sub;


Question: pgTAP test for Index (assertion 9).

CREATE UNIQUE INDEX idx_baz ON public.sometab(LOWER(name));

Explanation: SQL assertion from pgTAP test suite for Index.


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

SELECT pg_relation_size(reltoastrelid) = 0 AS is_empty
  FROM pg_class where relname = 'toasttest';

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

SELECT count(*) FROM (SELECT pg_relation_size(reltoastrelid) = 0 AS is_empty
  FROM pg_class where relname = 'toasttest') AS _sub;


Question: Write the DML statement from PostgreSQL regression test 'polygon' (example 12).

INSERT INTO POLYGON_TBL(f1) VALUES ('asdf');

Explanation: DML from PostgreSQL core regression test for Polygon.


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

SELECT count(*) FROM ltreetest WHERE t >= '12.3';

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


Question: pgTAP test for Hastap (assertion 273).

SELECT * FROM check_test(
    domain_type_isnt( 'public', 'us_postal_code', 'text', 'whatever'),
    false,
    'domain_type_isnt(schema, domain, type, desc) fail',
    'whatever',
    '        have: text
        want: anything else'
);

Explanation: SQL assertion from pgTAP test suite for Hastap.


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

INSERT INTO num_input_test(n1) VALUES ('1.2e3__4');

Explanation: DML from PostgreSQL core regression test for Numeric.


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

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

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


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

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


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

SELECT regexp_split_to_array('helloTworld'::citext, 't'::citext, 's') = ARRAY[ 'hello', 'world' ] AS t;

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


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

SELECT t1.c1, t2.c2, t3.c3 FROM ft2 t1 RIGHT JOIN ft2 t2 ON (t1.c1 = t2.c1) FULL JOIN ft4 t3 ON (t2.c1 = t3.c1) OFFSET 10 LIMIT 10;

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


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

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

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


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

SELECT * FROM pg_get_wal_stats_till_end_of_wal('FFFFFFFF/FFFFFFFF');

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


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

insert into pparent values (1,'parent1');

Explanation: DML from PostgreSQL core regression test for Rules.


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

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

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

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


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

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


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


Question: PostgreSQL Queries: show example 54.

WITH RECURSIVE included_parts(sub_part, part) AS ( SELECT sub_part, part FROM parts WHERE part = 'our_product' UNION ALL SELECT p.sub_part, p.part FROM included_parts pr, parts p WHERE p.part = pr.sub_part ) DELETE FROM parts WHERE part IN (SELECT part FROM included_parts);

Explanation: Example from PostgreSQL documentation on Queries.


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

CREATE FUNCTION btismn13cmp(ismn13, ismn)
	RETURNS int4
	AS 'btint8cmp'
	LANGUAGE 'internal'
	IMMUTABLE STRICT
	PARALLEL SAFE;

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


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

create function psql_df_internal (float8)
  returns float8
  language internal immutable parallel safe strict
  as 'dsin';

Explanation: DDL from PostgreSQL core regression test for Psql.


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

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

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


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

SELECT f1 FROM CIRCLE_TBL WHERE diameter(f1) >= 10;

SELECT count(*) FROM (SELECT f1 FROM CIRCLE_TBL WHERE diameter(f1) >= 10) AS _sub;


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

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


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


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

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


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

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

SELECT count(*) FROM (select jsonb_path_query('"1.23aaa"', '$.string()')) AS _sub;


Question: PostgreSQL Plpgsql: show example 46.

CREATE TABLE db (a INT PRIMARY KEY, b TEXT); CREATE FUNCTION merge_db(key INT, data TEXT) RETURNS VOID AS $$ BEGIN LOOP -- first try to update the key UPDATE db SET b = data WHERE a = key; IF found THEN RETURN; END IF; -- not there, so try to insert the key -- if someone else inserts the same key concurrently, -- we could get a unique-key failure BEGIN INSERT INTO db(a,b) VALUES (key, data); RETURN; EXCEPTION WHEN unique_violation THEN -- Do nothing, and loop to try the UPDATE again. END; END LOOP; END; $$ LANGUAGE plpgsql; SELECT merge_db(1, 'david'); SELECT merge_db(1, 'dennis');

Explanation: Example from PostgreSQL documentation on Plpgsql.


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

-- obsolete:
CREATE OPERATOR @ (
	LEFTARG = seg,
	RIGHTARG = seg,
	PROCEDURE = seg_contains,
	COMMUTATOR = '~',
	RESTRICT = contsel,
	JOIN = contjoinsel
);


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

PREPARE recentfilms(date) AS SELECT * FROM films WHERE date_prod > $1; CREATE TEMP TABLE films_recent ON COMMIT DROP AS EXECUTE recentfilms('2002-01-01');

Explanation: PostgreSQL CREATE TABLE AS command.


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

SELECT plainto_tsquery('english', 'foo bar') || !!plainto_tsquery('english', 'asd fg');

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

SELECT count(*) FROM (SELECT plainto_tsquery('english', 'foo bar') || !!plainto_tsquery('english', 'asd fg')) AS _sub;


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

SELECT server_name, user_name = CURRENT_USER as "user_name = CURRENT_USER",
  valid, used_in_xact, closed,
  remote_backend_pid = ANY(SELECT pid FROM pg_stat_activity
  WHERE backend_type = 'client backend' AND pid <> pg_backend_pid())
  as remote_backend_pid
  FROM postgres_fdw_get_connections() ORDER BY 1;


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

SELECT r.rngtypid, r.rngsubtype, p.proname
FROM pg_range r JOIN pg_proc p ON p.oid = r.rngmltconstruct0 JOIN pg_type t ON r.rngmultitypid = t.oid
WHERE p.pronargs != 0
    OR p.prorettype != r.rngmultitypid
    OR p.proname != t.typname OR p.prosrc != 'multirange_constructor0';

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

SELECT count(*) FROM (SELECT r.rngtypid, r.rngsubtype, p.proname
FROM pg_range r JOIN pg_proc p ON p.oid = r.rngmltconstruct0 JOIN pg_type t ON r.rngmultitypid = t.oid
WHERE p.pronargs != 0
    OR p.prorettype != r.rngmultitypid
    OR p.proname != t.typname OR p.prosrc != 'multirange_constructor0') AS _sub;


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

INSERT INTO FKTABLE VALUES (NULL, 2, 3, 2);

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


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

insert into rtest_view1 values (3, 'item 3', 't');


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

-- check that this doesn't leak a holdable portal
SELECT * FROM pg_cursors;

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


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

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


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

CREATE VIEW classv AS SELECT * FROM pg_class;

Explanation: DDL from PostgreSQL core regression test for Merge.


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

CREATE EVENT TRIGGER regress_event_trigger_report_end ON ddl_command_end
  EXECUTE PROCEDURE event_trigger_report_end();

Explanation: DDL from PostgreSQL core regression test for Event Trigger.


Question: pgTAP test for Resultset (assertion 161).

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

Explanation: SQL assertion from pgTAP test suite for Resultset.


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

create rule rules_foorule as on insert to rules_foo where f1 < 100
do instead insert into rules_foo2 values (new.f1);

Explanation: DDL from PostgreSQL core regression test for Rules.


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

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

SELECT count(*) FROM (SELECT xmlconcat(NULL, NULL)) AS _sub;


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

INSERT INTO hats VALUES ('h8', 'white') RETURNING *;

Explanation: DML from PostgreSQL core regression test for Rules.


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

SELECT * FROM (VALUES (1),(2),(3)) v(r), generate_series(10+r,20-r) f(i);

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

SELECT count(*) FROM (SELECT * FROM (VALUES (1),(2),(3)) v(r), generate_series(10+r,20-r) f(i)) AS _sub;


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

select *
  from (values (1),(2)) v(x),
       lateral (select a, b, sum(v.x) from gstest_data(v.x) group by rollup (a,b)) s;

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

SELECT count(*) FROM (select *
  from (values (1),(2)) v(x),
       lateral (select a, b, sum(v.x) from gstest_data(v.x) group by rollup (a,b)) s) AS _sub;


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

SELECT 'Ask Bjørn Hansen'::citext <> 'Ask Bjorn Hansen'::citext AS t;

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


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

Explanation: DML from PostgreSQL core regression test for Numeric.


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

ALTER OPERATOR FAMILY alt_opf14 USING btree ADD FUNCTION 1 fn_opf14(int4);

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


Question: Show a SQL definition from the citus project (merge_repartition1, item 16).

CREATE TABLE pg_source(id int, val int, const int);

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


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

Explanation: PL/pgSQL object from PostgreSQL core test for Event Trigger Login.


Question: PostgreSQL Typeconv: show example 6.

Explanation: Example from PostgreSQL documentation on Typeconv.


Question: Write the DDL statement from PostgreSQL regression test 'event_trigger' (example 37).

CREATE TABLE evttrig.part_10_15 PARTITION OF evttrig.part_10_20 (id)
  FOR VALUES FROM (10) TO (15);


Question: PostgreSQL Plpgsql: show example 22.

CREATE TABLE mytable (id int PRIMARY KEY, data text); INSERT INTO mytable VALUES (1,'one'), (2,'two');

Explanation: Example from PostgreSQL documentation on Plpgsql.


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

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

SELECT count(*) FROM (SELECT 37 - q1 AS minus4 FROM INT8_TBL) AS _sub;


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

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


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

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


Question: Write the DML statement from PostgreSQL regression test 'line' (example 13).

Explanation: DML from PostgreSQL core regression test for Line.


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

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

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


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

-- We started using CREATE OR REPLACE AGGREGATE for aggregate creation once the syntax was fully supported
-- as it is easier to support idempotent changes this way. This will allow for changes to functions supporting
-- the aggregate, and, for instance, the definition and inclusion of inverse functions for window function
-- support. However, it should still be noted that changes to the data structures used for the internal
-- state of the aggregate must be backwards compatible and the old format must be accepted by any new functions
-- in order for them to continue working with Continuous Aggregates, where old states may have been materialized.

-- This aggregate partitions the dataset into a specified number of buckets (nbuckets) ranging
-- from the inputted min to max values.
CREATE OR REPLACE AGGREGATE @extschema@.histogram (DOUBLE PRECISION, DOUBLE PRECISION, DOUBLE PRECISION, INTEGER) (
    SFUNC = _timescaledb_functions.hist_sfunc,
    STYPE = INTERNAL,
    COMBINEFUNC = _timescaledb_functions.hist_combinefunc,
    SERIALFUNC = _timescaledb_functions.hist_serializefunc,
    DESERIALFUNC = _timescaledb_functions.hist_deserializefunc,
    PARALLEL = SAFE,
    FINALFUNC = _timescaledb_functions.hist_finalfunc,
    FINALFUNC_EXTRA
);

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


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

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 'returning' (example 117).

CREATE TABLE foo_part_d2 (b float8, c text, a int);

Explanation: DDL from PostgreSQL core regression test for Returning.


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

SELECT ts_delete('base hidden rebel spaceship strike'::tsvector, 'spaceship');

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

SELECT count(*) FROM (SELECT ts_delete('base hidden rebel spaceship strike'::tsvector, 'spaceship')) AS _sub;


Question: pgTAP test for Hastap (assertion 143).

-- Make sure it works with composite types.
SELECT * FROM check_test(
    hasnt_column( 'sometype', 'foobar' ),
    true,
    'hasnt_column(type, column)',
    'Column sometype.foobar should not exist',
    ''
);

Explanation: SQL assertion from pgTAP test suite for Hastap.


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

ALTER EXTENSION pgtap ADD FUNCTION _currtest();


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

CREATE TRIGGER rw_view1_del_trig INSTEAD OF DELETE ON rw_view1
  FOR EACH ROW EXECUTE PROCEDURE rw_view1_trig_fn();

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


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

SELECT count(*) FROM float8tmp WHERE a <= -1890.0::float8;

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


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

Explanation: DML from PostgreSQL core regression test for Arrays.


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

CREATE OR REPLACE FUNCTION _trig ( NAME, NAME )
RETURNS BOOLEAN AS $$
    SELECT EXISTS(
        SELECT true
          FROM pg_catalog.pg_trigger t
          JOIN pg_catalog.pg_class c     ON c.oid = t.tgrelid
         WHERE c.relname = $1
           AND t.tgname  = $2
           AND pg_catalog.pg_table_is_visible(c.oid)
    );
$$ LANGUAGE SQL;

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


Question: PL/pgSQL test: Plpgsql Varprops (example 11).

do $$
declare x constant var_record; y int;
begin
  for x.f1, y in select 1, 2 loop  -- fail
  end loop;
end$$;

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


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

SELECT * FROM bt_multi_page_stats('test2_col1_idx', 1, 2);

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


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

DROP TRIGGER trans_deletetrig ON range_parted;

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


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

select a, b, row_number() over (order by a, b nulls first)
from (values (1, 1), (2, 2)) as t (a, b) where a = b
group by grouping sets((a, b), (a));

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

SELECT count(*) FROM (select a, b, row_number() over (order by a, b nulls first)
from (values (1, 1), (2, 2)) as t (a, b) where a = b
group by grouping sets((a, b), (a))) AS _sub;


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

CREATE TABLE reloptions_test(time integer, temp float8, color integer)
WITH (fillfactor=75, autovacuum_vacuum_threshold=100);


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

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


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

SELECT t1.a, t1.c, t2.b, t2.c FROM prt1_adv t1 INNER JOIN prt2_adv t2 ON (t1.a = t2.b) WHERE t1.b = 0 ORDER BY t1.a, t2.b;

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

SELECT count(*) FROM (SELECT t1.a, t1.c, t2.b, t2.c FROM prt1_adv t1 INNER JOIN prt2_adv t2 ON (t1.a = t2.b) WHERE t1.b = 0 ORDER BY t1.a, t2.b) AS _sub;


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

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

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

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


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

\set ON_ERROR_STOP 1

-- error injections
--
CREATE OR REPLACE FUNCTION test_error_injection(TEXT)
RETURNS VOID
AS :MODULE_PATHNAME, 'ts_test_error_injection'
LANGUAGE C VOLATILE STRICT;


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

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

Explanation: DML from PostgreSQL core regression test for Subselect.


Question: Show a SQL definition from the pglogical project (parallel, item 12).

SELECT pglogical.replicate_ddl_command($$
    CREATE TABLE public.basic_dml1 (
        id serial primary key,
        other integer,
        data text,
        something interval
    );
    CREATE TABLE public.basic_dml2 (
        id serial primary key,
        other integer,
        data text,
        something interval
    );
$$);

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


Question: pgTAP test for Hastap (assertion 144).


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

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

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


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

Explanation: DML from PostgreSQL core regression test for Rowsecurity.


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

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

SELECT count(*) FROM (SELECT jsonb_each_text('{"a":{"b":"c","c":"b","1":"first"},"b":[1,2],"c":"cc","1":"first","n":null}'::jsonb) AS q) AS _sub;


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

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


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

select jsonb_path_query('[1,"2",3]', '+$', silent => true);

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

SELECT count(*) FROM (select jsonb_path_query('[1,"2",3]', '+$', silent => true)) AS _sub;


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

create table notnull_tbl_fail (a int not null no inherit primary key);

Explanation: DDL from PostgreSQL core regression test for Constraints.


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

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

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

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


Question: pgTAP test for Ownership (assertion 132).

SELECT * FROM check_test(
    type_owner_is('sometype', current_user),
	true,
    'type_owner_is(type, user)',
    'Type sometype should be owned by ' || quote_ident(current_user),
    ''
);

Explanation: SQL assertion from pgTAP test suite for Ownership.


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

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


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

SELECT f.* FROM FLOAT8_TBL f WHERE f.f1 <> '1004.3';

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

SELECT count(*) FROM (SELECT f.* FROM FLOAT8_TBL f WHERE f.f1 <> '1004.3') AS _sub;


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

CREATE TRIGGER check_update BEFORE UPDATE ON accounts FOR EACH ROW EXECUTE FUNCTION check_account_update();

Explanation: PostgreSQL CREATE TRIGGER command.


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

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

SELECT count(*) FROM (SELECT brin_summarize_range('brin_summarize_bloom_idx', 2)) AS _sub;


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

SELECT * FROM pglogical_regress_variables()
\gset

\c :provider_dsn

SELECT pglogical.replicate_ddl_command($$
	CREATE TABLE public.test_trg_data(id serial primary key, data text);
$$);


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

SELECT '( 1 , 1)'::citext::point ~= '(1,1)'::point AS t;

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


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

INSERT INTO PRIMARY_TBL VALUES (1, 'three');

Explanation: DML from PostgreSQL core regression test for Constraints.


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

SELECT count(*) FROM (select jsonb_path_query('"12:34:56 +05:30"', '$.timestamp()')) AS _sub;


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

-- test as part of prepare/execute
CREATE FUNCTION test3() RETURNS void
LANGUAGE plperlu
TRANSFORM FOR TYPE hstore
AS $$
use Data::Dumper;
$Data::Dumper::Sortkeys = 1;
$Data::Dumper::Indent = 0;

$rv = spi_exec_query(q{SELECT 'aa=>bb, cc=>NULL'::hstore AS col1});
elog(INFO, Dumper($rv->{rows}[0]->{col1}));

$val = {a => 1, b => 'boo', c => undef};
$plan = spi_prepare(q{SELECT $1::text AS col1}, "hstore");
$rv = spi_exec_prepared($plan, {}, $val);
elog(INFO, Dumper($rv->{rows}[0]->{col1}));
$$;

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


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

CREATE FUNCTION zdb.schema_version() RETURNS text LANGUAGE sql AS $$
SELECT '3000.2.8 (a6e866f5904a99f977bd1d1840fd422329132350)'
$$;

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


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

create table T_dta2 (
    tkey	char(10),
    ref1	int4,
    ref2	char(20)
);

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


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

INSERT INTO num_exp_mul VALUES (5,0,'0');

Explanation: DML from PostgreSQL core regression test for Numeric.


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

SELECT JSON_QUERY(jsonb '123', '$' RETURNING queryfuncs_char2 DEFAULT '1' ON ERROR);

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

SELECT count(*) FROM (SELECT JSON_QUERY(jsonb '123', '$' RETURNING queryfuncs_char2 DEFAULT '1' ON ERROR)) AS _sub;


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

SELECT a, lower(coalesce(x, 'foo')), lower(coalesce(y, 'foo')) FROM collate_test10;

SELECT count(*) FROM (SELECT a, lower(coalesce(x, 'foo')), lower(coalesce(y, 'foo')) FROM collate_test10) AS _sub;


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

CREATE FUNCTION gin_extract_value_numeric(numeric, internal)
RETURNS internal
AS 'MODULE_PATHNAME'
LANGUAGE C STRICT IMMUTABLE;


Question: PL/pgSQL test: Plperl Util (example 12).

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


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

CREATE MATERIALIZED VIEW addr_nsp.genmatview AS SELECT * FROM addr_nsp.gentable;

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


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

SELECT x,
       gamma(x),
       lgamma(x)
FROM (VALUES (0.5), (1), (2), (3), (4), (5),
             (float8 'infinity'), (float8 'nan')) AS t(x);

SELECT count(*) FROM (SELECT x,
       gamma(x),
       lgamma(x)
FROM (VALUES (0.5), (1), (2), (3), (4), (5),
             (float8 'infinity'), (float8 'nan')) AS t(x)) AS _sub;


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

create table chi partition of middle for values from (1) to (5);

Explanation: DDL from PostgreSQL core regression test for Triggers.


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

create table lp (a char) partition by list (a);

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


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

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


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

CREATE INDEX brin_test_multi_a_idx ON brin_test_multi USING brin (a) WITH (pages_per_range = 2);

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


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

select count(*) from testhstore where h ?| ARRAY['public','disabled'];

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


Question: pgTAP test for Unique (assertion 9).

SELECT * FROM check_test(
    has_unique( 'public', 'uniqueless', 'public.uniqueless should have a unique constraint' ),
    false,
    'has_unique( schema, table, description ) fail',
    'public.uniqueless should have a unique constraint',
    ''
);

Explanation: SQL assertion from pgTAP test suite for Unique.


Question: Write the DML statement from PostgreSQL regression test 'fast_default' (example 148).

Explanation: DML from PostgreSQL core regression test for Fast Default.


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

update pg_class set reltuples = 1000 where relname = 'bigger_than_it_looks';

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


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

create index idxparti2 on idxpart (b, c);

Explanation: DDL from PostgreSQL core regression test for Indexing.


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

SELECT 1 FROM xact_test FOR UPDATE LIMIT 1;

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


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

SELECT regexp_split_to_array('helloTworld'::citext, 't'::citext) = ARRAY[ 'hello', 'world' ] AS t;

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


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

CREATE COLLATION mycoll2 ( LC_COLLATE = "POSIX", LC_CTYPE = "POSIX" );

Explanation: DDL from PostgreSQL core regression test for Collate.


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

INSERT INTO tbl_include_box_pk SELECT 1, 2, 3*x, box('4,4,4,4') FROM generate_series(1,10) AS x;

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


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

select * from tcl_dcomposite_result(1002);

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


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

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

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


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

SELECT * FROM JSON_TABLE(jsonb '"a"', '$' COLUMNS (a char(3) EXISTS PATH '$.a' ERROR ON ERROR));

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

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


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

select interval '0.01 months 9223372036854775807 microseconds';

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

SELECT count(*) FROM (select interval '0.01 months 9223372036854775807 microseconds') AS _sub;


Question: Write the DML statement from PostgreSQL regression test 'generated_stored' (example 121).

Explanation: DML from PostgreSQL core regression test for Generated Stored.


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

select (x+y)*1, sum(z)
 from (select 1 as x, 2 as y, 3 as z) s
 group by grouping sets (x+y, x);

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

SELECT count(*) FROM (select (x+y)*1, sum(z)
 from (select 1 as x, 2 as y, 3 as z) s
 group by grouping sets (x+y, x)) AS _sub;


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

INSERT INTO caster (citext)        VALUES ('08:00:2b:01:02:03'::macaddr);


Question: Show a SQL definition from the citus project (distributed_collations, item 25).

-- Test range table with collated distribution column
CREATE TABLE test_range(key text COLLATE german_phonebook, val int);

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


Question: PostgreSQL Rules: show example 33.

INSERT INTO shoelace_log VALUES ( shoelace_data.sl_name , 6 , current_user, current_timestamp ) FROM shoelace_data new, shoelace_data old, shoelace_data shoelace_data WHERE 6 <> old.sl_avail AND shoelace_data.sl_name = 'sl7';

Explanation: Example from PostgreSQL documentation on Rules.


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

CREATE TABLE pht1_p2 PARTITION OF pht1 FOR VALUES WITH (MODULUS 3, REMAINDER 1);

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


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

CREATE FUNCTION show_trgm(text)
RETURNS _text
AS 'MODULE_PATHNAME'
LANGUAGE C STRICT IMMUTABLE PARALLEL SAFE;

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


Question: Write the DML statement from PostgreSQL regression test 'stats' (example 118).

INSERT INTO drop_stats_test_subxact DEFAULT VALUES;

Explanation: DML from PostgreSQL core regression test for Stats.


Question: Create a trigger that updates a modified_at timestamp on every UPDATE.

CREATE TABLE articles (id serial PRIMARY KEY, title text, body text, modified_at timestamptz DEFAULT now());

CREATE OR REPLACE FUNCTION update_modified_at() RETURNS trigger AS $$
BEGIN
    NEW.modified_at := now();
    RETURN NEW;
END;
$$ LANGUAGE plpgsql;
CREATE TRIGGER trg_articles_modified BEFORE UPDATE ON articles FOR EACH ROW EXECUTE FUNCTION update_modified_at();

Explanation: PL/pgSQL trigger function sets NEW.modified_at to now() before each UPDATE. Trigger fires per row.


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

SELECT '2011-03-27 03:00:01 Europe/Moscow'::timestamptz;

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

SELECT count(*) FROM (SELECT '2011-03-27 03:00:01 Europe/Moscow'::timestamptz) AS _sub;


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

SELECT * FROM test_type_conversion_int8(100);

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


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

CREATE TABLE zdb.type_conversions
(
    typeoid    regtype NOT NULL PRIMARY KEY,
    funcoid    regproc NOT NULL,
    is_default boolean DEFAULT false
);

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


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

Explanation: DDL from PostgreSQL core regression test for Join.


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

CREATE FUNCTION plperl_to_hstore(val internal) RETURNS hstore
LANGUAGE C STRICT IMMUTABLE
AS '$libdir/hstore_plperl';

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


Question: Write the DDL statement from PostgreSQL regression test 'multirangetypes' (example 501).

create index nummultirange_test2_hash_idx on nummultirange_test2 using hash (nmr);

Explanation: DDL from PostgreSQL core regression test for Multirangetypes.


Question: pgTAP test for Runtests (assertion 17).

CREATE OR REPLACE FUNCTION whatever.testy() RETURNS SETOF TEXT AS $$
    SELECT fail('this test intentionally fails');
$$ LANGUAGE SQL;

Explanation: SQL assertion from pgTAP test suite for Runtests.