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

-- window functions are not to be included in GROUP BY, either
EXPLAIN (COSTS OFF) SELECT a, COUNT(a) OVER (PARTITION BY a) FROM t1 GROUP BY ALL;

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


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

Explanation: DML from PostgreSQL core regression test for Subselect.


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

SELECT * FROM nummultirange_test WHERE nmr <= '{}';

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

SELECT count(*) FROM (SELECT * FROM nummultirange_test WHERE nmr <= '{}') AS _sub;


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

INSERT INTO shoe_data VALUES ('sh4', 3, 'brown', 40.0, 50.0, 'inch');

Explanation: DML from PostgreSQL core regression test for Rules.


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

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


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

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


Question: pgTAP test for Functap (assertion 378).

SELECT * FROM check_test(
    volatility_is( 'yay'::name, 'volatile' ),
    true,
    'function_volatility(func, volatile)',
    'Function yay() should be VOLATILE',
    ''
);

Explanation: SQL assertion from pgTAP test suite for Functap.


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

select * from pg_get_object_address('function of access method', '{btree,integer_ops,99}', '{int4,int4}');

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

SELECT count(*) FROM (select * from pg_get_object_address('function of access method', '{btree,integer_ops,99}', '{int4,int4}')) AS _sub;


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

CREATE TABLE fk_partitioned_fk_full (x int, y int) PARTITION BY RANGE (x);

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


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

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

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


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

SELECT time '11:27:42' - interval '-infinity';

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

SELECT count(*) FROM (SELECT time '11:27:42' - interval '-infinity') AS _sub;


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

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


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

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


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

SELECT roundtrip('{"1": -1.1}', 'HASH');

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


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

create temp table float_table (float_col float8);

Explanation: DDL from PostgreSQL core regression test for Subselect.


Question: pgTAP test for Resultset (assertion 81).

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

Explanation: SQL assertion from pgTAP test suite for Resultset.


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

select jsonb_path_query('{}', '$.bigint()', silent => true);

SELECT count(*) FROM (select jsonb_path_query('{}', '$.bigint()', silent => true)) AS _sub;


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

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

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


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

create table lp_ad partition of lp for values in ('a', 'd');

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


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

select a < b and b < 3 from (values (1, 2)) t(a, b) group by rollup(a < b and b < 3) having a < b and b < 3;

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

SELECT count(*) FROM (select a < b and b < 3 from (values (1, 2)) t(a, b) group by rollup(a < b and b < 3) having a < b and b < 3) AS _sub;


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

Explanation: DDL from PostgreSQL core regression test for Domain.


Question: pgTAP test for Matching (assertion 8).

SELECT doesnt_imatch( 'foo'::text, '^o', 'doesnt_imatch() should work with a regex' );

Explanation: SQL assertion from pgTAP test suite for Matching.


Question: pgTAP test for Throwtap (assertion 23).

/****************************************************************************/
-- test throws_ilike().
SELECT * FROM check_test(
    throws_ilike( 'SELECT * FROM todo_end()', '%END() called without todo%', 'whatever' ),
    true,
    'throws_ilike(sql, pattern, desc)',
    'whatever',
    ''
);

Explanation: SQL assertion from pgTAP test suite for Throwtap.


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

SELECT t1.a, t1.c, t2.a, t2.c FROM plt1_adv t1 INNER JOIN plt2_adv t2 ON (t1.a = t2.a AND t1.c = t2.c) WHERE t1.c IN ('0003', '0004', '0005') AND t1.b < 10 ORDER BY t1.a;

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

SELECT count(*) FROM (SELECT t1.a, t1.c, t2.a, t2.c FROM plt1_adv t1 INNER JOIN plt2_adv t2 ON (t1.a = t2.a AND t1.c = t2.c) WHERE t1.c IN ('0003', '0004', '0005') AND t1.b < 10 ORDER BY t1.a) AS _sub;


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

--
-- Test spi_prepare/spi_query_prepared/spi_freeplan
--
CREATE OR REPLACE FUNCTION perl_spi_prepared_set(INTEGER, INTEGER) RETURNS SETOF INTEGER AS $$
  my $x = spi_prepare('SELECT $1 AS a union select $2 as a', 'INT4', 'INT4');
  my $q = spi_query_prepared( $x, 1+$_[0], 2+$_[1]);
  while (defined (my $y = spi_fetchrow($q))) {
      return_next $y->{a};
  }
  spi_freeplan($x);
  return;
$$ LANGUAGE plperl;

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


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

select '$ ? (@ like_regex "pattern" flag "")'::jsonpath;

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

SELECT count(*) FROM (select '$ ? (@ like_regex "pattern" flag "")'::jsonpath) AS _sub;


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

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

SELECT count(*) FROM (SELECT avg(four) AS avg_1 FROM onek) AS _sub;


Question: PostgreSQL Textsearch: show example 33.

SELECT * FROM ts_debug('public.pg', ' PostgreSQL, the highly scalable, SQL compliant, open source object-relational database management system, is now undergoing beta testing of the next version of our software. ');

Explanation: Example from PostgreSQL documentation on Textsearch.


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

insert into parted_conflict_1 values (40, 'cuarenta')
  on conflict (a) do update set b = excluded.b;

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


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

SELECT ks_test_uniform_random_numeric_in_range() OR
       ks_test_uniform_random_numeric_in_range() OR
       ks_test_uniform_random_numeric_in_range() AS uniform_numeric;

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

SELECT count(*) FROM (SELECT ks_test_uniform_random_numeric_in_range() OR
       ks_test_uniform_random_numeric_in_range() OR
       ks_test_uniform_random_numeric_in_range() AS uniform_numeric) AS _sub;


Question: pgTAP test for Functap (assertion 310).

SELECT * FROM check_test(
    is_window( 'yay', '{}'::name[] ),
    false,
    'is_window(func, noarg, desc)',
    'Function yay() should be a window function',
    ''
);

Explanation: SQL assertion from pgTAP test suite for Functap.


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

select id, f_float8, first_value(id) over w, last_value(id) over w
from numerics
window w as (order by f_float8 range between
             1 preceding and 1.1::float8 following);

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

SELECT count(*) FROM (select id, f_float8, first_value(id) over w, last_value(id) over w
from numerics
window w as (order by f_float8 range between
             1 preceding and 1.1::float8 following)) AS _sub;


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

ALTER EXTENSION pgtap ADD FUNCTION bag_ne( TEXT, anyarray, TEXT );

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


Question: Write the DML statement from PostgreSQL regression test 'merge' (example 470).

INSERT INTO cj_source1 VALUES (2, 20, 300);

Explanation: DML from PostgreSQL core regression test for Merge.


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

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

SELECT count(*) FROM (SELECT power('-inf'::numeric, '0')) AS _sub;


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

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


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

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


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

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

SELECT count(*) FROM (select row(1, '(1,2)')::testtype6 < row(1, '(1,3)')::testtype6) AS _sub;


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

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


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

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


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

CREATE INDEX ON _hyper_1_3_chunk(temp2);

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


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

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

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


Question: pgTAP test for Inheritance (assertion 98).

SELECT * FROM check_test(
    is_descendent_of( 'hide', 'h_child2', 'hide', 'nope', 2 ),
    false,
    'is_descendent_of(csch, ctab, psch, nope, 2)',
    'Table hide.h_child2 should be descendent 2 from hide.nope',
    ''
);

Explanation: SQL assertion from pgTAP test suite for Inheritance.


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

Explanation: DML from PostgreSQL core regression test for Insert.


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

SELECT XMLPARSE(DOCUMENT '<!DOCTYPE foo [<!ENTITY c SYSTEM "/etc/no.such.file">]><foo>&c;</foo>');

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

SELECT count(*) FROM (SELECT XMLPARSE(DOCUMENT '<!DOCTYPE foo [<!ENTITY c SYSTEM "/etc/no.such.file">]><foo>&c;</foo>')) AS _sub;


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

SELECT * FROM JSON_TABLE(jsonb '"world"', '$' COLUMNS (item text FORMAT JSON PATH '$' KEEP QUOTES));

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

SELECT count(*) FROM (SELECT * FROM JSON_TABLE(jsonb '"world"', '$' COLUMNS (item text FORMAT JSON PATH '$' KEEP QUOTES))) AS _sub;


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

SELECT 'a'::citext ~<=~ 'A'::citext AS t;

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


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

create temp table rngfunc(f1 int8, f2 int8);

Explanation: DDL from PostgreSQL core regression test for Rangefuncs.


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

Explanation: DML from PostgreSQL core regression test for Publication.


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

Explanation: DML from PostgreSQL core regression test for Rules.


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

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

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


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

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


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

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

SELECT count(*) FROM (SELECT '{[1,9)}' @> '{[1,5), [6,10)}'::nummultirange) AS _sub;


Question: Show a SQL definition from the citus project (multi_behavioral_analytics_create_table, item 29).

