Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Postgres Creating Schema in a specific database

I got one suggestion form stackoverflow.com to create schema in a specific database as follows:

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

But I am getting error as follows:

ERROR: syntax error at or near "\" LINE 2: \connect foo; ^

*** Error ***

ERROR: syntax error at or near "\"

Situation :

Login as postgress
create user u1
create database db1 with owner u1
\connect u1
create schema s1

Please help me in creating schema in a specific db.

like image 565
AVA Avatar asked Aug 14 '12 09:08

AVA


People also ask

Can we create schema in PostgreSQL?

Optionally, CREATE SCHEMA can include subcommands to create objects within the new schema. The subcommands are treated essentially the same as separate commands issued after creating the schema, except that if the AUTHORIZATION clause is used, all the created objects will be owned by that user.

How do I create a schema table in PostgreSQL?

If you write a database name, it must be the same as the database you are connected to. So to create a table in the new schema, use: CREATE TABLE myschema. mytable ( ... );


1 Answers

This works, if - and only if - you're using psql:

postgres@berry-pc:~$ psql template1
psql (8.4.10)
Type "help" for help.

template1=# CREATE DATABASE foo;
CREATE DATABASE
template1=# \connect foo;
psql (8.4.10)
You are now connected to database "foo".
foo=# \connect template1
psql (8.4.10)
You are now connected to database "template1".
template1=# DROP DATABASE foo;
DROP DATABASE
template1=# \q

\connect is a psql command. It's not normal SQL, so you can't use that in a .sql file. There is no way to do it from within a sql file, as far as I know. The rationale behind this, is that you should reconnect to a different database once you want to use that different database. This is for database separation. The reason MySQL has implemented the use $database syntax is because of it's lack of schema's, but PostgreSQL doesn't have a command like that, as a database should be separated in schema's, rather than databases.

like image 60
Berry Langerak Avatar answered Oct 13 '22 17:10

Berry Langerak