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

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

Thanks

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