-- same as agg_results_second
CREATE TABLE agg_results_fourth (user_id int, value_1_agg int, value_2_agg int, value_3_agg float, value_4_agg bigint, agg_time timestamp);

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


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

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

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


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

select split_part('joeuser@mydatabase','@@',2) AS "empty string";

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

SELECT count(*) FROM (select split_part('joeuser@mydatabase','@@',2) AS "empty string") AS _sub;


Question: pgTAP test for Resultset (assertion 379).

-- Fail with a missing record.
SELECT * FROM check_test(
    bag_eq(
        'SELECT name FROM names WHERE name like ''An%''',
        ARRAY['Andrew', 'Anna', 'Anthony', 'Alan', 'Antonio', 'Angelina', 'Andrea', 'Angel' ]
    ),
    false,
    'bag_eq(sql, array) missing record',
    '',
    '    Missing records:
        (Alan)'
);

Explanation: SQL assertion from pgTAP test suite for Resultset.


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

CREATE OR REPLACE PROCEDURE _timescaledb_functions.policy_recompression(job_id INTEGER, config JSONB)
AS '@MODULE_PATHNAME@', 'ts_policy_recompression_proc'
LANGUAGE C;

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


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

/* New stuff in 1.1 begins here */

CREATE FUNCTION pgstatginindex(IN relname regclass,
    OUT version INT4,
    OUT pending_pages INT4,
    OUT pending_tuples BIGINT)
AS 'MODULE_PATHNAME', 'pgstatginindex'
LANGUAGE C STRICT PARALLEL SAFE;


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

select jsonb_path_query('"10-03-2017 12:34"', '$.datetime("dd-mm-yyyy HH24:MI TZH")');

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

SELECT count(*) FROM (select jsonb_path_query('"10-03-2017 12:34"', '$.datetime("dd-mm-yyyy HH24:MI TZH")')) AS _sub;


Question: pgTAP test for Ownership (assertion 67).

SELECT * FROM check_test(
    sequence_owner_is('__not__public', 'someseq', current_user, 'mumble'),
	false,
    'sequence_owner_is(non-sch, sequence, user)',
    'mumble',
    '    Sequence __not__public.someseq does not exist'
);

Explanation: SQL assertion from pgTAP test suite for Ownership.


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

create function dom_check(int) returns di as $$
declare d di;
begin
  d := $1::di;
  return d;
end
$$ language plpgsql immutable;

Explanation: DDL from PostgreSQL core regression test for Domain.


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

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


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

CREATE OR REPLACE FUNCTION perl_int(int) RETURNS INTEGER AS $$
return $_[0] + 1;
$$ LANGUAGE plperl;


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

-- T312 character overlay function
SELECT OVERLAY('abcdef' PLACING '45' FROM 4) AS "abc45f";

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


Question: Write the DDL statement from PostgreSQL regression test 'uuid' (example 25).

CREATE INDEX guid1_hash  ON guid1 USING HASH  (guid_field);

Explanation: DDL from PostgreSQL core regression test for Uuid.


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

-- try changing the return types and call functions again

ALTER TABLE table_record DROP COLUMN first;

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


Question: PostgreSQL regression test 'inet': Write the SELECT query (example 102).

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


Question: pgTAP test for Functap (assertion 345).

SELECT * FROM check_test(
    is_strict( 'yay', '{}'::name[], 'whatever' ),
    true,
    'is_strict(func, 0 args, desc)',
    'whatever',
    ''
);

Explanation: SQL assertion from pgTAP test suite for Functap.


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

SELECT count(*) FROM uuidtmp WHERE a <  '55e65ca2-4136-4a4b-ba78-cd3fe4678203';

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


Question: pgTAP test for Runnotests (assertion 3).

CREATE OR REPLACE FUNCTION whatever.testthis() RETURNS SETOF TEXT AS $$
BEGIN
    -- Do nothing.
END;
$$ LANGUAGE plpgsql;

Explanation: SQL assertion from pgTAP test suite for Runnotests.


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

create index idxpart1_2c_idx on idxpart1 ((b + a)) where b > 1;

Explanation: DDL from PostgreSQL core regression test for Indexing.


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


Question: Write the DDL statement from PostgreSQL regression test 'alter_generic' (example 94).

CREATE OPERATOR FAMILY alt_nsp6.alt_opf6 USING btree;

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


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

CREATE TABLE invalid(time TEXT, value FLOAT) WITH (timescaledb.hypertable);


Question: pgTAP test for Hastap (assertion 240).

SELECT * FROM check_test(
  has_opclass( 'pg_catalog', 'int4_ops'::name ),
  true,
  'has_opclass( schema, name )',
  'Operator class pg_catalog.int4_ops should exist',
  ''
);

Explanation: SQL assertion from pgTAP test suite for Hastap.


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

CREATE FUNCTION isnge(ismn13, ismn)
	RETURNS boolean
	AS 'int8ge'
	LANGUAGE 'internal'
	IMMUTABLE STRICT
	PARALLEL SAFE;

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


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

drop function anyarray_anymultirange_func(anyarray, anymultirange);

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


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

select * from pg_input_error_info('junk', 'positiveint');

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

SELECT count(*) FROM (select * from pg_input_error_info('junk', 'positiveint')) AS _sub;


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

create table Room (
    roomno	char(8),
    comment	text
);

Explanation: DDL from PostgreSQL core regression test for Plpgsql.


Question: PL/pgSQL test: Plpgsql Record (example 2).

create type more_int4s as (f0 text, f1 int4, f2 int4);

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


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

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

SELECT count(*) FROM (SELECT to_char(q2, 'FM0999999999999999')     FROM INT8_TBL) AS _sub;


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

SELECT width_bucket(2.0, 3.0, '-inf', 888);

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

SELECT count(*) FROM (SELECT width_bucket(2.0, 3.0, '-inf', 888)) AS _sub;


Question: pgTAP test for Valueset (assertion 217).

-- Try some failures.
SELECT * FROM check_test(
    set_eq(
        'SELECT id, name FROM annames WHERE name <> ''Anna''',
        'expect'
    ),
    false,
    'set_eq(select, prepared) fail missing',
    '',
    '    Missing records:
        (44,Anna)'
);

Explanation: SQL assertion from pgTAP test suite for Valueset.


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

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


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

/* contrib/pgstattuple/pgstattuple--1.0--1.1.sql */

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

CREATE FUNCTION pgstatginindex(IN relname regclass,
    OUT version INT4,
    OUT pending_pages INT4,
    OUT pending_tuples BIGINT)
AS 'MODULE_PATHNAME', 'pgstatginindex'
LANGUAGE C STRICT;


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

CREATE SCHEMA AUTHORIZATION regress_create_schema_role
  CREATE INDEX ON schema_not_existing.tab (id);

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


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

create table notnull_tbl_fail (a serial, constraint foo not null a, constraint bar not null a);

Explanation: DDL from PostgreSQL core regression test for Constraints.


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

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


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

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


Question: PostgreSQL Indices: show example 37.

SELECT am.amname AS index_method, opf.opfname AS opfamily_name, amop.amopopr::regoperator AS opfamily_operator FROM pg_am am, pg_opfamily opf, pg_amop amop WHERE opf.opfmethod = am.oid AND amop.amopfamily = opf.oid ORDER BY index_method, opfamily_name, opfamily_operator;

Explanation: Example from PostgreSQL documentation on Indices.


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

CREATE VIEW vw_getrngfunc AS SELECT * FROM getrngfunc8(1) WITH ORDINALITY AS t1(v,o);

Explanation: DDL from PostgreSQL core regression test for Rangefuncs.


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

INSERT INTO stxdinh2 SELECT mod(a,100), mod(a,100) FROM generate_series(0, 999) a;

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


Question: pgTAP test for Hastap (assertion 162).


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

/* SPI errors in PL/Python functions should preserve the SQLSTATE value
 */
CREATE FUNCTION python_unique_violation() RETURNS void AS $$
plpy.execute("insert into specific values (1)")
plpy.execute("insert into specific values (1)")
$$ LANGUAGE plpython3u;

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


Question: PostgreSQL Rules: show example 3.

CREATE TABLE shoe_data ( shoename text, -- primary key sh_avail integer, -- available number of pairs slcolor text, -- preferred shoelace color slminlen real, -- minimum shoelace length slmaxlen real, -- maximum shoelace length slunit text -- length unit ); CREATE TABLE shoelace_data ( sl_name text, -- primary key sl_avail integer, -- available number of pairs sl_color text, -- shoelace color sl_len real, -- shoelace length sl_unit text -- length unit ); CREATE TABLE unit ( un_name text, -- primary key un_fact real -- factor to transform to cm );

Explanation: Example from PostgreSQL documentation on Rules.


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

CREATE FUNCTION int44in(cstring)
   RETURNS city_budget
   AS :'regresslib'
   LANGUAGE C STRICT IMMUTABLE;

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


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

