Project

General

Profile

Creating user database and adding access on PostgreSQL » History » Version 2

Viacheslav Anzhiganov, 04/10/2025 05:52 PM

1 1 Viacheslav Anzhiganov
# Creating user, database and adding access on PostgreSQL
2
3
NOTE: Right off the bat — this is valid as on March 2017, running on Ubuntu 16.04.2, with PostgreSQL 9.6
4
5
TL;DR; versionsudo -u postgres psql
6
7
```
8
postgres=# create database mydb;
9
postgres=# create user myuser with encrypted password ‘mypass’;
10
postgres=# grant all privileges on database mydb to myuser;
11
```
12
13
One nice thing about PGSQL is it comes with some utility binaries like createuser and createdb. So we will be making use of that.
14
15
As the default configuration of Postgres is, a user called postgres is made on and the user postgres has full superadmin access to entire PostgreSQL instance running on your OS.
16
17
```
18
$ sudo -u postgres psql
19
```
20
21
The above command gets you the psql command line interface in full admin mode.
22
23
In the following commands, keep in mind the < angular brackets > are to denote variables you have to set yourself. In the actual command, omit the <>
24 2 Viacheslav Anzhiganov
25
26
## Creating user
27
28
```
29
$ sudo -u postgres createuser <username>
30
```
31
32
## Creating Database
33
34
```
35
$ sudo -u postgres createdb <dbname>
36
```
37
38
Giving the user a password
39
40
```
41
$ sudo -u postgres psql
42
psql=# alter user <username> with encrypted password ‘<password>’;
43
```
44
45
Granting privileges on database
46
47
```
48
psql=# grant all privileges on database <dbname> to <username> ;
49
```
50
51
And yeah, that should be pretty much it !
52
53
Doing purely via psql
54
55
Your OS might not have the createuser or createdb binaries, or you may, for some reason want to do it purely via psql, then these are the three magic commands — CREATE DATABASE yourdbname;
56
57
```
58
CREATE USER youruser WITH ENCRYPTED PASSWORD ‘yourpass’;
59
GRANT ALL PRIVILEGES ON DATABASE yourdbname TO youruser;
60
```