loading...

Postgres \set variable

croaky profile image Dan Croak ・1 min read

Within psql, you can \set variables and reference them with :'var-name'. For example:

\set query '%SaaS%'

SELECT
  'https://example.com/companies/' || companies.id AS url,
  companies.name
FROM
  companies
  JOIN notes ON notes.company_id = companies.id
WHERE
  companies.name ILIKE :'query'
  OR companies.description ILIKE :'query'
  OR notes.comments ILIKE :'query'
GROUP BY
  url,
  companies.name
ORDER BY
  companies.name ASC;

I like to run scripts from Vim through psql with this config.

Discussion

pic
Editor guide