Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • Python Database
  • Python MySQL
  • Python SQLite
  • Python MongoDB
  • PostgreSQL
  • SQLAlchemy
  • Django
  • Flask
  • SQL
  • ReactJS
  • Vue.js
  • AngularJS
  • API
  • REST API
  • Express.js
  • NodeJS
Open In App
Next Article:
How to Add a Column to a MySQL Table in Python?
Next article icon

How to Copy a Table Definition in MySQL Using Python?

Last Updated : 11 Dec, 2020
Comments
Improve
Suggest changes
Like Article
Like
Report

Python requires an interface to access a database server. Python supports a wide range of interfaces to interact with various databases. To communicate with a MySQL database, MySQL Connector Python module, an API written purely in Python, is used. This module is self-sufficient meaning that it does not have dependencies and only requires the standard Python library. 

Copying a table definition in SQL:

With the CREATE and SELECT statements, one can copy the definition and data from an existing table to a new table.

Syntax:

CREATE TABLE new_table AS   SELECT * FROM original_table;

Here, the contents of an existing table (original_table) are copied to a new table (new_table). The CREATE statement creates a new table having the structure defined by the SELECT statement and populates the new table with the selected columns (* indicates all columns are selected). 

Note: The database objects associated with the original table like indexes, key constraints etc., are not duplicated.

To copy a table along with its dependent database objects, the CREATE, LIKE and INSERT statements are used.

Syntax:

CREATE TABLE new_table   LIKE original_table;    INSERT new_table   SELECT * FROM original_table;

First, the CREATE statement creates a new table (new_table) having the same structure and dependent objects as the existing table (original_table). Then the INSERT statement populates the new table with the values selected from the original table. Simply using the CREATE statement without the INSERT will create an empty table having the structure and dependent objects of the existing table.

Steps using Python:

  1. Establish a connection with the database server and create a cursor object.
  2. Use the cursor object to execute the CREATE-SELECT or CREATE-LIKE-INSERT statements to copy a table.
  3. Check if the table definition has been copied.

Let’s see some examples for better understanding.

Database in use:

We will use a store database with a products table describing the products and the available stock.

Example 1: Copy table definition using CREATE-SELECT statement

Use the connect() function to establish a connection with the database server and use the cursor() function to create a cursor object. With this cursor object, execute the CREATE-SELECT statement for creating a copy of the products table new inventory table using the execute() function. To check if the newly created table has the same table definition as the original, use the DESC statement to describe the structure and the SELECT statement to check the table contents.

Python

# Import required packages
import mysql.connector
  
# Establish connection to MySQL database
db = mysql.connector.connect(
    host = "localhost",
    user = "username",
    password = "geeksforgeeks",
    database = "store"
)
  
# Create a cursor object
cursor = db.cursor()
  
# MySQL query for copying existing table,
# selecting new table data and
# describing new table structure
queries = "CREATE TABLE inventory1 AS SELECT * FROM products;\
           DESC inventory1;"
      
# Execute the query 
results = cursor.execute(queries, multi = True)
  
# Print data and description of newly created table
for result in results:
    if result.with_rows:
        for row in result:
            print(row)
              
# Close database connection
db.close()
                      
                       

Output:

All the values from the products table are copied to the inventory table. The structure, that is, the data types and columns are retained. However, the database objects like the primary key constraint of prod_id is not retained. 

Example 2: Copy table definition without table content using CREATE-SELECT statement

Use the same code for establishing a connection and verification as the above example. To simply copy the table definition and not the contents, add a WHERE clause to the SELECT statement such that it returns an empty set and no values are copied as follows.

Python

# Import required packages
import mysql.connector
  
# Establish connection to MySQL database
db = mysql.connector.connect(
    host="localhost",
    user="username",
    password="geeksforgeeks",
    database="store"
)
  
# Create a cursor object
cursor = db.cursor()
  
# MySQL queries for copying existing table
# without copying its data,
# selecting new table data and
# describing new table structure
queries = "CREATE TABLE inventory2 AS \
           SELECT * FROM products \
           WHERE 1=0; \
           DESC inventory2;"
  
# Execute the query
results = cursor.execute(queries, multi=True)
  
# Print data and description of newly created table
for result in results:
    if result.with_rows:
        for row in result:
            print(row)
  
# Close database connection
db.close()
                      
                       

The 1 = 0 condition in the CREATE-SELECT query always evaluates false. So, the query returns an empty table, creating a new empty inventory table with the same structure as the existing products table.

Output:

Example 3: Copy table definition and dependent database objects using CREATE-LIKE statement

Use the same code for establishing a connection and verification as Example 1. To copy a table with all its dependent objects and contents, use the CREATE-LIKE-INSERT statement as shown below.

Python

