EDUCBA

EDUCBA

MENUMENU
  • Free Tutorials
  • Free Courses
  • Certification Courses
  • 360+ Courses All in One Bundle
  • Login
Home Data Science Data Science Tutorials PostgreSQL Tutorial Postgres DROP Database
Secondary Sidebar
PostgreSQL Tutorial
  • Basic
    • What is PostgreSQL
    • PostgreSQL Features
    • How to Install PostgreSQL
    • PostgreSQL Versions
    • PostgreSQL Architecture
    • PostgreSQL GUI
    • Postgres Command-Line
    • PostgreSQL Variables
    • PostgreSQL Data Types
    • PostgreSQL NOT NULL
    • PostgreSQL Integer
    • PostgreSQL Boolean
    • PostgreSQL BIGINT
    • PostgreSQL NULLIF
    • PostgreSQL Administration
    • PostgreSQL Commands
    • PostgreSQL Operators
    • PostgreSQL IN Operator
    • Postgres like query
    • PostgreSQL encode
    • PostgreSQL Cheat Sheet
    • PostgreSQL List Databases
    • PostgreSQL Rename Database
  • Control Statement
    • PostgreSQL IF Statement
    • PostgreSQL if else
    • PostgreSQL CASE Statement
    • PostgreSQL LOOP
    • PostgreSQL For Loop
    • PostgreSQL While Loop
  • Joins
    • Joins in PostgreSQL
    • PostgreSQL Inner Join
    • PostgreSQL Outer Join
    • LEFT OUTER JOIN in PostgreSQL
    • PostgreSQL FULL OUTER JOIN
    • PostgreSQL LEFT JOIN
    • PostgreSQL Full Join
    • PostgreSQL Cross Join
    • PostgreSQL NATURAL JOIN
    • PostgreSQL UPDATE JOIN
  • Queries
    • PostgreSQL Queries
    • PostgreSQL INSERT INTO
    • PostgreSQL WHERE Clause
    • PostgreSQL WITH Clause
    • PostgreSQL ORDER BY
    • PostgreSQL ORDER BY Random
    • PostgreSQL ORDER BY DESC
    • PostgreSQL GROUP BY
    • PostgreSQL group_concat
    • PostgreSQL HAVING
    • PostgreSQL Recursive Query
  • Advanced
    • PostgreSQL Schema
    • Postgres List Schemas
    • PostgreSQL Drop Schema
    • PostgreSQL VARCHAR
    • Array in PostgreSQL
    • PostgreSQL DDL
    • PostgreSQL List Users
    • Postgres Default User
    • Postgres add user
    • PostgreSQL User Password
    • PostgreSQL log_statement
    • PostgreSQL repository
    • PostgreSQL shared_buffer
    • PostgreSQL String Functions
    • PostgreSQL Compare Strings
    • PostgreSQL Text Search
    • PostgreSQL TEXT
    • PostgreSQL String Array
    • PostgreSQL where in array
    • PostgreSQL Constraints
    • PostgreSQL UNIQUE Constraint
    • PostgreSQL CHECK Constraint
    • PostgreSQL INTERSECT
    • PostgreSQL Like
    • Cursors in PostgreSQL
    • PostgreSQL UNION ALL
    • Indexes in PostgreSQL
    • PostgreSQL Index Types
    • PostgreSQL REINDEX
    • PostgreSQL UNIQUE Index
    • PostgreSQL Clustered Index
    • PostgreSQL DROP INDEX
    • PostgreSQL DISTINCT
    • PostgreSQL FETCH
    • PostgreSQL RAISE EXCEPTION
    • PostgreSQL Auto Increment
    • Sequence in PostgreSQL
    • Wildcards in PostgreSQL
    • PostgreSQL Subquery
    • PostgreSQL Alias
    • PostgreSQL LIMIT
    • PostgreSQL Limit Offset
    • PostgreSQL LAG()
    • PostgreSQL Table
    • Postgres Show Tables
    • PostgreSQL Describe Table
    • PostgreSQL Lock Table
    • PostgreSQL ALTER TABLE
    • Postgres Rename Table
    • PostgreSQL List Tables
    • PostgreSQL TRUNCATE TABLE
    • PostgreSQL Table Partitioning
    • Postgres DROP Table
    • PostgreSQL Functions
    • PostgreSQL Math Functions
    • PostgreSQL Window Functions
    • Aggregate Functions in PostgreSQL
    • PostgreSQL Primary Key
    • Foreign Key in PostgreSQL
    • PostgreSQL Procedures
    • PostgreSQL Stored Procedures
    • PostgreSQL Views
    • PostgreSQL Materialized Views
    • Postgres Create View
    • PostgreSQL Triggers
    • PostgreSQL DROP TRIGGER
    • PostgreSQL Date Functions
    • PostgreSQL TO_DATE()
    • PostgreSQL datediff
    • PostgreSQL Timestamp
    • PostgreSQL CURRENT_TIMESTAMP()
    • PostgreSQL Notify
    • PostgreSQL LENGTH()
    • PostgreSQL blob
    • PostgreSQL Median
    • PostgreSQL kill query
    • PostgreSQL Formatter
    • PostgreSQL RANK()
    • PostgreSQL Select
    • PostgreSQL Average
    • PostgreSQL DATE_PART()
    • PostgreSQL EXECUTE
    • PostgreSQL COALESCE
    • PostgreSQL EXTRACT()
    • PostgreSQL Sort
    • PostgreSQL TO_CHAR
    • PostgreSQL Interval
    • PostgreSQL Number Types
    • PostgreSQL ROW_NUMBER
    • Alter Column in PostgreSQL
    • PostgreSQL Identity Column
    • PostgreSQL SPLIT_PART()
    • PostgreSQL CONCAT()
    • PostgreSQL replace
    • PostgreSQL TRIM()
    • PostgreSQL MAX
    • PostgreSQL DELETE
    • PostgreSQL Float
    • PostgreSQL OID
    • PostgreSQL log
    • PostgreSQL REGEXP_MATCHES()
    • PostgreSQL MD5 
    • PostgreSQL NOW()
    • PostgreSQL RANDOM
    • PostgreSQL round
    • PostgreSQL Trunc()
    • PostgreSQL TIME
    • PostgreSQL IS NULL
    • PostgreSQL CURRENT_TIME
    • PostgreSQL MOD()
    • Postgresql Count
    • PostgreSQL Datetime
    • PostgreSQL MIN()
    • PostgreSQL age()
    • PostgreSQL enum
    • PostgreSQL OR
    • PostgreSQL Wal
    • PostgreSQL NOT IN
    • PostgreSQL SET
    • PostgreSQL Current Date
    • PostgreSQL Compare Date
    • PostgreSQL SERIAL
    • PostgreSQL UUID
    • PostgreSQL Merge
    • PostgreSQL Database
    • PostgreSQL Clone Database
    • PostgreSQL Copy Database
    • PostgreSQL Show Databases
    • PostgreSQL Restore Database
    • PostgreSQL DROP DATABASE
    • PostgreSQL ALTER DATABASE
    • Postgres DROP Database
    • Postgres Dump Database
    • PostgreSQL OFFSET
    • PostgreSQL GRANT
    • PostgreSQL COMMIT
    • PostgreSQL ROLLUP
    • PostgreSQL JSON
    • EXPLAIN ANALYZE in PostgreSQL
    • PostgreSQL Temporary Table
    • PostgreSQL Show Tables
    • PostgreSQL cluster
    • PostgreSQL Replication
    • PostgreSQL Logical Replication
    • PostgreSQL flush privileges
    • PostgreSQL Tablespaces
    • CAST in PostgreSQL
    • PostgreSQL CTE
    • hstore in PostgreSQL
    • PostgreSQL Encryption
    • PostgreSQL DECODE()
    • PostgreSQL Vacuum
    • PostgreSQL EXCLUDE
    • Postgres Change Password
    • Postgres Delete Cascade
    • PostgreSQL EXCEPT
    • PostgreSQL Roles
    • PostgreSQL Link
    • PostgreSQL Partition
    • PostgreSQL column does not exist
    • PostgreSQL Log Queries
    • PostgreSQL escape single quote
    • PostgreSQL Query Optimization
    • PostgreSQL Character Varying
    • PostgreSQL Transaction
    • PostgreSQL Extensions
    • PostgreSQL Import CSV
    • PostgreSQL Client
    • PostgreSQL caching
    • PostgreSQL Incremental Backup
    • PostgreSQL JSON vs JSONNB
    • PostgreSQL JDBC Driver
    • PostgreSQL Interview Questions

