Thursday, May 14, 2020

Substitute Variables in PostgreSQL

It is useful to use variables in a SQL script. For example, when writing a create objects script, we can use a variable to store the schema name. This way, if we decide to change the schema name later, we just need to re-set the value for the variable.

\set dm_schema 'dm'
CREATE SCHEMA IF NOT EXISTS :dm_schema;

create table IF NOT EXISTS :dm_schema.user(
    user_id                          serial primary key,
    user_name                        VARCHAR(128),
    user_email                       VARCHAR(128)
  
);

create table IF NOT EXISTS :dm_schema.use_groupr(
   group_id                          serial primary key,
   group_name                        VARCHAR(128)
  
);

No comments: