Explanation:
To create a database in PostgreSQL using the psql command, you can follow these steps:
- Open the psql terminal.
- Connect to the database server using a valid username and password:
- Execute the following SQL query to create a database if it does not already exist:
- You will receive a confirmation message indicating whether the database was created or it already existed.
psql -U your_username -W
CREATE DATABASE IF NOT EXISTS your_database_name;
In the above query, replace “your_database_name” with the desired name for your database.
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.