SELECT * FROM test_date WHERE i<'-infinity'::timestamp ORDER BY i;

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


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

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

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


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

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

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


Question: pgTAP test for Coltap (assertion 76).

-- Make sure it works with a NULL default.
SELECT * FROM check_test(
    col_default_is( 'sometab', 'myNum', 24 ),
    true,
    'col_default_is( tab, col, int )',
    'Column sometab."myNum" should default to ''24''',
    ''
);

Explanation: SQL assertion from pgTAP test suite for Coltap.


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

INSERT INTO caster (text)          VALUES ('the fat cat'::tsvector);

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


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

SELECT pg_current_xact_id() AS committed \gset
COMMIT;

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

SELECT count(*) FROM (SELECT pg_current_xact_id() AS committed \gset
COMMIT) AS _sub;


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

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

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


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

DELETE FROM unique_tbl WHERE i = 5 AND t = 'five';

Explanation: DML from PostgreSQL core regression test for Constraints.


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

CREATE FUNCTION perl2undef() RETURNS bool
LANGUAGE plperlu
TRANSFORM FOR TYPE bool
AS $$
return undef;
$$;

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


Question: Write the DML statement from PostgreSQL regression test 'updatable_views' (example 18).

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


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

insert into rule_and_refint_t2 values (1, 12);

Explanation: DML from PostgreSQL core regression test for Rules.


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

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

SELECT count(*) FROM (select jsonb_path_query('"2017-03-10"', '$.datetime()')) AS _sub;


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

SELECT * FROM array_op_test WHERE t @> '{}' ORDER BY seqno;

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

SELECT count(*) FROM (SELECT * FROM array_op_test WHERE t @> '{}' ORDER BY seqno) AS _sub;


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

select count(*) from test_multirange_gist where mr <@ int4range(10,50);

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

SELECT count(*) FROM (select count(*) from test_multirange_gist where mr <@ int4range(10,50)) AS _sub;


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

SELECT count(*) FROM moneytmp WHERE a >= '22649.64';

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


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

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

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


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

$$;

SELECT transaction_test4();

-- proconfig settings currently disallow transaction statements
CREATE PROCEDURE transaction_test5()
LANGUAGE plpgsql
SET work_mem = 555
AS $$
BEGIN
    COMMIT;

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


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

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


Question: Show a SQL definition from the zombodb project (zombodb--3000.0.3--3000.0.4, item 23).

CREATE OR REPLACE FUNCTION dsl.link_options(options text[], query zdbquery) RETURNS zdbquery AS 'MODULE_PATHNAME', 'link_options_wrapper' IMMUTABLE LANGUAGE c PARALLEL SAFE STRICT;

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


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

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


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

CREATE FUNCTION intarray_push_elem(_int4, int4)
RETURNS _int4
AS 'MODULE_PATHNAME'
LANGUAGE C STRICT IMMUTABLE PARALLEL SAFE;

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


Question: PostgreSQL Rules: show example 62.

CREATE FUNCTION tricky(text, text) RETURNS bool AS $$ BEGIN RAISE NOTICE '% => %', $1, $2; RETURN true; END; $$ LANGUAGE plpgsql COST 0.0000000000000000000001; SELECT * FROM phone_number WHERE tricky(person, phone);

Explanation: Example from PostgreSQL documentation on Rules.


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

-- composite_owner_is ( schema, composite, user )
CREATE OR REPLACE FUNCTION composite_owner_is ( NAME, NAME, NAME )
RETURNS TEXT AS $$
    SELECT composite_owner_is(
        $1, $2, $3,
        'Composite type ' || quote_ident($1) || '.' || quote_ident($2) || ' should be owned by ' || quote_ident($3)
    );
$$ LANGUAGE sql;

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


Question: pgTAP test for Privs (assertion 70).

/****************************************************************************/
-- Test schema_privileges_are().

SELECT * FROM check_test(
    schema_privs_are( current_schema(), current_user, ARRAY['CREATE', 'USAGE'], 'whatever' ),
    true,
    'schema_privs_are(schema, role, privs, desc)',
    'whatever',
    ''
);

Explanation: SQL assertion from pgTAP test suite for Privs.


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

INSERT INTO combocidtest SELECT 1 LIMIT 0;

Explanation: DML from PostgreSQL core regression test for Combocid.


Question: pgTAP test for Functap (assertion 18).

SELECT * FROM check_test(
    has_function( 'age', '{timestamptz,timestamptz}'::name[] ),
    true,
    'simple function with 2 args',
    'Function age(timestamptz, timestamptz) should exist',
    ''
);

Explanation: SQL assertion from pgTAP test suite for Functap.


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

Explanation: DDL from PostgreSQL core regression test for Indexing.


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

select jsonb_path_query('"inf"', '$.double()', silent => true);

SELECT count(*) FROM (select jsonb_path_query('"inf"', '$.double()', silent => true)) AS _sub;


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

Explanation: DDL from PostgreSQL core regression test for Join.


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

-- test jsonb null -> python None
CREATE FUNCTION test1null(val jsonb) RETURNS int
LANGUAGE plpython3u
TRANSFORM FOR TYPE jsonb
AS $$
assert(val == None)
return 1
$$;

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


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

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

SELECT count(*) FROM (select ln(9.342536355e34)) AS _sub;


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

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


Question: pgTAP test for Cmpok (assertion 4).

Explanation: SQL assertion from pgTAP test suite for Cmpok.


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

SELECT * FROM pg_partition_ancestors('ptif_test01_index');

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

SELECT count(*) FROM (SELECT * FROM pg_partition_ancestors('ptif_test01_index')) AS _sub;


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

SELECT * FROM check_estimated_rows('SELECT * FROM functional_dependencies WHERE a IN (1, 2, 26, 27, 51, 52, 76, 77) AND b IN (''1'', ''2'', ''26'', ''27'') AND c IN (1, 2)');

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

SELECT count(*) FROM (SELECT * FROM check_estimated_rows('SELECT * FROM functional_dependencies WHERE a IN (1, 2, 26, 27, 51, 52, 76, 77) AND b IN (''1'', ''2'', ''26'', ''27'') AND c IN (1, 2)')) AS _sub;


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

CREATE VIEW temp_view_test.v3_temp AS SELECT * FROM temp_table;

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


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

CREATE TABLE multiple_part_key(time TIMESTAMPTZ, time2 TIMESTAMP, device TEXT) PARTITION BY RANGE (time, time2) WITH (timescaledb.hypertable, timescaledb.partition_column='time');

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


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

SELECT t1."C 1", t2.c1, t3.c1 FROM "S 1"."T 1" t1 full join ft1 t2 full join ft2 t3 on (t2.c1 = t3.c1) on (t3.c1 = t1."C 1") OFFSET 100 LIMIT 10;

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


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

DELETE FROM temporal_mltrng WHERE id = '[5,6)';

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


Question: pgTAP test for Hastap (assertion 242).

SELECT * FROM check_test(
  has_opclass( 'int4_ops' ),
  true,
  'has_opclass( name )',
  'Operator class int4_ops should exist',
  ''
);

Explanation: SQL assertion from pgTAP test suite for Hastap.


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

CREATE TABLE fail_part PARTITION OF list_parted2 FOR VALUES IN (null);

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


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

SELECT count(*) FROM radix_text_tbl WHERE t ^@	 'Worth';

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

SELECT count(*) FROM (SELECT count(*) FROM radix_text_tbl WHERE t ^@	 'Worth') AS _sub;


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

CREATE TABLE pub_testpart2.child_parent1 partition of pub_testpart1.parent1 for values in (1);

Explanation: DDL from PostgreSQL core regression test for Publication.


Question: pgTAP test for Ruletap (assertion 19).

SELECT * FROM check_test(
    hasnt_rule( 'public', 'sometab', 'ins_me', 'whatever' ),
    false,
    'hasnt_rule(schema, table, rule, desc)',
    'whatever',
    ''
);

Explanation: SQL assertion from pgTAP test suite for Ruletap.


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

CREATE TABLE ATACC1 (TEST INT, TEST2 INT
	CHECK (TEST > 0), CHECK (TEST2 > 10) NO INHERIT);

Explanation: DDL from PostgreSQL core regression test for Constraints.


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

-- implicit cast during assignment is a separate code path, test that too

create or replace function dom_check(int) returns di as $$
declare d di;
begin
  d := $1;
  return d;
end
$$ language plpgsql immutable;

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


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

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

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

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


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

Explanation: DDL from PostgreSQL core regression test for Rowsecurity.


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

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

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


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

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


Question: pgTAP test for Hastap (assertion 160).

SELECT * FROM check_test(
    hasnt_cast( 'INT4', 'INT8', 'foo', 'desc' ),
    true,
    'hasnt_cast( src, targ, func, desc ) fail',
    'desc',
    ''
);


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

Explanation: DDL from PostgreSQL core regression test for Portals.


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

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

SELECT count(*) FROM (SELECT int2 '-0o100000') AS _sub;


Question: pgTAP test for Inheritance (assertion 46).

SELECT * FROM check_test(
    is_ancestor_of( 'hide', 'h_parent', 'hide', 'h_child1'::name ),
    true,
    'is_ancestor_of(psch, ptab, csch, ctab)',
    'Table hide.h_parent should be an ancestor of hide.h_child1',
    ''
);

Explanation: SQL assertion from pgTAP test suite for Inheritance.


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

/*
 * Function to manage pre-creation of the next partitions in a set.
 * Also manages dropping old partitions if the retention option is set.
 * If p_parent_table is passed, will only run run_maintenance() on that one table (no matter what the configuration table may have set for it)
 * Otherwise, will run on all tables in the config table with p_run_maintenance() set to true.
 * For large partition sets, running analyze can cause maintenance to take longer than expected. Can set p_analyze to false to avoid a forced analyze run.
 * Be aware that constraint exclusion may not work properly until an analyze on the partition set is run.
 */
CREATE OR REPLACE FUNCTION run_maintenance(p_parent_table text DEFAULT NULL, p_analyze boolean DEFAULT true, p_jobmon boolean DEFAULT true, p_debug boolean DEFAULT false) RETURNS void
    LANGUAGE plpgsql SECURITY DEFINER
    AS $$
DECLARE

ex_context                      text;
ex_detail                       text;
ex_hint                         text;
ex_message                      text;
v_adv_lock                      boolean;
v_check_subpart                 int;
v_create_count                  int := 0;
v_current_partition             text;
v_current_partition_id          bigint;
v_current_partition_timestamp   timestamp;
v_datetime_string               text;
v_drop_count                    int := 0;
v_job_id                        bigint;
v_jobmon                        boolean;
v_jobmon_schema                 text;
v_last_partition                text;
v_last_partition_created        boolean;
v_last_partition_id             bigint;
v_last_partition_timestamp      timestamp;
v_max_id_parent                 bigint;
v_max_time_parent               timestamp;
v_new_search_path               text := '@extschema@,pg_temp';
v_next_partition_id             bigint;
v_next_partition_timestamp      timestamp;
v_old_search_path               text;
v_parent_schema                 text;
v_parent_tablename              text;
v_premade_count                 int;
v_premake_id_max                bigint;
v_premake_id_min                bigint;
v_premake_timestamp_min         timestamp;
v_premake_timestamp_max         timestamp;
v_row                           record;
v_row_max_id                    record;
v_row_max_time                  record;
v_row_sub                       record;
v_skip_maint                    boolean;
v_step_id                       bigint;
v_step_overflow_id              bigint;
v_sub_id_max                    bigint;
v_sub_id_max_suffix             bigint;
v_sub_id_min                    bigint;
v_sub_parent                    text;
v_sub_timestamp_max             timestamp;
v_sub_timestamp_max_suffix      timestamp;
v_sub_timestamp_min             timestamp;
v_tablename                     text;
v_tables_list_sql               text;

BEGIN

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

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

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

v_row := NULL; -- Ensure it's reset

v_tables_list_sql := 'SELECT parent_table
                , partition_type
                , partition_interval
                , control
                , premake
                , datetime_string
                , undo_in_progress
                , sub_partition_set_full
                , epoch
                , infinite_time_partitions
            FROM @extschema@.part_config
            WHERE sub_partition_set_full = false';

IF p_parent_table IS NULL THEN
    v_tables_list_sql := v_tables_list_sql || ' AND use_run_maintenance = true';
ELSE
    v_tables_list_sql := v_tables_list_sql || format(' AND parent_table = %L', p_parent_table);
END IF;

