patternsqlMajor
Check if postgresql database exists (case insensitive way)
Viewed 0 times
postgresqlcaseinsensitivewaydatabaseexistscheck
Problem
Is there a "elegant built-in" case-insensitive way to check if db is exists?
I've found only
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.
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.
Solution
You can use:
... 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
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,
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.Code Snippets
SELECT datname FROM pg_catalog.pg_database WHERE lower(datname) = lower('dbname');Context
StackExchange Database Administrators Q#45143, answer score: 28
Revisions (0)
No revisions yet.