Create a PostgreSQL Database | Generated by AI

Home PDF

You’re already in the PostgreSQL interactive terminal (psql) as the postgres user, which is great! To create a database in PostgreSQL, you can use the CREATE DATABASE command. Here’s a step-by-step guide:

  1. Ensure you’re in psql: You already are, as shown by the postgres=# prompt.

  2. Create a database: Use the following command to create a new database. Replace mydatabase with your desired database name:

    CREATE DATABASE mydatabase;
    

    This creates a database named mydatabase.

  3. Verify the database was created: List all databases to confirm:

    \l
    

    This will display a table of all databases, including mydatabase.

  4. Connect to the new database: To start working in the new database, connect to it with:

    \c mydatabase
    

    This switches your session to mydatabase.

  5. Optional: Create a user and grant permissions: If you want a specific user to manage this database, create one and grant privileges:

    CREATE USER myuser WITH ENCRYPTED PASSWORD 'mypassword';
    GRANT ALL PRIVILEGES ON DATABASE mydatabase TO myuser;
    

    Replace myuser and mypassword with your desired username and password.

  6. Exit psql: When done, exit with:

    \q
    

Notes:

Example Session:

postgres=# CREATE DATABASE mydatabase;
CREATE DATABASE
postgres=# \l
                                  List of databases
   Name      |  Owner   | Encoding |   Collate   |    Ctype    |   Access privileges   
-------------+----------+----------+-------------+-------------+-----------------------
 mydatabase  | postgres | UTF8     | en_US.UTF-8 | en_US.UTF-8 | 
 postgres    | postgres | UTF8     | en_US.UTF-8 | en_US.UTF-8 | 
 template0   | postgres | UTF8     | en_US.UTF-8 | en_US.UTF-8 | =c/postgres          +
             |          |          |             |             | postgres=CTc/postgres
 template1   | postgres | UTF8     | en_US.UTF-8 | en_US.UTF-8 | =c/postgres          +
             |          |          |             |             | postgres=CTc/postgres
(4 rows)

postgres=# \c mydatabase
You are now connected to database "mydatabase" as user "postgres".
mydatabase=# \q

If you need further help (e.g., setting up tables, users, or connecting from an application), let me know!


Back 2025.06.29 Donate