FOR v_row IN EXECUTE v_tables_list_sql
LOOP

    CONTINUE WHEN v_row.undo_in_progress;
    v_skip_maint := true; -- reset every loop

    -- Check for consistent data in part_config_sub table. Was unable to get this working properly as either a constraint or trigger.
    -- Would either delay raising an error until the next write (which I cannot predict) or disallow future edits to update a sub-partition set's configuration.
    -- This way at least provides a consistent way to check that I know will run. If anyone can get a working constraint/trigger, please help!
    -- Don't have to worry about this in the serial trigger maintenance since subpartitioning requires run_maintenance().
    SELECT sub_parent INTO v_sub_parent FROM @extschema@.part_config_sub WHERE sub_parent = v_row.parent_table;
    IF v_sub_parent IS NOT NULL THEN
        SELECT count(*) INTO v_check_subpart FROM @extschema@.check_subpart_sameconfig(v_row.parent_table);
        IF v_check_subpart > 1 THEN
            RAISE EXCEPTION 'Inconsistent data in part_config_sub table. Sub-partition tables that are themselves sub-partitions cannot have differing configuration values among their siblings.
            Run this query: "SELECT * FROM @extschema@.check_subpart_sameconfig(''%'');" This should only return a single row or nothing.
            If multiple rows are returned, results are all children of the given parent. Update the differing values to be consistent for your desired values.', v_row.sub_parent;
        END IF;
    END IF;

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

    SELECT partition_tablename INTO v_last_partition FROM @extschema@.show_partitions(v_row.parent_table, 'DESC') LIMIT 1;
    IF p_debug THEN
        RAISE NOTICE 'run_maint: parent_table: %, v_last_partition: %', v_row.parent_table, v_last_partition;
    END IF;

    IF v_row.partition_type = 'time' OR v_row.partition_type = 'time-custom' THEN

        SELECT child_start_time INTO v_last_partition_timestamp
            FROM @extschema@.show_partition_info(v_parent_schema||'.'||v_last_partition, v_row.partition_interval, v_row.parent_table);

        -- Loop through child tables starting from highest to get current max value in partition set
        -- Avoids doing a scan on entire partition set and/or getting any values accidentally in parent.
        FOR v_row_max_time IN
            SELECT partition_schemaname, partition_tablename FROM @extschema@.show_partitions(v_row.parent_table, 'DESC')
        LOOP
            IF v_row.epoch = false THEN
                EXECUTE format('SELECT max(%I)::text FROM %I.%I'
                                    , v_row.control
                                    , v_row_max_time.partition_schemaname
                                    , v_row_max_time.partition_tablename
                                ) INTO v_current_partition_timestamp;
            ELSE
                EXECUTE format('SELECT to_timestamp(max(%I))::text FROM %I.%I'
                                    , v_row.control
                                    , v_row_max_time.partition_schemaname
                                    , v_row_max_time.partition_tablename
                                ) INTO v_current_partition_timestamp;
            END IF;
            IF v_current_partition_timestamp IS NOT NULL THEN
                SELECT suffix_timestamp INTO v_current_partition_timestamp FROM @extschema@.show_partition_name(v_row.parent_table, v_current_partition_timestamp::text);
                EXIT;
            END IF;
        END LOOP;
        -- Check for values in the parent table. If they are there and greater than all child values, use that instead
        -- This allows maintenance to continue working properly if there is a large gap in data insertion. Data will remain in parent, but new tables will be created
        IF v_row.epoch = false THEN
            EXECUTE format('SELECT max(%I) FROM ONLY %I.%I', v_row.control, v_parent_schema, v_parent_tablename) INTO v_max_time_parent;
        ELSE
            EXECUTE format('SELECT to_timestamp(max(%I)) FROM ONLY %I.%I', v_row.control, v_parent_schema, v_parent_tablename) INTO v_max_time_parent;
        END IF;
        IF p_debug THEN
            RAISE NOTICE 'run_maint: v_current_partition_timestamp: %, v_max_time_parent: %', v_current_partition_timestamp, v_max_time_parent;
        END IF;
        IF v_max_time_parent > v_current_partition_timestamp THEN
            SELECT suffix_timestamp INTO v_current_partition_timestamp FROM @extschema@.show_partition_name(v_row.parent_table, v_max_time_parent::text);
        END IF;
        IF v_current_partition_timestamp IS NULL THEN -- Partition set is completely empty
            IF v_row.infinite_time_partitions IS TRUE THEN
                -- Set it to now so new partitions continue to be created
                v_current_partition_timestamp = CURRENT_TIMESTAMP;
            ELSE
                -- Nothing to do
                CONTINUE;
            END IF;
        END IF;

        -- If this is a subpartition, determine if the last child table has been made. If so, mark it as full so future maintenance runs can skip it
        SELECT sub_min::timestamp, sub_max::timestamp INTO v_sub_timestamp_min, v_sub_timestamp_max FROM @extschema@.check_subpartition_limits(v_row.parent_table, 'time');
        IF v_sub_timestamp_max IS NOT NULL THEN
            SELECT suffix_timestamp INTO v_sub_timestamp_max_suffix FROM @extschema@.show_partition_name(v_row.parent_table, v_sub_timestamp_max::text);
            IF v_sub_timestamp_max_suffix = v_last_partition_timestamp THEN
                -- Final partition for this set is created. Set full and skip it
                UPDATE @extschema@.part_config SET sub_partition_set_full = true WHERE parent_table = v_row.parent_table;
                CONTINUE;
            END IF;
        END IF;

        -- Check and see how many premade partitions there are.
        v_premade_count = round(EXTRACT('epoch' FROM age(v_last_partition_timestamp, v_current_partition_timestamp)) / EXTRACT('epoch' FROM v_row.partition_interval::interval));
        v_next_partition_timestamp := v_last_partition_timestamp;
        IF p_debug THEN
            RAISE NOTICE 'run_maint before loop: current_partition_timestamp: %, v_premade_count: %, v_sub_timestamp_min: %, v_sub_timestamp_max: %'
                , v_current_partition_timestamp
                , v_premade_count
                , v_sub_timestamp_min
                , v_sub_timestamp_max;
        END IF;
        -- Loop premaking until config setting is met. Allows it to catch up if it fell behind or if premake changed
        WHILE (v_premade_count < v_row.premake) LOOP
            IF p_debug THEN
                RAISE NOTICE 'run_maint: parent_table: %, v_premade_count: %, v_next_partition_timestamp: %', v_row.parent_table, v_premade_count, v_next_partition_timestamp;
            END IF;
            IF v_next_partition_timestamp < v_sub_timestamp_min OR v_next_partition_timestamp > v_sub_timestamp_max THEN
                -- With subpartitioning, no need to run if the timestamp is not in the parent table's range
                EXIT;
            END IF;
            BEGIN
                v_next_partition_timestamp := v_next_partition_timestamp + v_row.partition_interval::interval;
            EXCEPTION WHEN datetime_field_overflow THEN
                v_premade_count := v_row.premake; -- do this so it can exit the premake check loop and continue in the outer for loop
                IF v_jobmon_schema IS NOT NULL THEN
                    v_step_overflow_id := add_step(v_job_id, 'Attempted partition time interval is outside PostgreSQL''s supported time range.');
                    PERFORM update_step(v_step_overflow_id, 'CRITICAL', format('Child partition creation skipped for parent table: %s', v_partition_time));
                END IF;
                RAISE WARNING 'Attempted partition time interval is outside PostgreSQL''s supported time range. Child partition creation skipped for parent table %', v_row.parent_table;
                CONTINUE;
            END;
            v_last_partition_created := @extschema@.create_partition_time(v_row.parent_table, ARRAY[v_next_partition_timestamp], p_analyze);
            IF v_last_partition_created THEN
                v_create_count := v_create_count + 1;
                PERFORM @extschema@.create_function_time(v_row.parent_table, v_job_id);
            END IF;

            v_premade_count = round(EXTRACT('epoch' FROM age(v_next_partition_timestamp, v_current_partition_timestamp)) / EXTRACT('epoch' FROM v_row.partition_interval::interval));
        END LOOP;
    ELSIF v_row.partition_type = 'id' THEN
        -- Loop through child tables starting from highest to get current max value in partition set
        -- Avoids doing a scan on entire partition set and/or getting any values accidentally in parent.
        FOR v_row_max_id IN
            SELECT partition_schemaname, partition_tablename FROM @extschema@.show_partitions(v_row.parent_table, 'DESC')
        LOOP
            EXECUTE format('SELECT max(%I)::text FROM %I.%I'
                            , v_row.control
                            , v_row_max_id.partition_schemaname
                            , v_row_max_id.partition_tablename) INTO v_current_partition_id;
            IF v_current_partition_id IS NOT NULL THEN
                SELECT suffix_id INTO v_current_partition_id FROM @extschema@.show_partition_name(v_row.parent_table, v_current_partition_id::text);
                EXIT;
            END IF;
        END LOOP;
        -- Check for values in the parent table. If they are there and greater than all child values, use that instead
        -- This allows maintenance to continue working properly if there is a large gap in data insertion. Data will remain in parent, but new tables will be created
        EXECUTE format('SELECT max(%I) FROM ONLY %I.%I', v_row.control, v_parent_schema, v_parent_tablename) INTO v_max_id_parent;
        IF v_max_id_parent > v_current_partition_id THEN
            SELECT suffix_id INTO v_current_partition_id FROM @extschema@.show_partition_name(v_row.parent_table, v_max_id_parent::text);
        END IF;
        IF v_current_partition_id IS NULL THEN
            -- Partition set is completely empty. Nothing to do
            CONTINUE;
        END IF;

        SELECT child_start_id INTO v_last_partition_id
            FROM @extschema@.show_partition_info(v_parent_schema||'.'||v_last_partition, v_row.partition_interval, v_row.parent_table);
        -- Determine if this table is a child of a subpartition parent. If so, get limits to see if run_maintenance even needs to run for it.
        SELECT sub_min::bigint, sub_max::bigint INTO v_sub_id_min, v_sub_id_max FROM @extschema@.check_subpartition_limits(v_row.parent_table, 'id');
        IF v_sub_id_max IS NOT NULL THEN
            SELECT suffix_id INTO v_sub_id_max_suffix FROM @extschema@.show_partition_name(v_row.parent_table, v_sub_id_max::text);
            IF v_sub_id_max_suffix = v_last_partition_id THEN
                -- Final partition for this set is created. Set full and skip it
                UPDATE @extschema@.part_config SET sub_partition_set_full = true WHERE parent_table = v_row.parent_table;
                CONTINUE;
            END IF;
        END IF;

        v_next_partition_id := v_last_partition_id;
        v_premade_count := ((v_last_partition_id - v_current_partition_id) / v_row.partition_interval::bigint);
        -- Loop premaking until config setting is met. Allows it to catch up if it fell behind or if premake changed.
        WHILE (v_premade_count < v_row.premake) LOOP
            IF p_debug THEN
                RAISE NOTICE 'run_maint: parent_table: %, v_premade_count: %, v_next_partition_id: %', v_row.parent_table, v_premade_count, v_next_partition_id;
            END IF;
            IF v_next_partition_id < v_sub_id_min OR v_next_partition_id > v_sub_id_max THEN
                -- With subpartitioning, no need to run if the id is not in the parent table's range
                EXIT;
            END IF;
            v_next_partition_id := v_next_partition_id + v_row.partition_interval::bigint;
            v_last_partition_created := @extschema@.create_partition_id(v_row.parent_table, ARRAY[v_next_partition_id], p_analyze);
            IF v_last_partition_created THEN
                v_create_count := v_create_count + 1;
                PERFORM @extschema@.create_function_id(v_row.parent_table, v_job_id);
            END IF;
            v_premade_count := ((v_next_partition_id - v_current_partition_id) / v_row.partition_interval::bigint);
        END LOOP;

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

END LOOP; -- end of creation loop

-- Manage dropping old partitions if retention option is set
FOR v_row IN
    SELECT parent_table FROM @extschema@.part_config WHERE retention IS NOT NULL AND undo_in_progress = false AND
        (partition_type = 'time' OR partition_type = 'time-custom')
LOOP
    IF p_parent_table IS NULL THEN
        v_drop_count := v_drop_count + @extschema@.drop_partition_time(v_row.parent_table);
    ELSE -- Only run retention on table given in parameter
        IF p_parent_table <> v_row.parent_table THEN
            CONTINUE;
        ELSE
            v_drop_count := v_drop_count + @extschema@.drop_partition_time(v_row.parent_table);
        END IF;
    END IF;
    IF v_drop_count > 0 THEN
        PERFORM @extschema@.create_function_time(v_row.parent_table, v_job_id);
    END IF;
END LOOP;
FOR v_row IN
    SELECT parent_table FROM @extschema@.part_config WHERE retention IS NOT NULL AND undo_in_progress = false AND partition_type = 'id'
LOOP
    IF p_parent_table IS NULL THEN
        v_drop_count := v_drop_count + @extschema@.drop_partition_id(v_row.parent_table);
    ELSE -- Only run retention on table given in parameter
        IF p_parent_table <> v_row.parent_table THEN
            CONTINUE;
        ELSE
            v_drop_count := v_drop_count + @extschema@.drop_partition_id(v_row.parent_table);
        END IF;
    END IF;
    IF v_drop_count > 0 THEN
        PERFORM @extschema@.create_function_id(v_row.parent_table, v_job_id);
    END IF;
END LOOP;

IF v_jobmon_schema IS NOT NULL THEN
    PERFORM update_step(v_step_id, 'OK', format('Partition maintenance finished. %s partitions made. %s partitions dropped.', v_create_count, v_drop_count));
    IF v_step_overflow_id IS NOT NULL THEN
        PERFORM fail_job(v_job_id);
    ELSE
        PERFORM close_job(v_job_id);
    END IF;
