Advertisements
First thing first, if you would like to play along with this tutorial, here is a code block to create a database and table:
create database sandbox;
use sandbox;
CREATE TABLE employee_id (
emp_nm varchar(30) not null,
emp_id varchar(8),
b_emp_id varchar(8),
PRIMARY KEY(emp_nm) );
To check if a table exists in MySql, you can use the INFORMATION_SCHEMA.TABLES table.
Running the following code, produces the results below:
Select *
from INFORMATION_SCHEMA.TABLES
where table_schema = 'Sandbox';
SELECT IF( EXISTS(
SELECT *
FROM INFORMATION_SCHEMA.TABLES
WHERE TABLE_NAME = 'employee_id'), 1, 0);
And if I try it with a table name that does not exist:
One of the more common uses I find for this when I need to create a table in a script. I want to make sure a table with same name doesn’t already exist, or my query will fail. So I write a query like the one below.
drop table if exists employee_id;
CREATE TABLE employee_id (
emp_nm varchar(30) not null,
emp_id varchar(8),
b_emp_id varchar(8),
PRIMARY KEY(emp_nm) );
INSERT INTO employee_id
(emp_nm, emp_id)
VALUES
('Bob', 'A1234567'),
('Lisa', 'A1234568'),
('Priyanka', 'B1234567');