Posts Basic Postgresql Commands
Post
Cancel

Basic Postgresql Commands

Create user, database and grant roles

Drop Database :

1
DROP database john_db;

Create Database :

1
CREATE DATABASE john_db;

Create User :

1
CREATE USER john;

or,

1
CREATE USER john WITH ENCRYPTED PASSWORD 'john@password';

Alter User :

1
ALTER USER john WITH ENCRYPTED PASSWORD 'john@password';

Grant Privileges :

1
GRANT ALL PRIVILEGES ON DATABASE john_db TO john;

Grant Privileges of everything to postgres, if not given with:

1
2
3
4
5
grant all privileges on all tables in schema public to postgres;

grant all privileges on all sequences in schema public to postgres;

Note: A schema is a namespace that contains a collection of database objects, such as tables, views, and functions. The schema public is the default schema.

Query all the tables in database

1
2
3
4
SELECT    table_name
FROM      information_schema.tables
WHERE     table_schema = 'public'
ORDER BY  table_name;

Postgres Dumps

1
2
3
4
5
6
7
# Export database

$ pg_dump -U {{ db_user }} {{ db_name }} > `date +%Y-%m-%d-%H:%M:%S`.pgsql

# Import database

$ psql -U {{ db_user }} {{ db_name }} < db_backup_to_be_imported.pgsql

Unix Domain Socket

1
2
3
psql: error: could not connect to server: could not connect to server: No such file or directory
        Is the server running locally and accepting
        connections on Unix domain socket "/tmp/.s.PGSQL.5432"?
1
2
$ rm /usr/local/var/postgres/postmaster.pid
$ brew services restart postgresql

References:

This post is licensed under CC BY 4.0 by the author.