18

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.

1
  • Why do you want a case insensitive check of a case sensitive item? Commented Jun 27, 2017 at 20:51

3 Answers 3

28

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.

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')
);
-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()

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.