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!

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 trial

Development Tools

Databases the purpose of IF EXISTS

I've been going through the databases library can someone help explain the purpose of IF EXIST i can't seem to grasp why it's important to use i've tried doing research on the net too see examples but none of them are really clear to me would be helpful for just a basic explanation


2 Answers

Rajanand Ilangovan
Rajanand Ilangovan
3,226 Points

For example, you want to create a table in a database.

  1. You write a sql code to create a table.
  2. Execute it and table is created if not exist else it returns an error message "There is already an object named 'table_name_here' in the database.

So, what will we do? Drop the existing table and re-execute our sql code to create the table. To do this, we can use IF EXISTS. If the object exist, drop the object first. and then create table sql code will get execute successfully without any error.

Ohhhh alright i get it now sort of like replacing something that's already there and avoiding errors thanks for that

Rajanand Ilangovan
Rajanand Ilangovan
3,226 Points

yes, that's right Tunde. if it answers your question, mark it as answer. :)

Thanks for that mate how do i mark your answer haha still a bit of a noob