Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cannot create a new table after "DROP SCHEMA public"

Since I wanted to drop some tables and somebody suggested the below and I did it:

postgres=# drop schema public cascade; DROP SCHEMA postgres=# create schema public; CREATE SCHEMA 

Then I got problem when creating a new database, such as:

postgres=# create database test; CREATE DATABASE postgres=# \c test You are now connected to database "test" as user "postgres". test=# create table hi(id int primary key); *ERROR:  no schema has been selected to create in* 

You can see I got error

ERROR: no schema has been selected to create in*

How can I restore the public schema?
I suggest people never do "drop schema public cascade;" if we don't know how to restore. Can somebody help me out?

like image 447
user1342336 Avatar asked Jan 11 '13 20:01

user1342336


People also ask

Can we drop public schema in PostgreSQL?

PostgreSQL stores all the tables on its record table named pg_table . SELECT 'DROP TABLE IF EXISTS "' || tablename || '" CASCADE;' from pg_tables WHERE schemaname = 'public'; As you can see, By the use of subquery, We can remove the entire tables from the schema.

Does Drop Table remove schema?

The DROP TABLE is another DDL (Data Definition Language) operation. But it is not used for simply removing data from a table; it deletes the table structure from the database, along with any data stored in the table.

What is public schema in PostgreSQL?

Public schema and public roleWhen a new database is created, PostgreSQL by default creates a schema named public and grants access on this schema to a backend role named public . All new users and roles are by default granted this public role, and therefore can create objects in the public schema.


1 Answers

The error message pops up when none of the schemas in your search_path can be found.
Either it is misconfigured. What do you get for this?

SHOW search_path; 

Or you deleted the public schema from your standard system database template1. You may have been connected to the wrong database when you ran drop schema public cascade;

As the name suggests, this is the template for creating new databases. Therefore, every new database starts out without the (default) schema public now - while your default search_path probably has 'public' in it.

Just run (as superuser public or see mgojohn's answer):

CREATE SCHEMA public; 

in the database template1 (or any other database where you need it).

The advice with DROP SCHEMA ... CASCADE to destroy all objects in it quickly is otherwise valid.

like image 53
Erwin Brandstetter Avatar answered Sep 30 '22 14:09

Erwin Brandstetter