If you’re getting an error that reads something like “ERROR 1050 (42S01) at line 22: Table ‘Pets’ already exists” when trying to create a table in MariaDB, it’s most likely because there’s already a table in the database with the same name.
To fix this issue, either change the name of the table you’re trying to create, or check the existing table to see if it’s the one you actually need.
Example of Error
Here’s an example of code that produces the error:
CREATE TABLE Pets (
PetId int NOT NULL PRIMARY KEY,
PetTypeId int NOT NULL,
OwnerId int NOT NULL,
PetName varchar(60) NOT NULL,
DOB date DEFAULT NULL
);
Result:
ERROR 1050 (42S01) at line 22: Table 'Pets' already exists
In this case, I’m trying to create a table called Pets
, but it already exists in the database.
Solution
The most obvious solution is to change the name of the table we’re creating:
CREATE TABLE Pets2 (
PetId int NOT NULL PRIMARY KEY,
PetTypeId int NOT NULL,
OwnerId int NOT NULL,
PetName varchar(60) NOT NULL,
DOB date DEFAULT NULL
);
Here, I simply renamed the table to Pets2
. In practice, we would probably give it a more appropriate name.
Bear in mind that if there’s already a table with the same name as the one we’re trying to create, there’s a possibility that our desired table has already been created. In this case we wouldn’t need to recreate it (unless we had good reason). We could either just go ahead and use it, or we could alter it to suit our new requirements.
We can always modify our CREATE TABLE
statement so that it won’t throw an error if the table already exists. To do this, we can use the IF NOT EXISTS
clause:
CREATE TABLE IF NOT EXISTS Pets (
PetId int NOT NULL PRIMARY KEY,
PetTypeId int NOT NULL,
OwnerId int NOT NULL,
PetName varchar(60) NOT NULL,
DOB date DEFAULT NULL
);
If the table already exists, a warning will be issued (but no error).
The Table REALLY Doesn’t Exist?
If you believe that the table really doesn’t exist, perhaps there’s something else going on. See this article on Stack Overflow for a discussion on possible solutions. That article is regarding MySQL (not MariaDB), but the 1050 error is a shared error for both MySQL and MariaDB.