This question is old, but for the sake of completeness ...
As has been pointed out in other answers, that's not simply possible because (per documentation):
CREATE DATABASE
cannot be executed inside a transaction block.
It has also been reported that the restriction can be bypassed with dblink
.
How to use (install) dblink in PostgreSQL?
What was missing so far is a proper function actually doing it:
CREATE OR REPLACE FUNCTION f_create_db(dbname text)
RETURNS integer AS
$func$
BEGIN
IF EXISTS (SELECT 1 FROM pg_database WHERE datname = dbname) THEN
RAISE NOTICE 'Database already exists';
ELSE
PERFORM dblink_exec('dbname=' || current_database() -- current db
, 'CREATE DATABASE ' || quote_ident(dbname));
END IF;
END
$func$ LANGUAGE plpgsql;
Checks if the db already exists in the local cluster. If not, proceed to create it - with a sanitized identifier. We would not want to invite SQL injection.