HiveBrain v1.2.0
Get Started
← Back to all entries
snippetsqlMinor

PostgeSQL: create role/user if not exists?

Submitted by: @import:stackexchange-dba··
0
Viewed 0 times
createuserpostgesqlroleexistsnot

Problem

Is there some way to create a user/role/group in PostgreSQL via SQL only if it does not exist yet? The only solution I have found so far is creating a custom stored procedure, since that supports conditionals. Is there a simpler solution that I have overlooked? Thank you!

Solution

You can use a DO block to only create the role if it doesn't exist, no need for a procedure:

do
$
begin
  if not exists (select * from pg_user where usename = 'new_role') then
     create role new_role password '...';
  end if;
end
$
;

Code Snippets

do
$$
begin
  if not exists (select * from pg_user where usename = 'new_role') then
     create role new_role password '...';
  end if;
end
$$
;

Context

StackExchange Database Administrators Q#301861, answer score: 8

Revisions (0)

No revisions yet.