END IF;

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

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 RUN MAINTENANCE'')', v_jobmon_schema) INTO v_job_id;
                EXECUTE format('SELECT %I.add_step(%s, ''EXCEPTION before job logging started'')', v_jobmon_schema, v_job_id, p_parent_table) INTO v_step_id;
            ELSIF v_step_id IS NULL THEN
                EXECUTE format('SELECT %I.add_step(%s, ''EXCEPTION before first step logged'')', v_jobmon_schema, v_job_id) INTO v_step_id;
            END IF;
            EXECUTE format('SELECT %I.update_step(%s, ''CRITICAL'', %L)', v_jobmon_schema, v_step_id, 'ERROR: '||coalesce(SQLERRM,'unknown'));
            EXECUTE format('SELECT %I.fail_job(%s)', v_jobmon_schema, v_job_id);
        END IF;
        RAISE EXCEPTION '%
CONTEXT: %
DETAIL: %
HINT: %', ex_message, ex_context, ex_detail, ex_hint;
END
$$;

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


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

select * from boolpart where a is not true and a is not false;

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

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


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

Explanation: DDL from PostgreSQL core regression test for Guc.


Question: Show a SQL definition from the timescaledb project (drop_hypertable, item 30).

CREATE TABLE t2 (time timestamptz) WITH (tsdb.hypertable);

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


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

create trigger parted_trigger after update of b on parted_trigger
  for each row execute procedure trigger_notice_ab();

Explanation: DDL from PostgreSQL core regression test for Triggers.


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

CREATE TABLE trunc_a2 PARTITION OF trunc_a FOR VALUES FROM (10) TO (20)
  PARTITION BY RANGE (a);

Explanation: DDL from PostgreSQL core regression test for Truncate.


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

DELETE FROM temporal_partitioned_rng WHERE id = '[5,6)' AND valid_at = daterange('2018-02-01', '2018-03-01');

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


Question: PostgreSQL Query: show example 28.

SELECT city, count(*) FILTER (WHERE temp_lo < 45), max(temp_lo) FROM weather GROUP BY city;

Explanation: Example from PostgreSQL documentation on Query.


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

CREATE TABLE part_a_10_a_20 PARTITION OF range_parted FOR VALUES FROM ('a', 10) TO ('a', 20);

Explanation: DDL from PostgreSQL core regression test for Update.


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

SELECT to_timestamp('2024 613566758 1', 'YYYY WW D');

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

SELECT count(*) FROM (SELECT to_timestamp('2024 613566758 1', 'YYYY WW D')) AS _sub;


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

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

SELECT count(*) FROM (SELECT make_timestamptz(1973, 07, 15, 08, 15, 55.33, '-2')) AS _sub;


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

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


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

CREATE UNLOGGED TABLE public.unlogged2 (a int primary key);		-- also OK
CREATE UNLOGGED TABLE pg_temp.unlogged3 (a int primary key);	-- not OK
CREATE TABLE pg_temp.implicitly_temp (a int primary key);		-- OK
CREATE TEMP TABLE explicitly_temp (a int primary key);			-- also OK
CREATE TEMP TABLE pg_temp.doubly_temp (a int primary key);		-- also OK
CREATE TEMP TABLE public.temp_to_perm (a int primary key);		-- not OK
DROP TABLE unlogged1, public.unlogged2;

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


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

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


Question: Show a SQL definition from the timescaledb project (create_table_with, item 49).

CREATE TABLE IF NOT EXISTS t9(time date NOT NULL, device text, value float) WITH (tsdb.columnstore=false,tsdb.hypertable,tsdb.partition_column='time',tsdb.chunk_interval='3 months');


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

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


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

CREATE FUNCTION alt_func1(int) RETURNS int LANGUAGE sql
  AS 'SELECT $1 + 1';

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


Question: pgTAP test for Proctap (assertion 11).

-- is_procedure ( NAME, NAME, NAME[], TEXT )
-- isnt_procedure ( NAME, NAME, NAME[], TEXT )
SELECT * FROM check_test(
    is_procedure( 'procschema', 'aproc', '{}'::name[], 'whatever' ),
    true,
    'is_procedure(schema, proc, noargs, desc)',
    'whatever',
    ''
);

Explanation: SQL assertion from pgTAP test suite for Proctap.


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

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

SELECT count(*) FROM (select 'four: ' || 2+2) AS _sub;


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

SELECT * FROM rngfuncb(42, 99) AS p(a,b);

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

SELECT count(*) FROM (SELECT * FROM rngfuncb(42, 99) AS p(a,b)) AS _sub;


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

-- type_owner_is ( schema, type, user, description )
CREATE OR REPLACE FUNCTION type_owner_is ( NAME, NAME, NAME, TEXT )
RETURNS TEXT AS $$
DECLARE
    owner NAME := _get_type_owner($1, $2);
BEGIN
    -- Make sure the type exists.
    IF owner IS NULL THEN
        RETURN ok(FALSE, $4) || E'\n' || diag(
            E'    Type ' || quote_ident($1) || '.' || quote_ident($2) || ' not found'
        );
    END IF;

    RETURN is(owner, $3, $4);
END;
$$ LANGUAGE plpgsql;

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


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

/*
 * Given a parent table and partition value, return the name of the child partition it would go in.
 * Also returns just the suffix value and true if the child table exists or false if it does not
 */
CREATE FUNCTION show_partition_name(p_parent_table text, p_value text, OUT partition_table text, OUT suffix_timestamp timestamp, OUT suffix_id bigint, OUT table_exists boolean) RETURNS record
    LANGUAGE plpgsql STABLE
    AS $$
DECLARE

v_child_exists          text;
v_datetime_string       text;
v_max_range             timestamptz;
v_min_range             timestamptz;
v_parent_schema         text;
v_parent_tablename      text;
v_partition_interval    text;
v_time_position         int;
v_type                  text;

BEGIN

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;

IF v_type IS NULL THEN
    RAISE EXCEPTION 'Parent table given is not managed by pg_partman (%)', p_parent_table;
END IF;

SELECT schemaname, tablename INTO v_parent_schema, v_parent_tablename FROM pg_catalog.pg_tables WHERE schemaname ||'.'|| tablename = p_parent_table;
IF v_parent_tablename IS NULL THEN
    RAISE EXCEPTION 'Parent table given does not exist (%)', p_parent_table;
END IF;

IF v_type = 'time' THEN
    CASE
        WHEN v_partition_interval::interval = '15 mins' THEN
            suffix_timestamp := date_trunc('hour', p_value::timestamp) +
                '15min'::interval * floor(date_part('minute', p_value::timestamp) / 15.0);
        WHEN v_partition_interval::interval = '30 mins' THEN
            suffix_timestamp := date_trunc('hour', p_value::timestamp) +
                '30min'::interval * floor(date_part('minute', p_value::timestamp) / 30.0);
        WHEN v_partition_interval::interval = '1 hour' THEN
            suffix_timestamp := date_trunc('hour', p_value::timestamp);
        WHEN v_partition_interval::interval = '1 day' THEN
            suffix_timestamp := date_trunc('day', p_value::timestamp);
        WHEN v_partition_interval::interval = '1 week' THEN
            suffix_timestamp := date_trunc('week', p_value::timestamp);
        WHEN v_partition_interval::interval = '1 month' THEN
            suffix_timestamp := date_trunc('month', p_value::timestamp);
        WHEN v_partition_interval::interval = '3 months' THEN
            suffix_timestamp := date_trunc('quarter', p_value::timestamp);
        WHEN v_partition_interval::interval = '1 year' THEN
            suffix_timestamp := date_trunc('year', p_value::timestamp);
    END CASE;
    partition_table := v_parent_schema||'.'||@extschema@.check_name_length(v_parent_tablename, to_char(suffix_timestamp, v_datetime_string), TRUE);
ELSIF v_type = 'id' THEN
    suffix_id := (p_value::bigint - (p_value::bigint % v_partition_interval::bigint));
    partition_table := v_parent_schema||'.'||@extschema@.check_name_length(v_parent_tablename, suffix_id::text, TRUE);
ELSIF v_type = 'time-custom' THEN

    SELECT child_table, lower(partition_range) INTO partition_table, suffix_timestamp FROM @extschema@.custom_time_partitions
        WHERE parent_table = p_parent_table AND partition_range @> p_value::timestamptz;

    IF partition_table IS NULL THEN
        SELECT max(upper(partition_range)) INTO v_max_range FROM @extschema@.custom_time_partitions WHERE parent_table = p_parent_table;
        SELECT min(lower(partition_range)) INTO v_min_range FROM @extschema@.custom_time_partitions WHERE parent_table = p_parent_table;
        IF p_value::timestamp >= v_max_range THEN
            suffix_timestamp := v_max_range;
            LOOP
                -- Keep incrementing higher until given value is below the upper range
                suffix_timestamp := suffix_timestamp + v_partition_interval::interval;
                IF p_value::timestamp < suffix_timestamp THEN
                    -- Have to subtract one interval because the value would actually be in the partition previous
                    --      to this partition timestamp since the partition names contain the lower boundary
                    suffix_timestamp := suffix_timestamp - v_partition_interval::interval;
                    EXIT;
                END IF;
            END LOOP;
        ELSIF p_value::timestamp < v_min_range THEN
            suffix_timestamp := v_min_range;
            LOOP
                -- Keep decrementing lower until given value is below or equal to the lower range
                suffix_timestamp := suffix_timestamp - v_partition_interval::interval;
                IF p_value::timestamp >= suffix_timestamp THEN
                    EXIT;
                END IF;
            END LOOP;
        ELSE
            RAISE EXCEPTION 'Unable to determine a valid child table for the given parent table and value';
        END IF;

        partition_table := v_parent_schema||'.'||@extschema@.check_name_length(v_parent_tablename, to_char(suffix_timestamp, v_datetime_string), TRUE);
    END IF;
