EDUCBA

EDUCBA

MENUMENU
  • Free Tutorials
  • Free Courses
  • Certification Courses
  • 360+ Courses All in One Bundle
  • Login

MySQL Merge

By Aanchal GuptaAanchal Gupta

Home » Data Science » Data Science Tutorials » MySQL Tutorial » MySQL Merge

MySQL Merge

Definition of MySQL Merge

MySQL Merge is a MySQL statement which allows us to update records in a specific table on the basis of values that matches from another database table. The MySQL Merge query command is responsible to perform three major query operations at the same time. Suppose, when we apply the CRUD operation commands such as INSERT, DELETE and UPDATE distinctly in our database queries then, we must have to build up three different MySQL statements so that the data in the destination table can be modified using the corresponding rows from the database source table.

For this the users should have SELECT, INSERT, DELETE and UPDATE privilegeson the database tables withwhich you will map to a MERGE table.

Start Your Free Data Science Course

Hadoop, Data Science, Statistics & others

Syntax of MySQL Merge

The succeeding code of structure defines an elementary syntax for MySQL Merge statement query:

Merge TargetTableName USING SourceTableName
ON Merging_Condition
WHEN MATCHED
THEN Update_Query
WHEN NOT MATCHED
THEN Insert_Query
WHEN NOT MATCHED BY SOURCE
THEN DELETE;

Let us discuss the syntax as follows:

  • Initially, we will define the target and source database tables in the MERGE clause query.
  • Then, we will add the merging condition that decides how the table rows from the table source will be matched to the table rows from the table target one. This can be said as similar to a JOIN condition used in the JOIN clause. Normally, we will apply the key columns that can be either UNIQUE Key or PRIMARY Key for the purpose of matching.
  • After that, this merge condition provides three simple states to query as below:
    • Matched: It defines the table rows that will match the Merge condition and for this we need to alter the table rows columns in the table target with the values form the table source. We use the UPDATE statement here.
    • Not Matched: It denotes the table rows from the source table which do not have any equivalent rows present in the target table. In this type of case, we should supplement the rows from the source table to the defined target table. Remember that NOT MATCHED can also be noted as NOT MATCHED BY TARGET. We will use the INSERT query here.
    • Not Matched by Source: It defines the table rows in the given target table which do not have any equivalent rows in the particular source table. We have to apply the match condition to remove or delete rows from the given target table if we want to coordinate the target table with the records from the source one. We will use the DELETE query here.

How does Merge Work in MySQL?

Assume that we have two database tables known as source table and target table. Using these tables we need to perform matching of values from the source table and update the target table. It provides three different cases described as follows:

  • The source table may include few rows that are not present in the target table. Therefore, in this case we can use the INSERT command to input rows into the target table that are found in the source table.
  • The target table may include few rows that are not present in the source table. Therefore, in this case we can use the DELETE command to remove rows from the target table that are not found in the source table.
  • In this case, we will find some table rows in the source table containing similar keys as that of target table rows. However, in the non-key table columns these table rows contain different values. Here, we will update the table rows in the target table with the approaching values from the source table.

A MERGE table is also recognized as anMRG_MyISAM table in the database, which denotes anassembly of comparableMyISAM tables which can be used as a single table. We can perform only SELECT, UPDATE and DELETE procedures on this group of tables. But suppose we want to drop the MERGE table, then after dropping only the MERGE specifications will be released. Here, the tables created comprises of identical table column and info of key because with columns packed inverselyor keys having another order, we cannot apply MERGE over that tables. In MySQL, merge can be performed with UNION, INSERT, or even using JOINS on two or more tables to combine the data values on the basis of UNIQUE key or PRIMARY key.

Examples of MySQL Merge

We will create two tables in the database named Products and Products_Info that will contain information of products.

CREATE TABLE Products (ProductID INT PRIMARY KEY, Product_Name VARCHAR(255) NOT NULL, Cost INT NOT NULL);

Inserting some items as:

INSERT INTO Products(ProductID, Product_Name, Cost) VALUES
(1,'Parle G',100),
(2, 'Maggie', 112),
(3, 'GoodDay Biscuit', 150);

View the table Products:

SELECT * FROM Products;

Output:

 MySQL Merge-1.1

Again,

CREATE TABLE Products_Info (ProductID INT PRIMARY KEY, Product_Name VARCHAR(255) NOT NULL, Cost INT NOT NULL);

Inserting some items as:

INSERT INTO Products_Info(ProductID, Product_Name, Cost) VALUES
(1,'Parle G', 100),
(2, 'Maggie', 112),
(3, 'GoodDay Biscuit', 115),
(4, 'Nestle Coffee', 125),
(5, 'TATA Tea', 80);

View the table Products:

SELECT * FROM Products_Info;

Output:

MySQL Merge-1.2

Now, with the values from the Products_Info table which is as source table by using the MERGE statement to update data to the Products table as target table we will use this below query in SQL because MySQL version may not support MERGE so, we will write code for it also to demonstrate:

