brewedbits.dev

Personal blog with guides and news on selfhosting, Linux and AI, from the Netherlands

nextDash nextdash --aboutYour bookmarks. Your terminal. checks your links knows your Docker host one container, no cloudLive demo →nextdash.cc ↗

Tip: \gset stores a one-row query result in psql variables you can reuse

Database
~/tips/tip-database-psql-gset-query-into-variable

\gset

Stores the single row of a query result in psql variables for later statements.

Sometimes the answer to one query is the input of the next. psql can hold it in a variable, so you do not copy values around by hand.

End a query with \gset instead of a semicolon. The query must return exactly one row, and each column becomes a variable named after the column. The PostgreSQL docs show it like this:

SELECT 'hello' AS var1, 10 AS var2
\gset
\echo :var1 :var2
hello 10

Give \gset a prefix to keep variable names apart, as in \gset result_, which stores :result_var1 and :result_var2.

To use the value in later SQL, interpolate it. :name copies the value as it is, :'name' quotes it as an SQL literal, and :"name" quotes it as an identifier. The docs warn that the unquoted form can be unsafe, because the value is copied literally and may contain unbalanced quotes or even backslash commands.

SELECT count(*) AS n FROM my_table
\gset
SELECT :n * 2 AS doubled;

Caveats: if the query fails or returns anything other than one row, no variables are changed. A NULL column does not set the variable to an empty value. It unsets the variable, so a later :name is left unchanged in the query, which usually ends in a syntax error that looks odd at first.

Further reading: psql (PostgreSQL documentation)

More Database tips mariadb -e 'CREATE DATABASE IF NOT EXISTS blog' mariadb-dump --no-create-info --insert-ignore shop orders > orders-rows.sql SELECT table_schema, table_name, CHECKSUM TABLE shop.orders; services: All Database tips (53) All topics

Link