Managing Databases with PostgreSQL

Published: Tuesday, 13 April 2004

Read the documentation for more detailed information.

The simplest way to create a new database is to use the createdb command. If you are going to use PostgreSQL frequently, it’s a good idea to add the PostgreSQL bin directory to your PATH.

$ createdb --help
createdb creates a PostgreSQL database.

Usage:
  createdb [OPTION]... [DBNAME] [DESCRIPTION]

Options:
  -D, --location=PATH       alternative place to store the database
  -E, --encoding=ENCODING   encoding for the database
  -O, --owner=OWNER         database user to own the new database
  -T, --template=TEMPLATE   template database to copy
  -e, --echo                show the commands being sent to the server
  -q, --quiet               don't write any messages
  --help                    show this help, then exit
  --version                 output version information, then exit

Connection options:
  -h, --host=HOSTNAME       database server host or socket directory
  -p, --port=PORT           database server port
  -U, --username=USERNAME   user name to connect as
  -W, --password            prompt for password

By default, a database with the same name as the current user is created.

Report bugs to <pgsql-bugs@postgresql.org>.

$ createdb -e test
Password:
CREATE DATABASE test;
CREATE DATABASE

The database named test has been created.

Listing all available Databases

Use the following psql -l command.

$ psql -l
Password:
        List of databases
   Name    |  Owner   | Encoding
-----------+----------+-----------
 template0 | postgres | SQL_ASCII
 template1 | postgres | SQL_ASCII
 test      | jurn     | SQL_ASCII
(3 rows)

The databases template0 and template1 are created when you initialise the cluster. The test database was created in the previous example.

Dropping or Removing a Database

Use the dropdb command:

$ dropdb -e test
Password:
DROP DATABASE test;
DROP DATABASE