MERGE Products t
USING Products_Info s
ON (s.ProductID = t.ProductID)
WHEN MATCHED
THEN UPDATE SET
t.Product_Name = s.Product_Name,
t.Cost = s.Cost
WHEN NOT MATCHED BY TARGET
THEN INSERT (ProductID, Product_Name,Cost)
VALUES(s.ProductID,s.Product_Name,s.Cost)
WHEN NOT MATCHED BY SOURCE
THEN DELETE;

Output:

 MySQL Merge-1.3

In MySQL, MERGE is not supported and we apply INSERT…..ON DUPLICATE KEY UPDATE where MySQL performs update on old tables values based on the new ones. Hence, for MySQL we can follow the below queries to combine two tables:

INSERT IGNORE INTO Products SELECT * FROM Products_Info;

Output:

MySQL Merge-1.4

SELECT * FROM Products UNION DISTINCT SELECT * FROM Products_Info;

Output:

 MySQL Merge-1.5

SELECT * FROM Products INNER JOIN Products_Info ON Products.ProductID = Products_Info.ProductID;

Popular Course in this category
MS SQL Training (13 Courses, 11+ Projects)13 Online Courses | 11 Hands-on Projects | 62+ Hours | Verifiable Certificate of Completion | Lifetime Access
4.5 (5,653 ratings)
Course Price

View Course

Related Courses
Oracle Training (14 Courses, 8+ Projects)PL SQL Training (4 Courses, 2+ Projects)

Output:

 MySQL Merge-1.6

Conclusion

  • MySQL Merge solves a lot of problems like it helps in managing log tables set easily, provides extra speed, can do proficiently the searches and repair operations, and more.
  • The MySQL Merge is useful to map various files to a single one instantly and implements additional file descriptors. But in Merge tables, you cannot use the REPLACE query.

Recommended Articles

This is a guide to MySQL Merge. Here we also discuss the definition and how does merge work in mysql? along with different examples and its code implementation. You may also have a look at the following articles to learn more –

  1. MySQL having
  2. MySQL BLOB
  3. MySQL today()
  4. MySQL Create Function

All in One Data Science Bundle (360+ Courses, 50+ projects)

360+ Online Courses

50+ projects

1500+ Hours

Verifiable Certificates

Lifetime Access

Learn More

