12

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.

1
  • How are you trying to connect to the database? Are you doing this with the psql command line tool? Commented Aug 14, 2012 at 9:37

1 Answer 1

14

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.