Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

If table exists drop table then create it, if it does not exist just create it

Tags:

mysql

I'm stumped, I don't know how to go about doing this.

Basically I just want to create a table, but if it exists it needs to be dropped and re-created, not truncated, but if it doesn't exist just create it.

Would anyone be able to help?

like image 406
George Avatar asked Oct 17 '22 18:10

George


People also ask

What happens on DROP if exist and the table does not exist?

The DROP TABLE statement deletes the specified table, and any data associated with it, from the database. The IF EXISTS clause allows the statement to succeed even if the specified tables does not exist. If the table does not exist and you do not include the IF EXISTS clause, the statement will return an error.

What does DROP TABLE if exists do in SQL?

If a table is dropped and there are associated views, stored procedures or functions that were created without schema binding, then stored procedures, functions, and views will still exist but will no longer work.

What happens if you DROP a table on which a view exists?

When you drop a view, the definition of the view and other information about the view is deleted from the system catalog. All permissions for the view are also deleted. Any view on a table that is dropped by using DROP TABLE must be dropped explicitly by using DROP VIEW.


2 Answers

Just put DROP TABLE IF EXISTS `tablename`; before your CREATE TABLE statement.

That statement drops the table if it exists but will not throw an error if it does not.

like image 379
G-Nugget Avatar answered Oct 19 '22 06:10

G-Nugget


Just use DROP TABLE IF EXISTS:

DROP TABLE IF EXISTS `foo`;
CREATE TABLE `foo` ( ... );

Try searching the MySQL documentation first if you have any other problems.

like image 54
r3mainer Avatar answered Oct 19 '22 06:10

r3mainer