0 Shares
Share
Tweet
Share
Primary Sidebar
MySQL Tutorial
  • Functions
    • MySQL Aggregate Function
    • MySQL String functions
    • MySQL Date Functions
    • MySQL Window Functions
    • MySQL Math Functions
    • MySQL Boolean
    • Cursor in MySQL
    • Condition in MySQL
    • MySQL BETWEEN
    • Insert in MySQL
    • MySQL count()
    • MIN() in MySQL
    • MySQL avg()
    • MySQL MAX() Function
    • MySQL BIN()
    • MySQL DECODE()
    • MySQL REGEXP_REPLACE()
    • MySQL TRUNCATE()
    • MySQL ROW_NUMBER()
    • NOT in MySQL
    • MySQL IN Operator
    • LIKE in MySQL
    • ANY in MySQL
    • MySQL NOT IN
    • MySQL CHECK Constraint
    • MySQL DISTINCT
    • MySQL ALL
    • MySQL UNION ALL
    • MySQL EXISTS
    • MySQL ON DELETE CASCADE
    • MySQL REGEXP
    • MySQL Index
    • MySQL Add Index
    • MySQL REINDEX
    • MySQL UNIQUE INDEX
    • Table in MySQL
    • ALTER TABLE MySQL
    • MySQL Temporary Table
    • MySQL Clone Table
    • MySQL Repair Table
    • MySQL Lock Table
    • TRUNCATE TABLE MySQL
    • MySQL Update Set
    • MySQL ALTER TABLE Add Column
    • MySQL RANK()
    • MySQL CTE
    • MySQL LAG()
    • MySQL GROUP_CONCAT()
    • MySQL EXTRACT()
    • MySQL REPLACE
    • MySQL AUTO_INCREMENT
    • MySQL SYSDATE()
    • MySQL NULLIF()
    • MySQL Substring
    • MySQL SUBSTRING_INDEX()
    • MySQL Row
    • MySQL NOW
    • MySQL CEIL
    • MySQL Alias
    • MySQL Trigger
    • MySQL SHOW Triggers
    • MySQL UPDATE Trigger
    • MySQL DELETE Trigger
    • MySQL Stored Procedure
    • ROLLUP in MySQL
    • MySQL INSTR()
    • MySQL Subquery
    • MySQL Timestamp
    • MySQL Hour()
    • MySQL MOD()
    • MySQL DATE_FORMAT()
    • ALTER Column in MySQL 
    • MySQL Rename Column
    • MySQL Interval
    • MySQL CURDATE
    • MySQL BIT
    • MySQL Binlog
    • MySQL Average
    • MySQL TEXT 
    • MySQL SHOW
    • MySQL Offset
    • MySQL Timezone
    • mysql_real_escape_string
    • MySQL Datetime
    • MySQL DATE_SUB()
    • MySQL FULLTEXT
    • MySQL DATE_ADD()
    • MySQL sum()
    • MySQL Merge
    • MySQL BigInt
    • MySQL ROUND
    • MySQL VARCHAR
    • MySQL Decimal
    • MySQL Limit
    • MySQL today()
    • MySQL WEEKDAY
    • MySQL Split
    • MySQL Create Function
    • MySQL BLOB
    • MySQL encode()
    • MySQL Primary Key
    • MySQL Foreign Key
    • Unique Key in MySQL
    • MySQL Drop Foreign Key
    • MYSQL Database
    • Delete Database MySQL
    • MySQL Root
    • MySQL Root Password
    • MySQL Client
    • MySQL Users
    • MySQL User Permissions
    • MySQL add user
    • MySQL List User
    • MySQL Show Users
    • MySQL User Password
    • MySQL Cardinality
    • MySQL Workbench
    • MySQL Backup
    • MySQL REVOKE
    • MySQL Dump
    • MySQL COALESCE
    • MySQL Cluster
    • MySQL Admin Tool
    • MySQL Export Database
    • MySQL Export to CSV
  • Basic
    • Introduction to MySQL
    • What is MySQL
    • Is MySQL Programming Language
    • MySQL Server
    • How To Install MySQL
    • MySQL OpenSource
    • MySQL Commands
    • Views in MySQL
    • MySQL Operators
    • What is MySQL Schema
    • Wildcards in MySQL
    • MySQL Constraints
    • MySQL Administration
    • MySQL Data Type
    • Cheat Sheet MySQL
  • Queries
    • MySQL Queries
    • MySQL Query Commands
    • SELECT in MySQL
    • MySQL INSERT IGNORE
    • MySQL having
    • ORDER BY in MySQL
    • MySQL GROUP BY
    • MySQL GROUP BY Count
    • MySQL GROUP BY month
    • MySQL WHERE Clause
    • MySQL WITH
    • MySQL FETCH
    • MySQL DDL
    • MySQL DML
  • Database
    • What is Data Modeling
    • What is Data Processing
    • DBMS Architecture
    • DBMS Keys
    • Careers in Database Administration
    • What is MySQL Database
    • MySQL Relational Database
    • How to Connect Database to MySQL
    • MySQL Database Repair
    • RDBMS Interview Questions
    • DBMS Interview Questions
  • Joins
    • Joins in MySQL
    • MySQL Outer Join
    • Left Outer Join in MySQL
    • MySQL Self Join
    • Natural Join in MySQL
    • MySQL DELETE JOIN
    • MySQL Update Join
    • MySQL Cross Join
  • Advanced
    • MySQL Flush Privileges
    • MySQL super Privilege
    • MySQL Character Set
    • MySQL Log File
    • MySQL Flush Log
    • Grant Privileges MySQL
    • MySQL WHILE LOOP
    • IF Statement in MySQL
    • MySQL CASE Statement
    • MySQL IF Function
    • MySQL UUID
    • MySQL Replication
    • MySQL Partition
    • Toad for MySQL
    • Navicat for MySQL
    • MySQL Transaction
    • MySQL sort_buffer_size
    • MySQL Sync
    • MySQL Query Cache
    • MySQL Collation
    • MySQL ODBC Driver
  • Interview Questions
    • MySQL Interview Questions

Related Courses

MS SQL Certification Courses

Oracle Certification Courses

PL/SQL Certification Courses

Footer
About Us
  • Blog
  • Who is EDUCBA?
  • Sign Up
  • Corporate Training
  • Certificate from Top Institutions
  • Contact Us
  • Verifiable Certificate
  • Reviews
  • Terms and Conditions
  • Privacy Policy
  •  
Apps
  • iPhone & iPad
  • Android
Resources
  • Free Courses
  • Database Management
  • Machine Learning
  • All Tutorials
Certification Courses
  • All Courses
  • Data Science Course - All in One Bundle
  • Machine Learning Course
  • Hadoop Certification Training
  • Cloud Computing Training Course
  • R Programming Course
  • AWS Training Course
  • SAS Training Course

© 2020 - EDUCBA. ALL RIGHTS RESERVED. THE CERTIFICATION NAMES ARE THE TRADEMARKS OF THEIR RESPECTIVE OWNERS.

EDUCBA
Free Data Science Course

Hadoop, Data Science, Statistics & others

*Please provide your correct email id. Login details for this Free course will be emailed to you
Book Your One Instructor : One Learner Free Class

Let’s Get Started

This website or its third-party tools use cookies, which are necessary to its functioning and required to achieve the purposes illustrated in the cookie policy. By closing this banner, scrolling this page, clicking a link or continuing to browse otherwise, you agree to our Privacy Policy

EDUCBA

*Please provide your correct email id. Login details for this Free course will be emailed to you
EDUCBA Login

Forgot Password?

EDUCBA
Free Data Science Course

Hadoop, Data Science, Statistics & others

*Please provide your correct email id. Login details for this Free course will be emailed to you

Special Offer - MS SQL Certification Courses Learn More