Psql create database if not exists

Explanation:

To create a database in PostgreSQL using the psql command, you can follow these steps:

  1. Open the psql terminal.
  2. Connect to the database server using a valid username and password:
  3. psql -U your_username -W
  4. Execute the following SQL query to create a database if it does not already exist:
  5. CREATE DATABASE IF NOT EXISTS your_database_name;

    In the above query, replace “your_database_name” with the desired name for your database.

  6. You will receive a confirmation message indicating whether the database was created or it already existed.

Here’s an example:

$ psql -U postgres -W
psql (12.4)
Type "help" for help.

postgres=# CREATE DATABASE IF NOT EXISTS mydatabase;
CREATE DATABASE

In the above example, we log in to the psql terminal as the user “postgres” and execute the SQL query to create a database named “mydatabase”. Since the database did not exist previously, the query returns “CREATE DATABASE” as the confirmation message.

By using the “IF NOT EXISTS” clause, the query ensures that the database creation is skipped if a database with the same name already exists.

Leave a comment