Postgres DROP Database

By Payal UdhaniPayal Udhani

Postgres DROP Database

Introduction to Postgres DROP Database

Whenever the data in the database is not important and no necessary to store it anymore further or is an empty database that you wish to delete then you can delete that database completely using the DROP Database command or one available utility for that named dropdb. Whenever we delete that means to drop a database at that time what happens is the whole directory which is there for that database is permanently deleted and its related information about the database to be deleted stored in the catalog entries is also deleted permanently. There is no way to rollback this query, hence you have to be very much sure and careful while using these commands.

In this article, we will learn how we can delete the database completely using available two methods of DROP Database statement and dropdb utility program one by one.

Syntax:

DROP DATABASE [IF EXISTS] nameOfTheDb;

Start Your Free Data Science Course

Hadoop, Data Science, Statistics & others

The above syntax contains the query statements DROP Database and other parameters in it can be explained in the following manner –

All in One Data Science Bundle(360+ Courses, 50+ projects)
Python TutorialMachine LearningAWSArtificial Intelligence
TableauR ProgrammingPowerBIDeep Learning
Price
View Courses
360+ Online Courses | 50+ projects | 1500+ Hours | Verifiable Certificates | Lifetime Access
4.7 (86,527 ratings)
  • IF EXISTS – It is an optional parameter. This keyword can be used to prevent any error which is resulted while using the above command when there is no database existence in the current database server having the name “nameOfTheDb”. If the “IF EXISTS” keyword is used in your query and none of the database named “nameOfTheDb” is present in the current server then it will simply notify you about the same and won’t result in any error.
  • nameOfTheDb – It is the name of the database that you wish to delete or drop and is located in the current database.

Notes:

There are few things to be considered while dropping a database and understanding its behavior.

  • We cannot delete the database if the database we are deleting has any active sessions associated with it.
  • Further, the database can only be deleted by the owner of the database.
  • One more thing to keep in mind that the drop database query statement cannot be executed for the same database you are connected to right now.
  • Once the database is deleted, the actions cannot be undone. So be more cautious while doing so.

Example

We can check all the databases present in our database server using the query \l which results into the following output currently for my server –

\l

Postgres DROP Database 1

Postgres DROP Database 2

As can be seen, there is no database named sample present in our database server.

Let us understand how we can use this command with the help of an example. The first thing that we need to do is open our psql command prompt and then execute our statement. Suppose, we want to drop the database named “sample”. So, my query statement will be as follows –

DROP DATABASE sample;

It will result in the following output –

Postgres DROP Database 3

As can be seen, it has resulted in an error saying that there is no database named “sample” in our current database server.

Now what will be output if we use IF EXISTS for the same command like –

DROP DATABASE IF EXISTS sample;

It will result in the following output –

Postgres DROP Database 4

We can see that instead of an error it has thrown a notice to inform us that there does not exist such a database.

Let us create a database named “sample” and then perform the above query. We can use this command for creating a new database for our purpose –

CREATE DATABASE sample;

that will result in the following output –

Postgres DROP Database 5

Let us check whether it is created successfully with the help of command \l which result as follows –

Postgres DROP Database 6

So, our database now exists. This means when we run any of the above DROP commands, it won’t result in error or notice. Let us check the output by firing the query itself.

DROP DATABASE sample;

now results in –

Postgres DROP Database 7

Let us verify by checking all databases.\l gives following output –

Postgres DROP Database 8

This means that our database is dropped successfully.

Let us try deleting a database with active connections. In this example, we will drop the database demo which already exists. You can even create a new database and try deleting it. For database o have active connections, then we will open a new terminal with psql prompt and then connect to demo database using \c demo; command.

\c demo;

demo

Now, returning back to my previous terminal, we will try to drop demo database.

DROP DATABASE demo;

demo 1

As can be seen, it shows an error saying one session is already using the database named demo. Hence, it cannot be deleted. In such cases, we can drop the database by first checking all the activities associated with it and terminating them. We can see all the activities of the database from table pg_stat_activity.

Let us fire the following query –

SELECT * FROM pg_stat_activity WHERE datname = 'demo';

that give output –

DROP Database 1

One session is associated with the demo database. We can terminate all of them by using the query –

