22

Is there a "elegant built-in" case-insensitive way to check if db is exists?

I've found only SELECT datname FROM pg_catalog.pg_database WHERE datname='dbname', but this is a CS check. The first thing that comes to mind to retrieve all db names and filter them by hand, but I think there is more elegant way to do it.

joanolo
  • 13,657
  • 8
  • 39
  • 67
Andrei Orlov
  • 537
  • 2
  • 4
  • 12

3 Answers3

31

You can use:

SELECT datname FROM pg_catalog.pg_database WHERE lower(datname) = lower('dbname');

... however, database names are case sensitive, so attempting to connect to the DB name won't actually work unless you match the case correctly. This won't use any indexes on dbname, but it's rather unlikely that you'd have enough databases for this to matter.

Folks don't realize that because PostgreSQL case-folds unquoted identifiers to lower-case, so most of the time it looks case-insensitive for clients. In fact, "DatabaseName" and "databasename" are different things.

Craig Ringer
  • 57,821
  • 6
  • 162
  • 193
10

If you want a true/false answer you can use

select exists(
 SELECT datname FROM pg_catalog.pg_database WHERE lower(datname) = lower('dbname')
);
mustaccio
  • 28,207
  • 24
  • 60
  • 76
Thomas Turner
  • 201
  • 2
  • 2
-1
    try:
        # establishing the connection
        conn = psycopg2.connect(
            database="postgres", user='postgres', password='put_password_here', host='Localhost', port='5432'
        )
        conn.autocommit = True

        # Creating a cursor object using the cursor() method
        cursor = conn.cursor()
        sql = '''select exists(SELECT datname FROM pg_catalog.pg_database WHERE lower(datname) = lower('db_name'))''';

        # Creating a database
        cursor.execute(sql)
        checktruth = cursor.fetchall()
        truthchecked = checktruth[0]
        checked = truthchecked[0]
        self.checked = str(checked)

        if self.checked == "True":
            messagebox.showinfo("Info", f"db_name already exists.")

        elif self.checked == "False":
            # Preparing query to create a database
            sql = '''CREATE database db_name ''';
            cursor.execute(sql)
            messagebox.showinfo("Info", f"db_name created successfully")

    except(Exception, psycopg2.Error) as error:
        messagebox.showerror("error", f"Failed to create db_name!\n{error}", parent=self.root)

    finally:
        ####closing database connection.
        if conn:
            cursor.close()
            conn.close()
John
  • 1