Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

Development Tools Database Foundations Creating Tables and Manipulating Data with SQL Creating a Database

Why use if not exists ?

I don't understand what is the reason of using the SQL syntax IF NOT EXISTS when creating a database, is it like a conditional or is just there to disable the errors and show warning messages instead ? I am a bit confused and any example would be helpful thanks !

2 Answers

The if NOT exists is used to check if the database exists prior to creating a new one. It is saying:

If the database does not exist, then create one.

You do not want to create a duplicate database, so this ensures you do not. Theoretically, you could use an if exists, then do all this stuff, else create the database. But if you do that, then you have to recode all the stuff you want to do after the database is created.

it is starting to make sense. thanks !

Pavle Lucic
Pavle Lucic
10,801 Points

maybe it could be use in sentence, create db1 if not exist, OR create db2 if db1 exist

I didn't think you could create a duplicate database. I thought you would get an error that the database already exists?

I thought you would use IF NOT EXISTS to prevent the error, not prevent creating a duplicate database.

Andre West
Andre West
2,861 Points

The way I understood it is that by using "if not exists" you get a warning instead of an error, in case youre trying to create a database that already exists. The reason why you would want a warning over an error is circumstantial but an error will stop your code from running while it will continue with a warning.