END IF;

SELECT schemaname, tablename INTO v_child_exists FROM pg_catalog.pg_tables WHERE schemaname ||'.'|| tablename = partition_table;

IF v_child_exists IS NOT NULL THEN
    table_exists := true;
ELSE
    table_exists := false;
END IF;

RETURN;

END
$$;

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


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

INSERT INTO users (fname, lname, username) VALUES ('charles', 'darwin', 'beagle');

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


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

SELECT cube_ll_coord(ll_to_earth(0,180),1)::numeric(20,5),
 cube_ll_coord(ll_to_earth(0,180),2)::numeric(20,5),
 cube_ll_coord(ll_to_earth(0,180),3)::numeric(20,5);

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


Question: pgTAP test for Hastap (assertion 4).

-- Create a partition.
CREATE FUNCTION mkpart() RETURNS SETOF TEXT AS $$
BEGIN
    IF pg_version_num() >= 100000 THEN
        EXECUTE $E$
            CREATE TABLE public.apart (dt DATE NOT NULL) PARTITION BY RANGE (dt);
        $E$;
    ELSE
    EXECUTE $E$
        CREATE TABLE public.apart (dt DATE NOT NULL);
    $E$;
    END IF;
    RETURN;
END;
$$ LANGUAGE plpgsql;

Explanation: SQL assertion from pgTAP test suite for Hastap.


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

SELECT aggfnoid, aggtransfn, aggcombinefn, aggtranstype::regtype,
       aggserialfn, aggdeserialfn, aggfinalmodify
FROM pg_aggregate
WHERE aggfnoid = 'myavg'::REGPROC;

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

SELECT count(*) FROM (SELECT aggfnoid, aggtransfn, aggcombinefn, aggtranstype::regtype,
       aggserialfn, aggdeserialfn, aggfinalmodify
FROM pg_aggregate
WHERE aggfnoid = 'myavg'::REGPROC) AS _sub;


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

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

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


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

CREATE ACCESS METHOD bogus TYPE INDEX HANDLER heap_tableam_handler;

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


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

CREATE TABLE ptif_test3 PARTITION OF ptif_test
  FOR VALUES FROM (200) TO (maxvalue) PARTITION BY list (b);

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


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

end$$ language plpgsql;

select stricttest();

-- test warnings and errors
set plpgsql.extra_warnings to 'all';
set plpgsql.extra_warnings to 'none';
set plpgsql.extra_errors to 'all';
set plpgsql.extra_errors to 'none';

-- test warnings when shadowing a variable

set plpgsql.extra_warnings to 'shadowed_variables';

-- simple shadowing of input and output parameters
create or replace function shadowtest(in1 int)
	returns table (out1 int) as $$
declare
in1 int;

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


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

select (select max(unique1) filter (where bool_or(ten > 0)) from int8_tbl) from tenk1;

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

SELECT count(*) FROM (select (select max(unique1) filter (where bool_or(ten > 0)) from int8_tbl) from tenk1) AS _sub;


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

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


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

Explanation: DML from PostgreSQL core regression test for Rules.


Question: Show a SQL definition from the citus project (pg13, item 22).

-- alter view rename column works fine
CREATE VIEW v AS SELECT * FROM dist_table;

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


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

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

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


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

CREATE UNIQUE INDEX unique_idx4 ON unique_tbl (i) NULLS NOT DISTINCT;  -- ok now

\d unique_tbl
\d unique_idx3
\d unique_idx4
SELECT pg_get_indexdef('unique_idx3'::regclass);

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


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

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


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

insert into vc4table values(array['too long']);  -- fail
insert into vc4table values(array['too long']::vc4[]);  -- cast truncates
select * from vc4table;

Explanation: DML from PostgreSQL core regression test for Domain.


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

select sum(ss.tst::int) from
  onek o cross join lateral (
  select i.ten in (select f1 from int4_tbl where f1 <= o.hundred) as tst,
         random() as r
  from onek i where i.unique1 = o.unique1 ) ss
where o.ten = 0;

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

SELECT count(*) FROM (select sum(ss.tst::int) from
  onek o cross join lateral (
  select i.ten in (select f1 from int4_tbl where f1 <= o.hundred) as tst,
         random() as r
  from onek i where i.unique1 = o.unique1 ) ss
where o.ten = 0) AS _sub;


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

CREATE OR REPLACE RULE y_rule AS ON INSERT TO y DO INSTEAD NOTIFY foo;

Explanation: DDL from PostgreSQL core regression test for With.


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

CREATE OPERATOR = (
	PROCEDURE = isneq,
	LEFTARG = isbn13,
	RIGHTARG = isbn,
	COMMUTATOR = =,
	NEGATOR = <>,
	RESTRICT = eqsel,
	JOIN = eqjoinsel,
	MERGES,
	HASHES);

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


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

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

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


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

SELECT octet_length(get_raw_page('test1', 'main', 0)) AS main_0;

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


Question: pgTAP test for Resultset (assertion 257).

-- Handle failure due to missing dupe.
SELECT * FROM check_test(
    bag_eq(
        'SELECT 1 AS a, ''Anna''::text AS b UNION ALL SELECT 86, ''Angelina'' UNION ALL SELECT 1, ''Anna''',
        'SELECT 1 AS a, ''Anna''::TEXT AS b UNION ALL SELECT 86, ''Angelina'''
    ),
    false,
    'bag_eq(values, values) fail missing dupe',
    '',
    '    Extra records:
        (1,Anna)'
);

Explanation: SQL assertion from pgTAP test suite for Resultset.


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

UPDATE part_b_10_b_20 set c = c + 20 returning c, b, a;

Explanation: DML from PostgreSQL core regression test for Update.


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

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

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


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

SELECT rpad('hi'::text,   5, 'xy'::citext) = 'hixyx' AS t;

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


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

SELECT * FROM test_squash WHERE id = ANY (ARRAY[1, 2, 3, 4, 5, 6, 7, 8, 9])
    AND data = ANY (ARRAY[1, 2, 3, 4, 5, 6, 7, 8, 9]);

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


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

SELECT * FROM JSON_TABLE(jsonb '{"rec": "(1,2)"}', '$' COLUMNS (id FOR ORDINALITY, comp comp path '$.rec' omit quotes)) jt;

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

SELECT count(*) FROM (SELECT * FROM JSON_TABLE(jsonb '{"rec": "(1,2)"}', '$' COLUMNS (id FOR ORDINALITY, comp comp path '$.rec' omit quotes)) jt) AS _sub;


Question: pgTAP test for Valueset (assertion 333).

-- Compare with missing dupe.
SELECT * FROM check_test(
    results_ne(
        'VALUES (1, ''Anna''), (86, ''Angelina''), (1, ''Anna'')',
        'VALUES (1, ''Anna''), (86, ''Angelina'')'
    ),
    true,
    'results_ne(values dupe, values)',
    '',
    ''
);

Explanation: SQL assertion from pgTAP test suite for Valueset.


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

ALTER EXTENSION pgtap ADD FUNCTION _definer ( NAME, NAME, NAME[] );

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


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

$$;

SELECT create_and_insert();

TABLE ddl_test;

CREATE FUNCTION alter_and_insert() RETURNS VOID LANGUAGE sql AS $$
  alter table ddl_test alter column f1 type numeric;

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


Question: PL/pgSQL test: Plpython Transaction (example 29).

DO LANGUAGE plpython3u $$
for row in plpy.cursor("SELECT * FROM test2 ORDER BY x"):
    plpy.execute("INSERT INTO test1 (a) VALUES (%s)" % row['x'])
    plpy.rollback()
$$;

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


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

SELECT count(*) FROM tstu WHERE i = 7 AND t = '5';

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


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

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

SELECT count(*) FROM (select '1'::xid != '1'::xid8::xid) AS _sub;


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

select interval '2147483647 months 0.1 yrs';

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

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


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

INSERT INTO num_typemod_test (thousands) VALUES (999500);

Explanation: DML from PostgreSQL core regression test for Numeric.


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

insert into rtest_view3 select * from rtest_vview3;

Explanation: DML from PostgreSQL core regression test for Rules.


Question: pgTAP test for Unique (assertion 12).

SELECT * FROM check_test(
    col_is_unique( 'public', 'sometab', ARRAY['numb', 'myint'], 'public.sometab.numb+myint should be unique' ),
    true,
    'col_is_unique( schema, table, columns, description )',
    'public.sometab.numb+myint should be unique',
    ''
);

