Welcome to the Treehouse Community
Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.
Looking to learn something new?
Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.
Start your free trialsayedshahidi
9,158 PointsWhy 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
Ted Sumner
Courses Plus Student 17,967 PointsThe 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.
Andre West
2,861 PointsThe 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.
sayedshahidi
9,158 Pointssayedshahidi
9,158 Pointsit is starting to make sense. thanks !
Pavle Lucic
10,801 PointsPavle Lucic
10,801 Pointsmaybe it could be use in sentence, create db1 if not exist, OR create db2 if db1 exist
David Bilson
13,819 PointsDavid Bilson
13,819 PointsI 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.