# Import required packages
import mysql.connector
  
# Establish connection to MySQL database
db = mysql.connector.connect(
    host="localhost",
    user="username",
    password="geeksforgeeks",
    database="store"
)
  
# Create a cursor object
cursor = db.cursor()
  
# MySQL queries for copying existing table,
# selecting new table data and
# describing new table structure
queries = "CREATE TABLE inventory3 LIKE products; \
           INSERT inventory3 SELECT * FROM products;\
           DESC inventory3;"
      
# Execute the query 
results = cursor.execute(queries, multi = True)
  
# Print data and description of newly created table
for result in results:
    if result.with_rows:
        for row in result:
            print(row)
              
# Close database connection
db.close()
                      
                       

Output:

Notice that the primary key constraint of prod_id is retained.

Example 4: Copy table definition and dependent objects without table data using CREATE-LIKE statement

Use the same code for establishing a connection and verification as Example 1. To simply copy the table definition and not the contents, remove the INSERT statement as shown below.

Python

# Import required packages
import mysql.connector
  
# Establish connection to MySQL database
db = mysql.connector.connect(
    host="localhost",
    user="username",
    password="geeksforgeeks",
    database="store"
)
  
# Create a cursor object
cursor = db.cursor()
  
# MySQL queries for copying existing table
# without copying its data,
# selecting new table data and
# describing new table structure
queries = "CREATE TABLE inventory4 LIKE products; \
           DESC inventory4;"
  
# Execute the query
results = cursor.execute(queries, multi=True)
  
# Print data and description of newly created table
for result in results:
    if result.with_rows:
        for row in result:
            print(row)
  
# Close database connection
db.close()
                      
                       

Output:



Next Article
How to Add a Column to a MySQL Table in Python?

A

akshisaxena
Improve
Article Tags :
  • Python
  • Python-mySQL
Practice Tags :
  • python

Similar Reads

  • How to Copy a Table in MySQL Using Python?
    In this article, we will create a table in MySQL and will create a copy of that table using Python. We will copy the entire table, including all the columns and the definition of the columns, as well as all rows of data in the table. To connect to MySQL database using python, we need PyMySql module.
    3 min read
  • How to Show All Tables in MySQL using Python?
    A connector is employed when we have to use mysql with other programming languages. The work of mysql-connector is to provide access to MySQL Driver to the required language. Thus, it generates a connection between the programming language and the MySQL Server. In order to make python interact with
    1 min read
  • How to Add a Column to a MySQL Table in Python?
    Prerequisite: Python: MySQL Create Table Python allows the integration of a wide range of database servers with applications. A database interface is required to access a database from Python. MySQL Connector-Python module is an API in python for communicating with a MySQL database.   ALTER statemen
    4 min read
  • How to Concatenate Column Values of a MySQL Table Using Python?
    Prerequisite: Python: MySQL Create Table In this article, we show how to concatenate column values of a MySQL table using Python. We use various data types in SQL Server to define data in a particular column appropriately. We might have requirements to concatenate data from multiple columns into a s
    2 min read
  • Add comment to column in MySQL using Python
    MySQL server is an open-source relational database management system which is a major support for web-based applications. Databases and related tables are the main component of many websites and applications as the data is stored and exchanged over the web. In order to access MySQL databases from a
    3 min read
  • How to Perform Arithmetic Across Columns of a MySQL Table Using Python?
    Python is a dynamic language, and Python applications can be integrated with database servers. The module used to access a MySQL database from Python is MySQL Connector Python. PyMySQL, MySQLDB and mysqlclient are other Python modules to communicate with a MySQL database server in Python. However, w
    5 min read
  • How to store XML data into a MySQL database using Python?
    In this article, we are going to store XML data into the MySQL database using python through XAMPP server. So we are taking student XML data and storing the values into the database. RequirementsXAMPP server: It is a cross-platform web server used to develop and test programs on a local server. It i
    3 min read
  • Adding new enum column to an existing MySQL table using Python
    Prerequisite: Python: MySQL Create Table In this article, we are going to see how to add a new enum column to an existing MySQL table using Python. Python allows the integration of a wide range of database servers with applications. A database interface is required to access a database from Python.
    1 min read
  • How to Find Duplicate Values in a SQL Table using Python?
    MySQL server is an open-source relational database management system that is a major support for web-based applications. Databases and related tables are the main component of many websites and applications as the data is stored and exchanged over the web. In order to access MySQL databases from a w
    3 min read
  • Python MariaDB - Insert into Table using PyMySQL
    MariaDB is an open source Database Management System and its predecessor to MySQL. The pymysql client can be used to interact with MariaDB similar to that of MySQL using Python. In this article we will look into the process of inserting rows to a table of the database using pymysql. You can insert o
    2 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences