### Start PostgreSQL server Source: https://devdocs.io/postgresql~18/upgrading Start the database server using the new installation binaries. ```bash /usr/local/pgsql/bin/postgres -D /usr/local/pgsql/data ``` -------------------------------- ### Complete crosstab Example with Table Setup Source: https://devdocs.io/postgresql~18/tablefunc This example demonstrates creating a table, inserting data, and then using crosstab to pivot the data, defining the output columns explicitly. ```sql CREATE TABLE ct(id SERIAL, rowid TEXT, attribute TEXT, value TEXT); INSERT INTO ct(rowid, attribute, value) VALUES('test1','att1','val1'); INSERT INTO ct(rowid, attribute, value) VALUES('test1','att2','val2'); INSERT INTO ct(rowid, attribute, value) VALUES('test1','att3','val3'); INSERT INTO ct(rowid, attribute, value) VALUES('test1','att4','val4'); INSERT INTO ct(rowid, attribute, value) VALUES('test2','att1','val5'); INSERT INTO ct(rowid, attribute, value) VALUES('test2','att2','val6'); INSERT INTO ct(rowid, attribute, value) VALUES('test2','att3','val7'); INSERT INTO ct(rowid, attribute, value) VALUES('test2','att4','val8'); SELECT * FROM crosstab( 'select rowid, attribute, value from ct where attribute = ''att2'' or attribute = ''att3'' order by 1,2') AS ct(row_name text, category_1 text, category_2 text, category_3 text); ``` ```sql row_name | category_1 | category_2 | category_3 ----------+------------+------------+------------ test1 | val2 | val3 | test2 | val6 | val7 | (2 rows) ``` -------------------------------- ### Benchmark Setup and Execution Source: https://devdocs.io/postgresql~18/intarray Provides commands to set up a test database, create the intarray extension, load test data, and run the benchmark suite. Requires DBD::Pg to be installed. ```shell cd .../contrib/intarray/bench createdb TEST psql -c "CREATE EXTENSION intarray" TEST ./create_test.pl | psql TEST ./bench.pl ``` -------------------------------- ### SHOW Command Examples Source: https://devdocs.io/postgresql~18/sql-show Examples demonstrating how to query specific parameters and all available settings. ```sql SHOW DateStyle; DateStyle ----------- ISO, MDY (1 row) ``` ```sql SHOW geqo; geqo ------ on (1 row) ``` ```sql SHOW ALL; name | setting | description -------------------------+---------+------------------------------------------------- allow_system_table_mods | off | Allows modifications of the structure of ... . . . xmloption | content | Sets whether XML data in implicit parsing ... zero_damaged_pages | off | Continues processing past damaged page headers. (196 rows) ``` -------------------------------- ### Setup and query hierarchical data Source: https://devdocs.io/postgresql~18/tablefunc Complete example creating a tree table, inserting data, and querying it with and without branch and ordering parameters. ```sql CREATE TABLE connectby_tree(keyid text, parent_keyid text, pos int); INSERT INTO connectby_tree VALUES('row1',NULL, 0); INSERT INTO connectby_tree VALUES('row2','row1', 0); INSERT INTO connectby_tree VALUES('row3','row1', 0); INSERT INTO connectby_tree VALUES('row4','row2', 1); INSERT INTO connectby_tree VALUES('row5','row2', 0); INSERT INTO connectby_tree VALUES('row6','row4', 0); INSERT INTO connectby_tree VALUES('row7','row3', 0); INSERT INTO connectby_tree VALUES('row8','row6', 0); INSERT INTO connectby_tree VALUES('row9','row5', 0); -- with branch, without orderby_fld (order of results is not guaranteed) SELECT * FROM connectby('connectby_tree', 'keyid', 'parent_keyid', 'row2', 0, '~') AS t(keyid text, parent_keyid text, level int, branch text); keyid | parent_keyid | level | branch -------+--------------+-------+--------------------- row2 | | 0 | row2 row4 | row2 | 1 | row2~row4 row6 | row4 | 2 | row2~row4~row6 row8 | row6 | 3 | row2~row4~row6~row8 row5 | row2 | 1 | row2~row5 row9 | row5 | 2 | row2~row5~row9 (6 rows) -- without branch, without orderby_fld (order of results is not guaranteed) SELECT * FROM connectby('connectby_tree', 'keyid', 'parent_keyid', 'row2', 0) AS t(keyid text, parent_keyid text, level int); keyid | parent_keyid | level -------+--------------+------- row2 | | 0 row4 | row2 | 1 row6 | row4 | 2 row8 | row6 | 3 row5 | row2 | 1 row9 | row5 | 2 (6 rows) ``` -------------------------------- ### dict_xsyn Usage and Examples Source: https://devdocs.io/postgresql~18/dict-xsyn Demonstrates how to install, alter, and use the dict_xsyn dictionary, including examples of ts_lexize function calls and text search configuration. ```APIDOC ## F.13.2. Usage Installing the `dict_xsyn` extension creates a text search template `xsyn_template` and a dictionary `xsyn` based on it, with default parameters. You can alter the parameters, for example ```sql mydb# ALTER TEXT SEARCH DICTIONARY xsyn (RULES='my_rules', KEEPORIG=false); ALTER TEXT SEARCH DICTIONARY ``` or create new dictionaries based on the template. To test the dictionary, you can try ```sql mydb=# SELECT ts_lexize('xsyn', 'word'); ts_lexize ----------------------- {syn1,syn2,syn3} mydb# ALTER TEXT SEARCH DICTIONARY xsyn (RULES='my_rules', KEEPORIG=true); ALTER TEXT SEARCH DICTIONARY mydb=# SELECT ts_lexize('xsyn', 'word'); ts_lexize ----------------------- {word,syn1,syn2,syn3} mydb# ALTER TEXT SEARCH DICTIONARY xsyn (RULES='my_rules', KEEPORIG=false, MATCHSYNONYMS=true); ALTER TEXT SEARCH DICTIONARY mydb=# SELECT ts_lexize('xsyn', 'syn1'); ts_lexize ----------------------- {syn1,syn2,syn3} mydb# ALTER TEXT SEARCH DICTIONARY xsyn (RULES='my_rules', KEEPORIG=true, MATCHORIG=false, KEEPSYNONYMS=false); ALTER TEXT SEARCH DICTIONARY mydb=# SELECT ts_lexize('xsyn', 'syn1'); ts_lexize ----------------------- {word} ``` Real-world usage will involve including it in a text search configuration as described in Chapter 12. That might look like this: ```sql ALTER TEXT SEARCH CONFIGURATION english ALTER MAPPING FOR word, asciiword WITH xsyn, english_stem; ``` ``` -------------------------------- ### Create Tables for Publication Examples Source: https://devdocs.io/postgresql~18/logical-replication-row-filter Initial table setup required for demonstrating publication row filters. ```sql /* pub # */ CREATE TABLE t1(a int, b int, c text, PRIMARY KEY(a,c)); /* pub # */ CREATE TABLE t2(d int, e int, f int, PRIMARY KEY(d)); /* pub # */ CREATE TABLE t3(g int, h int, i int, PRIMARY KEY(g)); ``` -------------------------------- ### Initiate a psql session Source: https://devdocs.io/postgresql~18/app-psql Example of starting a psql session connected to a specific database. ```shell $ psql testdb psql (18.3) Type "help" for help. testdb=> ``` -------------------------------- ### List Partitioning Examples Source: https://devdocs.io/postgresql~18/sql-createtable Examples of creating list-partitioned tables. ```APIDOC ## CREATE TABLE cities_ab ### Description Creates a list partition named 'cities_ab' for the 'cities' table, containing values 'a' and 'b', with a check constraint. ### Method CREATE TABLE ### Endpoint N/A (SQL Command) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```sql CREATE TABLE cities_ab PARTITION OF cities ( CONSTRAINT city_id_nonzero CHECK (city_id != 0) ) FOR VALUES IN ('a', 'b'); ``` ### Response #### Success Response (200) Table created successfully. #### Response Example ```sql -- No specific output, table is created. ``` ``` ```APIDOC ## CREATE TABLE cities_ab_10000_to_100000 ### Description Creates a range partition 'cities_ab_10000_to_100000' for the list-partitioned table 'cities_ab', for population values from 10000 to 100000. ### Method CREATE TABLE ### Endpoint N/A (SQL Command) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```sql CREATE TABLE cities_ab_10000_to_100000 PARTITION OF cities_ab FOR VALUES FROM (10000) TO (100000); ``` ### Response #### Success Response (200) Table created successfully. #### Response Example ```sql -- No specific output, table is created. ``` ``` -------------------------------- ### Drop a server example Source: https://devdocs.io/postgresql~18/sql-dropserver Example demonstrating how to drop a server named 'foo' if it exists. ```sql DROP SERVER IF EXISTS foo; ``` -------------------------------- ### Hash Partitioning Examples Source: https://devdocs.io/postgresql~18/sql-createtable Examples of creating hash-partitioned tables for the 'orders' table. ```APIDOC ## CREATE TABLE orders_p1 ### Description Creates a hash partition 'orders_p1' for the 'orders' table with MODULUS 4 and REMAINDER 0. ### Method CREATE TABLE ### Endpoint N/A (SQL Command) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```sql CREATE TABLE orders_p1 PARTITION OF orders FOR VALUES WITH (MODULUS 4, REMAINDER 0); ``` ### Response #### Success Response (200) Table created successfully. #### Response Example ```sql -- No specific output, table is created. ``` ``` ```APIDOC ## CREATE TABLE orders_p2 ### Description Creates a hash partition 'orders_p2' for the 'orders' table with MODULUS 4 and REMAINDER 1. ### Method CREATE TABLE ### Endpoint N/A (SQL Command) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```sql CREATE TABLE orders_p2 PARTITION OF orders FOR VALUES WITH (MODULUS 4, REMAINDER 1); ``` ### Response #### Success Response (200) Table created successfully. #### Response Example ```sql -- No specific output, table is created. ``` ``` ```APIDOC ## CREATE TABLE orders_p3 ### Description Creates a hash partition 'orders_p3' for the 'orders' table with MODULUS 4 and REMAINDER 2. ### Method CREATE TABLE ### Endpoint N/A (SQL Command) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```sql CREATE TABLE orders_p3 PARTITION OF orders FOR VALUES WITH (MODULUS 4, REMAINDER 2); ``` ### Response #### Success Response (200) Table created successfully. #### Response Example ```sql -- No specific output, table is created. ``` ``` ```APIDOC ## CREATE TABLE orders_p4 ### Description Creates a hash partition 'orders_p4' for the 'orders' table with MODULUS 4 and REMAINDER 3. ### Method CREATE TABLE ### Endpoint N/A (SQL Command) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```sql CREATE TABLE orders_p4 PARTITION OF orders FOR VALUES WITH (MODULUS 4, REMAINDER 3); ``` ### Response #### Success Response (200) Table created successfully. #### Response Example ```sql -- No specific output, table is created. ``` ``` -------------------------------- ### SELinux Context Notification Examples Source: https://devdocs.io/postgresql~18/sepgsql Example of harmless notifications that may appear during installation depending on libselinux and selinux-policy versions. ```text /etc/selinux/targeted/contexts/sepgsql_contexts: line 33 has invalid object type db_blobs /etc/selinux/targeted/contexts/sepgsql_contexts: line 36 has invalid object type db_language /etc/selinux/targeted/contexts/sepgsql_contexts: line 37 has invalid object type db_language /etc/selinux/targeted/contexts/sepgsql_contexts: line 38 has invalid object type db_language /etc/selinux/targeted/contexts/sepgsql_contexts: line 39 has invalid object type db_language /etc/selinux/targeted/contexts/sepgsql_contexts: line 40 has invalid object type db_language ``` -------------------------------- ### Default Partition Example Source: https://devdocs.io/postgresql~18/sql-createtable Example of creating a default partition for a table. ```APIDOC ## CREATE TABLE cities_partdef ### Description Creates a default partition named 'cities_partdef' for the 'cities' table. ### Method CREATE TABLE ### Endpoint N/A (SQL Command) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```sql CREATE TABLE cities_partdef PARTITION OF cities DEFAULT; ``` ### Response #### Success Response (200) Table created successfully. #### Response Example ```sql -- No specific output, table is created. ``` ``` -------------------------------- ### Start Upgraded PostgreSQL Server Source: https://devdocs.io/postgresql~18/logical-replication-upgrade Starts the newly upgraded PostgreSQL server instance. ```bash pg_ctl -D /opt/PostgreSQL/data1_upgraded start -l logfile ``` ```bash pg_ctl -D /opt/PostgreSQL/data2_upgraded start -l logfile ``` -------------------------------- ### Create a subscription replicating multiple publications Source: https://devdocs.io/postgresql~18/sql-createsubscription This example demonstrates creating a subscription that replicates tables from multiple specified publications. Replication starts immediately on commit. ```sql CREATE SUBSCRIPTION mysub CONNECTION 'host=192.168.1.50 port=5432 user=foo dbname=foodb' PUBLICATION mypublication, insert_only; ``` -------------------------------- ### CREATE ROLE Examples Source: https://devdocs.io/postgresql~18/sql-createrole Practical examples demonstrating the usage of the CREATE ROLE command for various scenarios. ```APIDOC ## CREATE ROLE Examples ### Description Provides practical examples of using the `CREATE ROLE` command. ### Examples 1. **Create a role that can log in, but without a password:** ```sql CREATE ROLE jonathan LOGIN; ``` 2. **Create a user with a password:** ```sql CREATE USER davide WITH PASSWORD 'jw8s0F4'; ``` *Note: `CREATE USER` implies `LOGIN`.* 3. **Create a role with a password valid until a specific date:** ```sql CREATE ROLE miriam WITH LOGIN PASSWORD 'jw8s0F4' VALID UNTIL '2005-01-01'; ``` 4. **Create a role with privileges to create databases and manage roles:** ```sql CREATE ROLE admin WITH CREATEDB CREATEROLE; ``` ``` -------------------------------- ### Start Upgraded Publisher Server Source: https://devdocs.io/postgresql~18/logical-replication-upgrade Command to start the upgraded PostgreSQL publisher server on node1. ```bash pg_ctl -D /opt/PostgreSQL/data1_upgraded start -l logfile ``` -------------------------------- ### Example pg_basebackup Module Source: https://devdocs.io/postgresql~18/btree-gist This is an example module for pg_basebackup, demonstrating shell integration for backup operations. ```sql basic_archive — an example WAL archive module ``` -------------------------------- ### Install extension using search path Source: https://devdocs.io/postgresql~18/sql-createextension Sets the search path to the target schema before installing the extension. ```sql SET search_path = addons; CREATE EXTENSION hstore; ``` -------------------------------- ### Example pg_basebackup Shell Module Source: https://devdocs.io/postgresql~18/btree-gist This is an example module for pg_basebackup that integrates with the shell environment. ```sql basebackup_to_shell — example "shell" pg_basebackup module ``` -------------------------------- ### Execute Tutorial Scripts Source: https://devdocs.io/postgresql~18/tutorial-sql-intro Start the psql session in single-step mode and load the tutorial SQL file. ```bash $ **psql -s mydb** ... mydb=> **\i basics.sql** ``` -------------------------------- ### Get Backend Start Time Source: https://devdocs.io/postgresql~18/monitoring-stats Returns the timestamp indicating when the specified backend process was started. ```sql pg_stat_get_backend_start(integer) ``` -------------------------------- ### Manual directory setup and cluster initialization Source: https://devdocs.io/postgresql~18/creating-cluster Demonstrates the process of creating a parent directory, assigning ownership to the postgres user, and initializing the cluster. ```bash root# **mkdir /usr/local/pgsql** root# **chown postgres /usr/local/pgsql** root# **su postgres** postgres$ **initdb -D /usr/local/pgsql/data** ``` -------------------------------- ### Get Backend Transaction Start Time Source: https://devdocs.io/postgresql~18/monitoring-stats Returns the timestamp when the backend's current transaction was started. ```sql pg_stat_get_backend_xact_start(integer) ``` -------------------------------- ### Get Backend Activity Start Time Source: https://devdocs.io/postgresql~18/monitoring-stats Returns the timestamp when the backend's most recent query was started. ```sql pg_stat_get_backend_activity_start(integer) ``` -------------------------------- ### Compile Tutorial Files Source: https://devdocs.io/postgresql~18/tutorial-sql-intro Navigate to the tutorial directory and compile the necessary scripts and C files. ```bash $ **cd .../src/tutorial** $ **make** ``` -------------------------------- ### Create a basic database Source: https://devdocs.io/postgresql~18/sql-createdatabase Initializes a new database with default settings. ```sql CREATE DATABASE lusiadas; ``` -------------------------------- ### Example postgresql.conf configuration Source: https://devdocs.io/postgresql~18/config-setting A sample snippet showing the structure of the postgresql.conf file. ```text ``` -------------------------------- ### Get Token Types with Parser OID - ts_token_type Source: https://devdocs.io/postgresql~18/functions-textsearch Use `ts_token_type` to get a description of token types recognized by a parser specified by its OID. Provide the parser OID. Example uses OID 3722. ```sql ts_token_type(3722) ``` -------------------------------- ### Get Token Types with Named Parser - ts_token_type Source: https://devdocs.io/postgresql~18/functions-textsearch Use `ts_token_type` to get a description of token types recognized by a named parser. Specify the parser name. Example shows retrieving types for the 'default' parser. ```sql ts_token_type('default') ``` -------------------------------- ### Example: Listening and then Unlistening Source: https://devdocs.io/postgresql~18/sql-unlisten This example demonstrates how to set up a listener using LISTEN, send a notification with NOTIFY, and then stop listening with UNLISTEN. After UNLISTEN, further NOTIFY messages on that channel are ignored. ```sql LISTEN virtual; NOTIFY virtual; Asynchronous notification "virtual" received from server process with PID 8448. UNLISTEN virtual; NOTIFY virtual; -- no NOTIFY event is received ``` -------------------------------- ### Create a disabled subscription Source: https://devdocs.io/postgresql~18/sql-createsubscription This example shows how to create a subscription that does not start replicating immediately. It can be enabled later using ALTER SUBSCRIPTION. ```sql CREATE SUBSCRIPTION mysub CONNECTION 'host=192.168.1.50 port=5432 user=foo dbname=foodb' PUBLICATION insert_only WITH (enabled = false); ``` -------------------------------- ### Generate Date Series with Interval Source: https://devdocs.io/postgresql~18/functions-srf Generates a series of dates by adding a specified interval to a start date. This example uses the date-plus-integer operator. ```sql SELECT current_date + s.a AS dates FROM generate_series(0,14,7) AS s(a); ``` -------------------------------- ### CREATE SEQUENCE Syntax and Examples Source: https://devdocs.io/postgresql~18/sql-createsequence Demonstrates how to create sequences with different options and use them in SQL commands. ```APIDOC ## CREATE SEQUENCE ### Description Creates a new sequence object. Sequences are typically used to generate unique identifiers for rows in a table. ### Method SQL Statement ### Endpoint N/A (SQL Command) ### Parameters #### Path Parameters N/A #### Query Parameters N/A #### Request Body N/A ### Request Example ```sql CREATE SEQUENCE serial START 101; ``` ### Response #### Success Response (0) Sequence created successfully. #### Response Example N/A ## Using Sequences ### Description Examples of how to use sequences to generate unique numbers for inserts and updates. ### Method SQL Statement ### Endpoint N/A (SQL Command) ### Parameters N/A ### Request Example ```sql -- Select the next number from a sequence SELECT nextval('serial'); -- Use sequence in an INSERT statement INSERT INTO distributors VALUES (nextval('serial'), 'nothing'); -- Update sequence value after a COPY FROM command BEGIN; COPY distributors FROM 'input_file'; SELECT setval('serial', max(id)) FROM distributors; END; ``` ### Response #### Success Response (200) Returns the next sequence value or confirms statement execution. #### Response Example ``` nextval --------- 101 ``` ## Sequence Properties and Limitations ### Description Details on sequence data types, range, and behavior with caching and concurrent access. ### Method N/A (Conceptual Information) ### Endpoint N/A ### Parameters N/A ### Request Example N/A ### Response #### Success Response (0) Provides information about sequence characteristics. #### Response Example Sequences are based on `bigint` arithmetic, with a range from -9223372036854775808 to 9223372036854775807. `nextval` and `setval` calls are never rolled back. Using `cache` greater than one can lead to gaps in sequence numbers when multiple sessions access the sequence concurrently. ``` -------------------------------- ### Extracting Substrings with regexp_substr Source: https://devdocs.io/postgresql~18/functions-matching Examples demonstrating the use of regexp_substr to extract specific matches from a string based on pattern, start position, and occurrence index. ```sql regexp_substr('number of your street, town zip, FR', '[^,]+', 1, 2) ``` ```sql regexp_substr('ABCDEFGHI', '(c..)(...)', 1, 1, 'i', 2) ``` -------------------------------- ### Creating a Foreign Table with file_fdw Source: https://devdocs.io/postgresql~18/file-fdw Example demonstrating how to install the file_fdw extension, create a foreign server, and then define a foreign table to access CSV log files. ```APIDOC ## Creating a Foreign Table with file_fdw ### Description This example shows the steps to set up and use the `file_fdw` to access PostgreSQL CSV logs. ### Steps 1. **Install the extension:** ```sql CREATE EXTENSION file_fdw; ``` 2. **Create a foreign server:** ```sql CREATE SERVER pglog FOREIGN DATA WRAPPER file_fdw; ``` 3. **Create the foreign data table:** Define the columns, the CSV file name, and its format. ```sql CREATE FOREIGN TABLE pglog ( -- column definitions here ) SERVER pglog OPTIONS ( filename 'pglog.csv', format 'csv', header 'true' -- other options as needed ); ``` ``` -------------------------------- ### Get Backend PIDs and Queries Source: https://devdocs.io/postgresql~18/monitoring-stats Retrieves the process IDs (PIDs) and current queries for all active backend processes. This example demonstrates using pg_stat_get_backend_idset() in conjunction with other per-backend statistics functions. ```sql SELECT pg_stat_get_backend_pid(backendid) AS pid, pg_stat_get_backend_activity(backendid) AS query FROM pg_stat_get_backend_idset() AS backendid; ``` -------------------------------- ### Modular PostgreSQL Configuration Example Source: https://devdocs.io/postgresql~18/config-setting This example demonstrates how to use multiple `include` directives to break down configuration into shared, memory-specific, and server-specific files. The order of inclusion matters as later settings can override earlier ones. ```postgresql include 'shared.conf' include 'memory.conf' include 'server.conf' ``` -------------------------------- ### Configure extension and library paths together Source: https://devdocs.io/postgresql~18/runtime-config-client Example of setting both extension and library paths to include nonstandard locations. ```text extension_control_path = '/usr/local/share/postgresql:$system' dynamic_library_path = '/usr/local/lib/postgresql:$libdir' ``` -------------------------------- ### Initialize pgbench Database Source: https://devdocs.io/postgresql~18/pgbench Use the -i option to create and populate the necessary tables for the default benchmark. Ensure you use a separate database to avoid data loss. ```bash pgbench -i [ other-options ] dbname ``` -------------------------------- ### Get Database Object Comment by OID and Catalog in PostgreSQL Source: https://devdocs.io/postgresql~18/functions-info Retrieves the comment for a database object identified by its OID and the name of its system catalog. Example: retrieving a comment for a table with OID 123456. ```sql obj_description(123456, 'pg_class') ``` -------------------------------- ### PostgreSQL Query With JIT Enabled Source: https://devdocs.io/postgresql~18/jit-decision This example demonstrates the output of EXPLAIN ANALYZE after adjusting JIT cost settings. It shows that JIT compilation was used, including details on functions, options, and timing, even though inlining and optimization were not applied. ```sql #= EXPLAIN ANALYZE SELECT SUM(relpages) FROM pg_class; QUERY PLAN -------------------------------------------------------------------​------------------------------------------ Aggregate (cost=16.27..16.29 rows=1 width=8) (actual time=6.049..6.049 rows=1.00 loops=1) Buffers: shared hit=14 -> Seq Scan on pg_class (cost=0.00..15.42 rows=342 width=4) (actual time=0.019..0.052 rows=356.00 loops=1) Buffers: shared hit=14 Planning Time: 0.133 ms JIT: Functions: 3 Options: Inlining false, Optimization false, Expressions true, Deforming true Timing: Generation 1.259 ms (Deform 0.000 ms), Inlining 0.000 ms, Optimization 0.797 ms, Emission 5.048 ms, Total 7.104 ms Execution Time: 7.416 ms ``` -------------------------------- ### Get Start Times of Segments with High Heart Rate Source: https://devdocs.io/postgresql~18/functions-json Apply a filter expression to select segments meeting a condition, then extract a specific field from the filtered results. The path within the condition is relative to the current item. ```sql select jsonb_path_query(:'json', '$.track.segments[*] ? (@.HR > 130)."start time"') ``` -------------------------------- ### Get Range of Enum Values Source: https://devdocs.io/postgresql~18/functions-enum Returns an ordered array of enum values between two specified enum members. If the first parameter is null, the range starts from the first enum value. If the second parameter is null, the range ends with the last enum value. ```sql enum_range('orange'::rainbow, 'green'::rainbow) ``` ```sql enum_range(NULL, 'green'::rainbow) ``` ```sql enum_range('orange'::rainbow, NULL) ``` -------------------------------- ### Create a new database with default settings Source: https://devdocs.io/postgresql~18/app-createdb Use this command to create a new database with the default server settings. Ensure the database server is running. ```bash $ createdb demo ``` -------------------------------- ### Rename PostgreSQL installation directory Source: https://devdocs.io/postgresql~18/pgupgrade Use this command to move an existing PostgreSQL installation directory to avoid conflicts with a new installation. ```bash mv /usr/local/pgsql /usr/local/pgsql.old ``` -------------------------------- ### Configure Standby Server Parameters Source: https://devdocs.io/postgresql~18/warm-standby Example configuration settings for a standby server, including connection information, restore commands, and archive cleanup. ```text primary_conninfo = 'host=192.168.1.50 port=5432 user=foo password=foopass options=''-c wal_sender_timeout=5000''' restore_command = 'cp /path/to/archive/%f %p' archive_cleanup_command = 'pg_archivecleanup /path/to/archive %r' ``` -------------------------------- ### pg_backup_start Source: https://devdocs.io/postgresql~18/functions-admin Prepares the server to begin an on-line backup. ```APIDOC ## pg_backup_start ### Description Prepares the server to begin an on-line backup. ### Parameters #### Request Body - **label** (text) - Required - An arbitrary user-defined label for the backup. - **fast** (boolean) - Optional - If true, forces an immediate checkpoint. ``` -------------------------------- ### Range Partitioning Examples Source: https://devdocs.io/postgresql~18/sql-createtable Examples of creating range-partitioned tables for time-series data. ```APIDOC ## CREATE TABLE measurement_ym_y2016m11 ### Description Creates a partition for the 'measurement_year_month' table for the month of November 2016. ### Method CREATE TABLE ### Endpoint N/A (SQL Command) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```sql CREATE TABLE measurement_ym_y2016m11 PARTITION OF measurement_year_month FOR VALUES FROM (2016, 11) TO (2016, 12); ``` ### Response #### Success Response (200) Table created successfully. #### Response Example ```sql -- No specific output, table is created. ``` ``` ```APIDOC ## CREATE TABLE measurement_ym_y2016m12 ### Description Creates a partition for the 'measurement_year_month' table for the month of December 2016. ### Method CREATE TABLE ### Endpoint N/A (SQL Command) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```sql CREATE TABLE measurement_ym_y2016m12 PARTITION OF measurement_year_month FOR VALUES FROM (2016, 12) TO (2017, 01); ``` ### Response #### Success Response (200) Table created successfully. #### Response Example ```sql -- No specific output, table is created. ``` ``` ```APIDOC ## CREATE TABLE measurement_ym_y2017m01 ### Description Creates a partition for the 'measurement_year_month' table for the month of January 2017. ### Method CREATE TABLE ### Endpoint N/A (SQL Command) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```sql CREATE TABLE measurement_ym_y2017m01 PARTITION OF measurement_year_month FOR VALUES FROM (2017, 01) TO (2017, 02); ``` ### Response #### Success Response (200) Table created successfully. #### Response Example ```sql -- No specific output, table is created. ``` ``` -------------------------------- ### EXISTS Usage Example Source: https://devdocs.io/postgresql~18/functions-subquery Example of using EXISTS to perform a semi-join operation. ```sql SELECT col1 FROM tab1 WHERE EXISTS (SELECT 1 FROM tab2 WHERE col2 = tab1.col2); ``` -------------------------------- ### Substring Matching with starts with Source: https://devdocs.io/postgresql~18/functions-json Checks if a string value starts with the specified prefix. ```SQL jsonb_path_query('["John Smith", "Mary Stone", "Bob Johnson"]', '$[*] ? (@ starts with "John")') ``` -------------------------------- ### Create a table with multi-line input Source: https://devdocs.io/postgresql~18/app-psql Demonstrates how to spread a SQL command across multiple lines using the psql prompt. ```sql testdb=> CREATE TABLE my_table ( testdb(> first integer not null default 0, testdb(> second text) testdb-> ; CREATE TABLE ``` -------------------------------- ### Install file_fdw Extension Source: https://devdocs.io/postgresql~18/file-fdw Installs the file_fdw extension. This is a prerequisite for using the file_fdw functionality. ```sql CREATE EXTENSION file_fdw; ``` -------------------------------- ### Example of Dynamic Domain Transition with sepgsql_setcon Source: https://devdocs.io/postgresql~18/sepgsql Demonstrates switching to a more restricted security context and the denial of switching back to a less restricted one. Requires the 'setcurrent' and 'dyntransition' permissions. ```sql regression=# select sepgsql_getcon(); sepgsql_getcon ------------------------------------------------------- unconfined_u:unconfined_r:unconfined_t:s0-s0:c0.c1023 (1 row) regression=# SELECT sepgsql_setcon('unconfined_u:unconfined_r:unconfined_t:s0-s0:c1.c4'); sepgsql_setcon ---------------- t (1 row) regression=# SELECT sepgsql_setcon('unconfined_u:unconfined_r:unconfined_t:s0-s0:c1.c1023'); ERROR: SELinux: security policy violation ``` -------------------------------- ### Remove a Sequence Example Source: https://devdocs.io/postgresql~18/sql-dropsequence A basic example demonstrating how to remove a sequence named 'serial'. ```sql DROP SEQUENCE serial; ``` -------------------------------- ### DROP TABLE Example Source: https://devdocs.io/postgresql~18/sql-droptable Example demonstrating how to remove multiple tables in a single command. ```sql DROP TABLE films, distributors; ``` -------------------------------- ### Create a sample table Source: https://devdocs.io/postgresql~18/indexes-intro Defines a basic table structure for demonstrating index usage. ```sql CREATE TABLE test1 ( id integer, content varchar ); ``` -------------------------------- ### Start PostgreSQL on a specific port Source: https://devdocs.io/postgresql~18/app-postgres Launches the server instance listening on a custom port. ```bash postgres -p 1234 ``` -------------------------------- ### Pass Configuration Parameters to Postgres Server Source: https://devdocs.io/postgresql~18/config-setting Sets configuration parameters during server startup using command-line arguments. ```bash postgres -c log_connections=all --log-destination='syslog' ``` -------------------------------- ### Drop a Publication Example Source: https://devdocs.io/postgresql~18/sql-droppublication A basic example demonstrating how to remove a publication named 'mypublication'. ```sql DROP PUBLICATION mypublication; ```