SELECT pg_terminate_backend (pg_stat_activity.pid) FROM pg_stat_activity WHERE pg_stat_activity.datname = 'demo';

DROP Database 2

Let us drop our demo db now.

DROP DATABASE demo;

DROP Database 3

And \l command now results in –

DROP Database 4

Hence, our database is dropped successfully.

dropdb command -

We can even use the dropdb command for deleting the database. It works similarly to the DROP DATABASE statement. The advantage is that we can drop the database remotely using dropdb functionality but it is necessary to be the owner of the database, we are trying to drop. the syntax is as follows –

Dropdb [option.] nameOfTheDb;

  • nameOfTheDb – It is the name of the database that you wish to delete or drop and is located in the current database.

Options can be any of the following –

Option Description
-e Echo commands.
-i Whether to display verification prompt
-V For printing dropdb version
–help For getting help
-h host Specify host of current system
-p port Socket used by current established connections.
–if exists Whether to show notice instead of error if database does not exists.
-U username User name using which to connect database.
-w If no password prompt required to be ask.
-W If password prompt required to be ask before droping Database.
maintenance db-=dbname Name od datbase to connect to for droping target database.

Example of Postgres DROP Database

dropdb -p 5432 -i -e educational_platform;

example

Note that dropdb command is shell command and not psql. You can open psql command and fire \l command to check whether a database is deleted or not.

example 1

So, our database educational_platform is deleted successfully.

Conclusion

We can drop our database either by using the DROP Database statement or dropdb utility. Be careful while doing so as action cannot be undone.

Recommended Articles

This is a guide to Postgres DROP Database. Here we discuss introduction of Postgres DROP Database, syntax, parameters, and examples with code implementation. You may also have a look at the following articles to learn more –

  1. PostgreSQL EXCEPT
  2. Postgres Delete Cascade
  3. PostgreSQL Roles
  4. PostgreSQL Commands
Popular Course in this category
PostgreSQL Course (2 Courses, 1 Project)
  2 Online Courses |  1 Hands-on Project |  7+ Hours |  Verifiable Certificate of Completion
4.5
Price

View Course
0 Shares
Share
Tweet
Share
Primary Sidebar
Footer
About Us
  • Blog
  • Who is EDUCBA?
  • Sign Up
  • Live Classes
  • Corporate Training
  • Certificate from Top Institutions
  • Contact Us
  • Verifiable Certificate
  • Reviews
  • Terms and Conditions
  • Privacy Policy
  •  
Apps
  • iPhone & iPad
  • Android
Resources
  • Free Courses
  • Database Management
  • Machine Learning
  • All Tutorials
Certification Courses
  • All Courses
  • Data Science Course - All in One Bundle
  • Machine Learning Course
  • Hadoop Certification Training
  • Cloud Computing Training Course
  • R Programming Course
  • AWS Training Course
  • SAS Training Course

ISO 10004:2018 & ISO 9001:2015 Certified

© 2022 - EDUCBA. ALL RIGHTS RESERVED. THE CERTIFICATION NAMES ARE THE TRADEMARKS OF THEIR RESPECTIVE OWNERS.

EDUCBA
Free Data Science Course

SPSS, Data visualization with Python, Matplotlib Library, Seaborn Package

*Please provide your correct email id. Login details for this Free course will be emailed to you

By signing up, you agree to our Terms of Use and Privacy Policy.

EDUCBA Login

Forgot Password?

By signing up, you agree to our Terms of Use and Privacy Policy.

EDUCBA
Free Data Science Course

Hadoop, Data Science, Statistics & others

*Please provide your correct email id. Login details for this Free course will be emailed to you

By signing up, you agree to our Terms of Use and Privacy Policy.

EDUCBA

*Please provide your correct email id. Login details for this Free course will be emailed to you

By signing up, you agree to our Terms of Use and Privacy Policy.

Let’s Get Started

By signing up, you agree to our Terms of Use and Privacy Policy.

This website or its third-party tools use cookies, which are necessary to its functioning and required to achieve the purposes illustrated in the cookie policy. By closing this banner, scrolling this page, clicking a link or continuing to browse otherwise, you agree to our Privacy Policy

Loading . . .
Quiz
Question:

Answer:

Quiz Result
Total QuestionsCorrect AnswersWrong AnswersPercentage

Explore 1000+ varieties of Mock tests View more