- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Create a table if it does not already exist and insert a record in the same query with MySQL
Use CREATE TABLE IF NOT EXISTS for this as shown in the below syntax −
create table if not exists yourTableName ( yourColumnName1 dataType, yourColumnName2 dataType, yourColumnName3 dataType, . . N ) as select yourValue1 as yourColumnName1 , yourValue2 as yourColumnName2 , yourValue3 as yourColumnName3,.............................N;
Let us first create a table and insert value if the table does not already exist −
mysql> create table if not exists DemoTable ( id int, FirstName varchar(20), LastName varchar(20) ) as select 100 as id, 'John' as FirstName , 'Smith' as LastName; Query OK, 1 row affected (0.65 sec) Records: 1 Duplicates: 0 Warnings: 0
Let us now display the records −
mysql> select *from DemoTable;
This will produce the following output −
+------+-----------+----------+ | id | FirstName | LastName | +------+-----------+----------+ | 100 | John | Smith | +------+-----------+----------+ 1 row in set (0.00 sec)
- Related Articles
- How to check if a table exists in MySQL and create if it does not already exist?
- Create view in MySQL only if it does not already exist?
- PHP and MYSQL database connection and table creation only once if it does not already exist?
- MySQL create user if it does not exist?
- Insert records in MongoDB collection if it does not exist?
- How to insert only those records that does not exist in a MySQL table?
- Insert record in a MySQL table with Java
- How to create a folder if it does not exist in C#?
- How can I create a python directory if it does not exist?
- How can I create a directory if it does not exist using Python?
- Create a table inside a MySQL stored procedure and insert a record on calling the procedure
- Select from table where value does not exist with MySQL?
- INSERT INTO table if a table exists in MySQL else implement CREATE TABLE and create the table
- Add object to array in JavaScript if name does not already exist?
- Upsert in MongoDB while using custom _id values to insert a document if it does not exist?

Advertisements