PostgreSQL: Create schema in specific database

SqlDatabaseSchemaPostgresql

Sql Problem Overview


I need to write an sql script that creates both a new database AND a new schema in the database I just created.

How can I do it? Can I somehow change the current database to the new one? Or can I somehow specify the database for CREATE SCHEMA?

I'm using PostgreSQL 9.0

Sql Solutions


Solution 1 - Sql

You can connect to the database, and execute the "CREATE SCHEMA" statement. That should result in a new schema in that database. It's not as tough as you think ;) When you want to do this from a .SQL file instead, you can use the \connect command as such:

 CREATE DATABASE foo;
 \connect foo;
 CREATE SCHEMA yourschema;

Solution 2 - Sql

Login to New-Database with new user:

postgres=> \connect newdb user1
...
You are now connected to database "newdb" as user "user1".
newdb=> 

To create schema with new user "user1" in newdb:

newdb=> CREATE SCHEMA s1;

To list the schema :

SELECT * from information_schema.schemata;

Solution 3 - Sql

Create database using --CREATE DATABASE test;

Enter to the test database using --psql -d test;

Create your schema in test database using --create schema if not exists test_schema;

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionAxel FontaineView Question on Stackoverflow
Solution 1 - SqlBerry LangerakView Answer on Stackoverflow
Solution 2 - SqlKiruthika kanagarajanView Answer on Stackoverflow
Solution 3 - SqlPraveenView Answer on Stackoverflow