Explanation: SQL assertion from pgTAP test suite for Unique.


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

CREATE TABLE salespeople2_5(salesperson_id INT NOT NULL, salesperson_name VARCHAR(30));

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


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

CREATE POLICY p1 ON b1 USING (a % 2 = 0);

Explanation: DDL from PostgreSQL core regression test for Rowsecurity.


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

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

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


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

select multirange_of_text(textrange2('a','Z'));  -- should fail
select multirange_of_text(textrange1('a','Z')) @> 'b'::text;

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

SELECT count(*) FROM (select multirange_of_text(textrange2('a','Z'));  -- should fail
select multirange_of_text(textrange1('a','Z')) @> 'b'::text) AS _sub;


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

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

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


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

select jsonb_path_query('[[null, 1, "abc", "abcabc"]]', 'lax $ ? (@[*] starts with "abc")');

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

SELECT count(*) FROM (select jsonb_path_query('[[null, 1, "abc", "abcabc"]]', 'lax $ ? (@[*] starts with "abc")')) AS _sub;


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

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

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


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

SELECT count(*) FROM quad_box_tbl WHERE b &<| box '((100,200),(300,500))';

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

SELECT count(*) FROM (SELECT count(*) FROM quad_box_tbl WHERE b &<| box '((100,200),(300,500))') AS _sub;


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

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

SELECT count(*) FROM (SELECT timestamptz(date '1994-01-01', time '11:00') AS "Jan_01_1994_10am") AS _sub;


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

select ts_headline('[]'::jsonb, tsquery('aaa & bbb'));

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

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


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

SELECT * FROM brin_revmap_data(get_raw_page('test1_a_idx', 1)) LIMIT 5;

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


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

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


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

CREATE INDEX ON test_jsonb_mutability (JSON_QUERY(js, '$.time_tz()'));

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


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

SELECT * FROM f_star* x WHERE x.c ISNULL;

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

SELECT count(*) FROM (SELECT * FROM f_star* x WHERE x.c ISNULL) AS _sub;


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

Explanation: DML from PostgreSQL core regression test for Inherit.


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

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


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

CREATE FUNCTION isnlt(issn, ean13)
	RETURNS boolean
	AS 'int8lt'
	LANGUAGE 'internal'
	IMMUTABLE STRICT
	PARALLEL SAFE;


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

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

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


Question: pgTAP test for Cmpok (assertion 3).

SELECT * FROM check_test(
    cmp_ok( 1, '<>', 2, '1 should <> 2' ),
    true,
    'cmp_ok( int, <>, int )',
    '1 should <> 2',
    ''
);

Explanation: SQL assertion from pgTAP test suite for Cmpok.


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

-- Can reference function with or without OUT params for DROP, etc
DROP FUNCTION rngfunc(int);

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


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

SELECT count(*) FROM (select jsonb_pretty('[{"f1":1,"f2":null},2,null,[[{"x":true},6,7],8],3]')) AS _sub;


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

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

SELECT count(*) FROM (SELECT CAST('922337203685477580700.0'::float8 AS int8)) AS _sub;


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


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

SELECT a,b,c,substring(d for 30), length(d) from clstr_tst ORDER BY c;

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

SELECT count(*) FROM (SELECT a,b,c,substring(d for 30), length(d) from clstr_tst ORDER BY c) AS _sub;


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

CREATE SERVER s8 FOREIGN DATA WRAPPER postgresql OPTIONS (foo '1'); -- ERROR
CREATE SERVER s8 FOREIGN DATA WRAPPER postgresql OPTIONS (host 'localhost', dbname 's8db');

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


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

INSERT INTO foo VALUES (9,'j','{"a9","b9","c9"}');

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


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


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

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


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

Explanation: DML from PostgreSQL core regression test for Window.


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

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

SELECT count(*) FROM (SELECT make_date(-2147483648, 1, 1)) AS _sub;


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

SELECT * FROM gin_metapage_info(get_raw_page('test1', 0));


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

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

SELECT count(*) FROM (SELECT 'N A N'::float8) AS _sub;


Question: Write the DDL statement from PostgreSQL regression test 'create_operator' (example 71).

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


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

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


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

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

SELECT count(*) FROM (SELECT to_regoper('||/')) AS _sub;


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

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


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

SELECT * FROM test_oid WHERE i>3::oid ORDER BY i;

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


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

INSERT INTO clstr_tst (b, c) VALUES (27, 'veintisiete');

Explanation: DML from PostgreSQL core regression test for Cluster.


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

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

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


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

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

SELECT count(*) FROM (SELECT to_number('viv', 'RN')) AS _sub;


Question: PostgreSQL Textsearch: show example 20.

ALTER TEXT SEARCH CONFIGURATION astro_en ADD MAPPING FOR asciiword WITH astrosyn, english_ispell, english_stem;

Explanation: Example from PostgreSQL documentation on Textsearch.


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

update rtest_v1 set b = 88 where b < 50;

Explanation: DML from PostgreSQL core regression test for Rules.


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

CREATE INDEX tbl_gist_idx ON tbl_gist using gist (c4) INCLUDE (c1,c2,c3);

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


Question: pgTAP test for Resultset (assertion 308).

DECLARE chave CURSOR FOR SELECT id, name from annames ORDER BY id;

Explanation: SQL assertion from pgTAP test suite for Resultset.


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

SELECT id FROM test_tablesample_v1 TABLESAMPLE BERNOULLI (1);

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

SELECT count(*) FROM (SELECT id FROM test_tablesample_v1 TABLESAMPLE BERNOULLI (1)) AS _sub;


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

SELECT jsonb_path_match('{}', 'strict $.a', silent => false);

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

SELECT count(*) FROM (SELECT jsonb_path_match('{}', 'strict $.a', silent => false)) AS _sub;


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

CREATE TABLE default_expr_non_column (a int DEFAULT (avg(non_existent)));

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


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

SELECT * FROM test_money WHERE i='1'::money ORDER BY i;


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

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

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


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

CREATE MATERIALIZED VIEW mvtest_tmm AS SELECT sum(totamt) AS grandtot FROM mvtest_tm;

Explanation: DDL from PostgreSQL core regression test for Matview.


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

SELECT regexp_match('foobarbequebazmorebarbequetoo'::citext, '(BAR)(BEQUE)'::citext, 'g') AS "error";

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


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

create view id_ordered as select * from id order by id;

Explanation: DDL from PostgreSQL core regression test for Rules.


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

SELECT '1,1'::cube < '1,2'::cube AS bool;

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


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

SELECT * FROM pglogical_regress_variables()
\gset

\c :provider_dsn

-- Test conflicts where a secondary unique constraint with a predicate exits,
-- ensuring we don't generate false conflicts.
SELECT pglogical.replicate_ddl_command($$
CREATE TABLE public.secondary_unique_pred (
    a integer PRIMARY KEY,
    b integer NOT NULL,
    check_unique boolean NOT NULL
);

CREATE UNIQUE INDEX ON public.secondary_unique_pred (b) WHERE (check_unique);
$$);

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


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

Explanation: DDL from PostgreSQL core regression test for Maintain Every.


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

INSERT INTO foo VALUES (2,'c','{"a2","b2","c2"}');

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


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

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

SELECT count(*) FROM (SELECT to_regtype('ng_catalog.int4')) AS _sub;


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

CREATE FUNCTION isnge(isbn13, isbn)
	RETURNS boolean
	AS 'int8ge'
	LANGUAGE 'internal'
	IMMUTABLE STRICT
	PARALLEL SAFE;

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


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

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


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

SELECT * FROM test_ne WHERE a <> '2009-01-01' AND b <> 10.7;

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


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

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


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

select ten, grouping(ten) from onek
group by cube(ten) having grouping(ten) > 0
order by 2,1;

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

SELECT count(*) FROM (select ten, grouping(ten) from onek
group by cube(ten) having grouping(ten) > 0
order by 2,1) AS _sub;


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

insert into dropcol(key, keep1, keep2) values(1, '4', 4) on conflict(key)
    do update set keep1 = excluded.keep1, keep2 = excluded.keep2
    where excluded.keep1 is not null and excluded.keep2 is not null
          and dropcol.keep1 is not null and dropcol.keep2 is not null
    returning *;

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


Question: Show a SQL definition from the pglogical project (pglogical--2.2.1, item 29).

CREATE FUNCTION pglogical.replication_set_remove_table(set_name name, relation regclass)
RETURNS boolean STRICT VOLATILE LANGUAGE c AS 'MODULE_PATHNAME', 'pglogical_replication_set_remove_table';


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

create function non_strict(text) returns text as
    'select coalesce($1, ''got passed a null'');'
    language sql called on null input;

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


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

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

SELECT count(*) FROM (SELECT xpath('/nosuchtag', '<root/>')) AS _sub;