Last Updated on July 17, 2012 EDT by Jordan
PostgreSQL Interactive Terminal
Postgresql is similar to MySQL in that it uses an interactive terminal. To gain access type the following as root
su - postgres -c psql
You’re now logged into the Postgresql interactive terminal and interacting with the local server.
Common Shell Commands
Dump a database.
When dumping and restoring a database, you have to work within the postgres user, this is the default setup. The home directory for the postgres user is /var/lib/postgresql
pg_dump -U username database -f file.sql
Restore a database.
In order to restore the database you will need to ensure that the database name exist, for instance if it was dropped.
psql -U username -d database -f file.sql
Common Interactive Terminal Commands
Connect to a database, like “use database” in MySQL.
connect databasename;
View current databases on local server
select datname from pg_database;
View current databases on local server
\l
Show current roles
select rolname from pg_roles;
Create a user.
create user ramesh with password 'tmppassword';
Create a database.
CREATE DATABASE mydb WITH OWNER ramesh;
Drop database.
DROP DATABASE mydb;
If you notice that you’re unable to drop a database because of connections, then run the following.
SELECT pg_terminate_backend(procpid) FROM pg_stat_activity WHERE -- don't kill my own connection! procpid <> pg_backend_pid();
If it’s a busy database then you may need to run the following first.
REVOKE CONNECT ON DATABASE dbname FROM PUBLIC, username;