A RetroSearch Logo

Home - News ( United States | United Kingdom | Italy | Germany ) - Football scores

Search Query:

Showing content from https://www.w3resource.com/PostgreSQL/snippets/postgresql-create-database-if-not-exists.php below:

Website Navigation


Guide to Conditional Database Creation in PostgreSQL

Guide to Conditional Database Creation in PostgreSQLLast update on December 31 2024 13:03:55 (UTC/GMT +8 hours)

PostgreSQL: Create Database If Not Exists

PostgreSQL does not have a direct CREATE DATABASE IF NOT EXISTS clause, as seen in some other relational databases like MySQL. However, this functionality can be emulated by querying the system catalog to check for the existence of the database and creating it conditionally.

This guide provides detailed steps to create a database in PostgreSQL only if it does not already exist. We include syntax, examples, and an explanation for better understanding.

Syntax:

Since PostgreSQL lacks the IF NOT EXISTS clause for database creation, you can use a combination of a conditional query and dynamic SQL within a block. Here's the syntax:

 
DO $$
BEGIN
    IF NOT EXISTS (
        SELECT 1 FROM pg_database WHERE datname = 'database_name'
    ) THEN
        PERFORM dblink_exec('dbname=postgres', 'CREATE DATABASE database_name');
    END IF;
END $$;

Example 1: Using pg_database to Check for Existence

Code:

-- Check if the database 'testdb' exists and create it if it does not
DO $$
BEGIN
    IF NOT EXISTS (
        -- Query the system catalog to check for the database
        SELECT 1 FROM pg_database WHERE datname = 'testdb'
    ) THEN
        -- Execute the CREATE DATABASE statement
        PERFORM dblink_exec('dbname=postgres', 'CREATE DATABASE testdb');
    END IF;
END $$;

Explanation:

Example 2: Emulating Behavior Without Extensions

If dblink is unavailable, you can use a script outside PostgreSQL to achieve similar functionality:

Code:

#!/bin/bash
# Check if the database exists
DB_NAME="testdb"
DB_EXISTS=$(psql -U postgres -tAc "SELECT 1 FROM pg_database WHERE datname='${DB_NAME}'")

if [ "${DB_EXISTS}" != "1" ]; then
  # Create the database
  createdb -U postgres ${DB_NAME}
  echo "Database ${DB_NAME} created."
else
  echo "Database ${DB_NAME} already exists."
fi

Explanation

Common Use Cases

Additional Notes

All PostgreSQL Questions, Answers, and Code Snippets Collection.


RetroSearch is an open source project built by @garambo | Open a GitHub Issue

Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo

HTML: 3.2 | Encoding: UTF-8 | Version: 0.7.4