PostgreSQL Usage

User Basics

Create a new user

su - postgres
psql
create user USER with password 'PASSWORD';

Database Basics

Create a new database

su - postgres
psql
create database DATABASE with owner USER;

Copying a database

su - postgres
createdb -O USER -T DATABASE_ORIGINAL DATABASE_COPY

Renaming a database

su - postgres
psql
alter database DATABASE_ORIGINAL rename to DATABASE_RENAMED;

Remove a database

su - postgres
psql
drop database DATABASE;

Creating a database dump

su - postgres
pg_dump DATABASE > dump.sql
su - postgres
pg_dump DATABASE | plzip > dump.sql.lz

Importing a database dump

su - postgres
psql -d DATABASE -f dump.sql

Switching to a database

su - postgres
psql
\connect DATABASE;

Give all rights on a database to a user

su - postgres
psql
grant all privileges on database DATABASE to USER;

Table Basics

Create a table

su - postgres
psql
\connect DATABASE;
create table TABLE(...);

Remove a table

su - postgres
psql
\connect DATABASE;
drop table TABLE;

Show table schema

su - postgres
psql
\connect DATABASE;
\d TABLE;
\d+ TABLE;