{"id":97227,"date":"2020-11-24T11:00:00","date_gmt":"2020-11-24T09:00:00","guid":{"rendered":"https:\/\/examples.javacodegeeks.com\/?p=97227"},"modified":"2021-09-29T10:14:11","modified_gmt":"2021-09-29T07:14:11","slug":"sql-insert-query-example","status":"publish","type":"post","link":"https:\/\/examples.javacodegeeks.com\/sql-insert-query-example\/","title":{"rendered":"SQL Insert Query Example"},"content":{"rendered":"<h2 class=\"wp-block-heading\" id=\"h-1-introduction\">1. Introduction<\/h2>\n<p>In this article, we will look at one of the Data Manipulation Language (DML) constructs or statements called Insert query using the MySQL RDBMS.<\/p>\n<h2 class=\"wp-block-heading\" id=\"h-2-what-is-data-manipulation-language\">2. What is Data Manipulation Language?<\/h2>\n<p>In SQL, Data Manipulation language consists of SQL data-change statements that modify data but not the underlying schema or database objects. The commands included in the data manipulation language are:<\/p>\n<ul class=\"wp-block-list\">\n<li>Insert &#8211; add new records\/tuples in table or tables.<\/li>\n<li>Update \u2013 alter records\/tuples already present.<\/li>\n<li>Delete \u2013 remove records\/tuples.<\/li>\n<\/ul>\n<p>Unlike Data Definition statements, DML statements are not auto-commit transactions by default. Hence, until we specifically \u201ccommit\u201d the transaction, the changes can be undone. These commands also correspond to the \u201cCRUD\u201d (Create-retrieve-update-delete) statements which most front-end applications use.<\/p>\n<h3 class=\"wp-block-heading\" id=\"h-2-1-what-is-a-transaction\">2.1 What is a Transaction?<\/h3>\n<p>A transaction is a unit of work, performed in the order in a database. Transactions propagate or reverse one or more changes done to a database. Transactions are used for DML statements and are extremely important to ensure data integrity. More on transactions in general <a href=\"https:\/\/en.wikipedia.org\/wiki\/Database_transaction\" target=\"_blank\" rel=\"noreferrer noopener\">here<\/a>.<\/p>\n<h2 class=\"wp-block-heading\" id=\"h-3-sql-insert-query-syntax\">3. SQL Insert Query Syntax<\/h2>\n<p>In general, the Insert statement has 2 syntaxes. The first syntax is to insert only specific columns in a table.<\/p>\n<pre class=\"brush:sql\">INSERT INTO table_name (column1, column2, column3, ...)\nVALUES (value1, value2, value3, ...);\n<\/pre>\n<li>Where table_name = table in which the insertion needs to happen.<\/li>\n<li>Column\/field_name = name of the columns in the table.<\/li>\n<li>Value = the actual record that is put in the table.<\/li>\n<p>For this insert statement syntax, all the columns with the \u201cNot NULL\u201d constraint must be inserted. The columns which are not inserted, get the value of \u201cNULL\u201d. Alternatively, we can also specify a default value to be specified by using the DEFAULT Keyword.<\/p>\n<p>If all the columns in the table are to be filled, we can simply skip the column_names and directly give the values.<\/p>\n<pre class=\"brush:sql\">INSERT INTO table_name \nVALUES (value1, value2, value3, ...);\n<\/pre>\n<p>The syntaxes above will insert a single record in the table mentioned. To insert multiple records into a table, depending on the RDBMS we use, different syntaxes are available. For example, to insert multiple records at once in Oracle, we use the \u201cINSERT ALL\u201d while the MySQL and PostgreSQL use the \u201cINSERT INTO\u201d. Microsoft SQL does not support multiple record insertion<\/p>\n<h2 class=\"wp-block-heading\" id=\"h-4-insert-query-in-mysql\">4. INSERT Query in MySQL<\/h2>\n<p>The full syntax of the insert query as per the MySQL docs is<\/p>\n<pre class=\"brush:sql\">INSERT [LOW_PRIORITY | DELAYED | HIGH_PRIORITY] [IGNORE]\n    [INTO] tbl_name\n    [PARTITION (partition_name [, partition_name] ...)]\n    [(col_name [, col_name] ...)]\n    { {VALUES | VALUE} (value_list) [, (value_list)] ...\n      |\n      VALUES row_constructor_list\n    }\n    [AS row_alias[(col_alias [, col_alias] ...)]]\n    [ON DUPLICATE KEY UPDATE assignment_list]\n\nINSERT [LOW_PRIORITY | DELAYED | HIGH_PRIORITY] [IGNORE]\n    [INTO] tbl_name\n    [PARTITION (partition_name [, partition_name] ...)]\n    [AS row_alias[(col_alias [, col_alias] ...)]]\n    SET assignment_list\n    [ON DUPLICATE KEY UPDATE assignment_list]\n\nINSERT [LOW_PRIORITY | HIGH_PRIORITY] [IGNORE]\n    [INTO] tbl_name\n    [PARTITION (partition_name [, partition_name] ...)]\n    [(col_name [, col_name] ...)]\n    [AS row_alias[(col_alias [, col_alias] ...)]]\n    {SELECT ... | TABLE table_name}\n    [ON DUPLICATE KEY UPDATE assignment_list]\n\nvalue:\n    {expr | DEFAULT}\n\nvalue_list:\n    value [, value] ...\n\nrow_constructor_list:\n    ROW(value_list)[, ROW(value_list)][, ...]\n\nassignment:\n    col_name = [row_alias.]value\n\nassignment_list:\n    assignment [, assignment] ...\n<\/pre>\n<p>To understand the most used options and their syntaxes, we will look at some examples next.<\/p>\n<h3 class=\"wp-block-heading\" id=\"h-4-1-setup-for-examples\">4.1 Setup for examples<\/h3>\n<p>Forgoing through the examples related to Insert, we will consider a new database called \u201cTestDB\u201d. This database has 3 tables named employees, departments, and employee_dept.<\/p>\n<p>The Create scripts for the 3 tables are as follows:<\/p>\n<pre class=\"brush:sql\">CREATE TABLE EMPLOYEES(\n    EMP_ID INT AUTO_INCREMENT PRIMARY KEY,\n    FIRST_NAME VARCHAR(20) NOT NULL,\n    LAST_NAME VARCHAR(20),\n    BIRTH_DATE DATE DEFAULT '1900-00-00',\n    HIRE_DATE DATE DEFAULT (CURRENT_DATE())\n);\n\nCREATE TABLE DEPARTMENTS(\n   DEPT_ID INT AUTO_INCREMENT PRIMARY KEY,\n   DEPT_NAME VARCHAR(30)\n);\n\nCREATE TABLE EMPLOYEE_DEPT(\n   RECORD_ID INT AUTO_INCREMENT PRIMARY KEY,\n   EMP_ID INT,\n   DEPT_ID INT,\n   FROM_DATE DATE,\n   TO_DATE DATE,\n   FOREIGN KEY (EMP_ID) REFERENCES EMPLOYEES(EMP_ID),\n   FOREIGN KEY (DEPT_ID) REFERENCES DEPARTMENTS(DEPT_ID)\n);\n<\/pre>\n<p>We also have another table called EMPLOYEES2 which has the same structure as the Employees table.<div style=\"display:inline-block; margin: 15px 0;\"> <div id=\"adngin-JavaCodeGeeks_incontent_video-0\" style=\"display:inline-block;\"><\/div> <\/div><\/p>\n<pre class=\"brush:sql\">CREATE TABLE EMPLOYEES2(\n    EMP_ID INT PRIMARY KEY,\n    FIRST_NAME VARCHAR(20) NOT NULL,\n    LAST_NAME VARCHAR(20),\n    BIRTH_DATE DATE DEFAULT '1900-00-00',\n    HIRE_DATE DATE DEFAULT (CURRENT_DATE())\n);\n<\/pre>\n<p>For running the queries, we will use the MySQL Workbench. The documentation for MySQL Workbench is available <a href=\"https:\/\/dev.mysql.com\/doc\/workbench\/en\/\" target=\"_blank\" rel=\"noreferrer noopener\">here<\/a>. Set the Workbench to \u201cAuto-commit Transactions\u201d.<\/p>\n<h2 class=\"wp-block-heading\" id=\"h-5-insert-into-examples\">5. INSERT INTO Examples<\/h2>\n<p>Using the setup above we will look at various options and syntaxes used with the Insert statements.<\/p>\n<h3 class=\"wp-block-heading\" id=\"h-5-1-insert-a-single-row-in-the-table-using-column_names\">5.1 Insert a single row in the table using column_names<\/h3>\n<p>To insert a single row in say the Employees table, we use the query<\/p>\n<pre class=\"brush:sql\"> INSERT INTO EMPLOYEES (FIRST_NAME, LAST_NAME, BIRTH_DATE, HIRE_DATE)\nvalues('Thorin','Oakenshield','2746-01-01','2760-05-01'); \n<\/pre>\n<p>The output is as follows:<\/p>\n<div class=\"wp-block-image\">\n<figure class=\"aligncenter size-full\"><img decoding=\"async\" width=\"820\" height=\"449\" src=\"https:\/\/examples.javacodegeeks.com\/wp-content\/uploads\/2020\/11\/insert_all_values.jpg\" alt=\"SQL Insert Query - 'Insert into' with all column names specified\" class=\"wp-image-97229\" srcset=\"https:\/\/examples.javacodegeeks.com\/wp-content\/uploads\/2020\/11\/insert_all_values.jpg 820w, https:\/\/examples.javacodegeeks.com\/wp-content\/uploads\/2020\/11\/insert_all_values-300x164.jpg 300w, https:\/\/examples.javacodegeeks.com\/wp-content\/uploads\/2020\/11\/insert_all_values-768x421.jpg 768w\" sizes=\"(max-width: 820px) 100vw, 820px\" \/><figcaption>&#8216;Insert into&#8217; with all column names specified<\/figcaption><\/figure>\n<\/div>\n<p>If you observe, the first column in the <em>employees <\/em>table: EMP_ID is not mentioned in our Insertion Query but is still inserted with a correct value. The reason for that is we have declared the EMP_ID as an auto_increment value. It means that MySQL generates a sequential integer whenever a row is inserted into the table.<\/p>\n<h3 class=\"wp-block-heading\" id=\"h-5-2-insert-a-single-row-in-a-table-without-column_names\">5.2 Insert a single row in a table without column_names<\/h3>\n<p>If all the columns are to be inserted in a table, we can skip the column names altogether and just put the values. While doing so, we must set the EMP_ID i.e. the auto_incremented value to a DEFAULT value.<\/p>\n<pre class=\"brush:sql\">INSERT INTO EMPLOYEES\nvalues(default,'Thrain','Oakenshield','2850-01-01','2910-05-01');\n<\/pre>\n<p>The output is as follows:<\/p>\n<div class=\"wp-block-image\">\n<figure class=\"aligncenter size-full\"><img decoding=\"async\" width=\"820\" height=\"552\" src=\"https:\/\/examples.javacodegeeks.com\/wp-content\/uploads\/2020\/11\/insert_without_column_names.jpg\" alt=\"SQL Insert Query - 'Insert into' with no column names specified\" class=\"wp-image-97230\" srcset=\"https:\/\/examples.javacodegeeks.com\/wp-content\/uploads\/2020\/11\/insert_without_column_names.jpg 820w, https:\/\/examples.javacodegeeks.com\/wp-content\/uploads\/2020\/11\/insert_without_column_names-300x202.jpg 300w, https:\/\/examples.javacodegeeks.com\/wp-content\/uploads\/2020\/11\/insert_without_column_names-768x517.jpg 768w\" sizes=\"(max-width: 820px) 100vw, 820px\" \/><figcaption>&#8216;Insert into&#8217; with no column names specified<\/figcaption><\/figure>\n<\/div>\n<h3 class=\"wp-block-heading\" id=\"h-5-3-insert-a-single-row-in-a-table-with-a-default-value\">5.3 Insert a single row in a table with a default value<\/h3>\n<p>In the <em>employees <\/em>table, we have defined the Birth_date with the default value as \u201c1900-00-00\u201d. When during insertion we do not mention the birth_date, then the record is inserted with the default value.<\/p>\n<pre class=\"brush:sql\"> INSERT INTO EMPLOYEES (FIRST_NAME,HIRE_DATE)\nvalues('Smaug','2600-05-01');\n<\/pre>\n<p>The output is as follows:<\/p>\n<div class=\"wp-block-image\">\n<figure class=\"aligncenter size-full\"><img decoding=\"async\" width=\"810\" height=\"526\" src=\"https:\/\/examples.javacodegeeks.com\/wp-content\/uploads\/2020\/11\/insert_with_default_values.jpg\" alt=\"SQL Insert Query - 'Insert into' with default values\" class=\"wp-image-97231\" srcset=\"https:\/\/examples.javacodegeeks.com\/wp-content\/uploads\/2020\/11\/insert_with_default_values.jpg 810w, https:\/\/examples.javacodegeeks.com\/wp-content\/uploads\/2020\/11\/insert_with_default_values-300x195.jpg 300w, https:\/\/examples.javacodegeeks.com\/wp-content\/uploads\/2020\/11\/insert_with_default_values-768x499.jpg 768w\" sizes=\"(max-width: 810px) 100vw, 810px\" \/><figcaption>&#8216;Insert into&#8217; with default values<\/figcaption><\/figure>\n<\/div>\n<h3 class=\"wp-block-heading\" id=\"h-5-4-insert-with-not-null-constraint-violation\">5.4 Insert with Not NULL constraint violation<\/h3>\n<p>If a column is specified as \u201cNot NULL\u201d, it necessarily needs to have a value inserted in it. If we try to insert a record without a value specified for the \u201cNot NULL\u201d column, then insertion fails and the record is not inserted.<\/p>\n<pre class=\"brush:sql\"> INSERT INTO EMPLOYEES(LAST_NAME,BIRTH_DATE,HIRE_DATE)\nVALUES('Oakenshield','2650-09-12','3010-07-15'); <\/pre>\n<p>The output is as follows:<\/p>\n<div class=\"wp-block-image\">\n<figure class=\"aligncenter size-full\"><img decoding=\"async\" width=\"810\" height=\"363\" src=\"https:\/\/examples.javacodegeeks.com\/wp-content\/uploads\/2020\/11\/insert_error_not_null_constraint.jpg\" alt=\"SQL Insert Query - 'Not Null' constraint violated\" class=\"wp-image-97232\" srcset=\"https:\/\/examples.javacodegeeks.com\/wp-content\/uploads\/2020\/11\/insert_error_not_null_constraint.jpg 810w, https:\/\/examples.javacodegeeks.com\/wp-content\/uploads\/2020\/11\/insert_error_not_null_constraint-300x134.jpg 300w, https:\/\/examples.javacodegeeks.com\/wp-content\/uploads\/2020\/11\/insert_error_not_null_constraint-768x344.jpg 768w\" sizes=\"(max-width: 810px) 100vw, 810px\" \/><figcaption>&#8216;Not Null&#8217; constraint violated<\/figcaption><\/figure>\n<\/div>\n<h3 class=\"wp-block-heading\" id=\"h-5-5-insert-multiple-records-in-a-table\">5.5 Insert Multiple records in a table<\/h3>\n<p>To insert multiple records in the Departments table, we use the query<\/p>\n<pre class=\"brush:sql\"> INSERT INTO DEPARTMENTS (DEPT_NAME)\nvalues\n('Logistics'),\n('Support'),\n('Development'),\n('Transport');\n<\/pre>\n<p>Here again, the DEPT_ID column is auto-increment and will be generated in Sequence.<\/p>\n<div class=\"wp-block-image\">\n<figure class=\"aligncenter size-full\"><img decoding=\"async\" width=\"820\" height=\"441\" src=\"https:\/\/examples.javacodegeeks.com\/wp-content\/uploads\/2020\/11\/insert_multiple_values.jpg\" alt=\"Multiple Values insert\" class=\"wp-image-97233\" srcset=\"https:\/\/examples.javacodegeeks.com\/wp-content\/uploads\/2020\/11\/insert_multiple_values.jpg 820w, https:\/\/examples.javacodegeeks.com\/wp-content\/uploads\/2020\/11\/insert_multiple_values-300x160.jpg 300w, https:\/\/examples.javacodegeeks.com\/wp-content\/uploads\/2020\/11\/insert_multiple_values-768x413.jpg 768w\" sizes=\"(max-width: 820px) 100vw, 820px\" \/><figcaption>Multiple Values insert<\/figcaption><\/figure>\n<\/div>\n<h3 class=\"wp-block-heading\" id=\"h-5-6-insert-into-table-with-foreign-keys-constraint\">5.6 Insert into table with Foreign keys constraint<\/h3>\n<p>For Insertion in a table, with references to other tables i.e. foreign keys, the records for the Foreign key must exist in the other table before we can insert into the current table.<\/p>\n<p>Correct Foreign key reference query<\/p>\n<pre class=\"brush:sql\"> INSERT INTO EMPLOYEE_DEPT (EMP_ID,DEPT_ID,FROM_DATE,TO_DATE)\nVALUES (1,3,'2760-05-15','2800-10-15');\n<\/pre>\n<p>The output is as follows:<\/p>\n<div class=\"wp-block-image\">\n<figure class=\"aligncenter size-full\"><img decoding=\"async\" width=\"810\" height=\"397\" src=\"https:\/\/examples.javacodegeeks.com\/wp-content\/uploads\/2020\/11\/insertion_foreign_keys.jpg\" alt=\"Insert foreign key records\" class=\"wp-image-97234\" srcset=\"https:\/\/examples.javacodegeeks.com\/wp-content\/uploads\/2020\/11\/insertion_foreign_keys.jpg 810w, https:\/\/examples.javacodegeeks.com\/wp-content\/uploads\/2020\/11\/insertion_foreign_keys-300x147.jpg 300w, https:\/\/examples.javacodegeeks.com\/wp-content\/uploads\/2020\/11\/insertion_foreign_keys-768x376.jpg 768w\" sizes=\"(max-width: 810px) 100vw, 810px\" \/><figcaption>Insert foreign key records<\/figcaption><\/figure>\n<\/div>\n<p>Here both the records for the EMP_ID and DEPT_ID exist in their respective tables.<\/p>\n<h3 class=\"wp-block-heading\" id=\"h-5-7-foreign-key-constraint-violation\">5.7 Foreign Key constraint violation<\/h3>\n<p>IF the Foreign key we are trying to insert is either not present or is incorrect, then record cannot be inserted<\/p>\n<pre class=\"brush:sql\">INSERT INTO EMPLOYEE_DEPT (EMP_ID,DEPT_ID,FROM_DATE,TO_DATE)\nVALUES (3,10,'2765-05-15','2900-10-15');\n<\/pre>\n<p>The output is as follows:<\/p>\n<div class=\"wp-block-image\">\n<figure class=\"aligncenter size-full\"><img decoding=\"async\" width=\"820\" height=\"310\" src=\"https:\/\/examples.javacodegeeks.com\/wp-content\/uploads\/2020\/11\/foreign_key_violated.jpg\" alt=\"Foreign key constraint violation\" class=\"wp-image-97235\" srcset=\"https:\/\/examples.javacodegeeks.com\/wp-content\/uploads\/2020\/11\/foreign_key_violated.jpg 820w, https:\/\/examples.javacodegeeks.com\/wp-content\/uploads\/2020\/11\/foreign_key_violated-300x113.jpg 300w, https:\/\/examples.javacodegeeks.com\/wp-content\/uploads\/2020\/11\/foreign_key_violated-768x290.jpg 768w\" sizes=\"(max-width: 820px) 100vw, 820px\" \/><figcaption>Foreign key constraint violation<\/figcaption><\/figure>\n<\/div>\n<p>Here the record for the DEPT_ID used is not present in the Departments table.<\/p>\n<h3 class=\"wp-block-heading\" id=\"h-5-8-insert-into-using-a-select-query\">5.8 Insert Into using a Select Query<\/h3>\n<p>If we have two identical tables or even one table which has a subset of columns from the other table, we can use the select query with the insert query.<\/p>\n<p>To select a particular record to insert<\/p>\n<pre class=\"brush:sql\"> INSERT INTO EMPLOYEES2 (EMP_ID, FIRST_NAME, LAST_NAME, BIRTH_DATE, HIRE_DATE)\nSELECT EMP_ID, FIRST_NAME, LAST_NAME, BIRTH_DATE, HIRE_DATE FROM EMPLOYEES WHERE EMP_ID =1;\n<\/pre>\n<p>If the Columns names in the two tables are identical then we can skip the column names in the Select query and use the asterisk (*) instead.<\/p>\n<pre class=\"brush:sql\">INSERT INTO EMPLOYEES2 (EMP_ID, FIRST_NAME, LAST_NAME, BIRTH_DATE, HIRE_DATE)\nSELECT * FROM EMPLOYEES WHERE EMP_ID =2;\n<\/pre>\n<p>The queries above give the output:<\/p>\n<div class=\"wp-block-image\">\n<figure class=\"aligncenter size-full\"><img decoding=\"async\" width=\"820\" height=\"649\" src=\"https:\/\/examples.javacodegeeks.com\/wp-content\/uploads\/2020\/11\/insert_into_select.jpg\" alt=\"Insert into with Select Clause\" class=\"wp-image-97236\" srcset=\"https:\/\/examples.javacodegeeks.com\/wp-content\/uploads\/2020\/11\/insert_into_select.jpg 820w, https:\/\/examples.javacodegeeks.com\/wp-content\/uploads\/2020\/11\/insert_into_select-300x237.jpg 300w, https:\/\/examples.javacodegeeks.com\/wp-content\/uploads\/2020\/11\/insert_into_select-768x608.jpg 768w\" sizes=\"(max-width: 820px) 100vw, 820px\" \/><figcaption>Insert into with Select Clause<\/figcaption><\/figure>\n<\/div>\n<h3 class=\"wp-block-heading\" id=\"h-5-9-insert-into-using-a-select-without-a-where-clause\">5.9 Insert into using a Select without a where clause<\/h3>\n<p>To insert all the records from one table to another , we can use any one of the syntaxes of the select statement from above, just without a where clause<\/p>\n<pre class=\"brush:sql\"> INSERT INTO EMPLOYEES2 (EMP_ID,FIRST_NAME,LAST_NAME,BIRTH_DATE,HIRE_DATE)\nSELECT * FROM EMPLOYEES;\n<\/pre>\n<p>The output is:<\/p>\n<div class=\"wp-block-image\">\n<figure class=\"aligncenter size-full\"><img decoding=\"async\" width=\"820\" height=\"432\" src=\"https:\/\/examples.javacodegeeks.com\/wp-content\/uploads\/2020\/11\/insert_select_all.jpg\" alt=\"Insert into with a Select Clause, no where\" class=\"wp-image-97237\" srcset=\"https:\/\/examples.javacodegeeks.com\/wp-content\/uploads\/2020\/11\/insert_select_all.jpg 820w, https:\/\/examples.javacodegeeks.com\/wp-content\/uploads\/2020\/11\/insert_select_all-300x158.jpg 300w, https:\/\/examples.javacodegeeks.com\/wp-content\/uploads\/2020\/11\/insert_select_all-768x405.jpg 768w\" sizes=\"(max-width: 820px) 100vw, 820px\" \/><figcaption>Insert into with a Select Clause, no where<\/figcaption><\/figure>\n<\/div>\n<h3 class=\"wp-block-heading\" id=\"h-5-10-insert-into-with-the-on-duplicate-key-update\">5.10 Insert into with the ON DUPLICATE KEY UPDATE<\/h3>\n<p>If we try to insert a row in a table with a primary key that already exists, we get a \u201cDuplicate entry\u201d error. This would apply to a column that has a \u201cUnique\u201d constraint as well.<\/p>\n<pre class=\"brush:sql\">INSERT INTO EMPLOYEES2 (EMP_ID,FIRST_NAME)\nVALUES (4,'Bofur');\n<\/pre>\n<p>The error shown is<\/p>\n<div class=\"wp-block-image\">\n<figure class=\"aligncenter size-full\"><img decoding=\"async\" width=\"800\" height=\"150\" src=\"https:\/\/examples.javacodegeeks.com\/wp-content\/uploads\/2020\/11\/primary_key_violation.jpg\" alt=\"Unique or Primary key violation error\" class=\"wp-image-97238\" srcset=\"https:\/\/examples.javacodegeeks.com\/wp-content\/uploads\/2020\/11\/primary_key_violation.jpg 800w, https:\/\/examples.javacodegeeks.com\/wp-content\/uploads\/2020\/11\/primary_key_violation-300x56.jpg 300w, https:\/\/examples.javacodegeeks.com\/wp-content\/uploads\/2020\/11\/primary_key_violation-768x144.jpg 768w\" sizes=\"(max-width: 800px) 100vw, 800px\" \/><figcaption>Unique or Primary key violation error<\/figcaption><\/figure>\n<\/div>\n<p>However, if we use the On DUPLICATE KEY UPDATE statement with the insertion, then the record already present in the table is updated instead. Example Query<\/p>\n<pre class=\"brush:sql\"> INSERT INTO EMPLOYEES2 (EMP_ID, FIRST_NAME)\nVALUES (4,'Smaug')\nON DUPLICATE KEY UPDATE LAST_NAME=\"The Fierce\";\n<\/pre>\n<p>The Emp_id = 4 already exists in the Employees2 table. When we mentioned, the on Duplicate key update statement, the record for the emp_id=4 is retrieved and updated i.e. the Last_Name is updated from NULL to \u201cThe Fierce\u201d in the above example.<\/p>\n<div class=\"wp-block-image\">\n<figure class=\"aligncenter size-full\"><img decoding=\"async\" width=\"820\" height=\"601\" src=\"https:\/\/examples.javacodegeeks.com\/wp-content\/uploads\/2020\/11\/insert_on_duplicate_key.jpg\" alt=\"Insert into ... on DUPLICATE KEY Update clause \" class=\"wp-image-97239\" srcset=\"https:\/\/examples.javacodegeeks.com\/wp-content\/uploads\/2020\/11\/insert_on_duplicate_key.jpg 820w, https:\/\/examples.javacodegeeks.com\/wp-content\/uploads\/2020\/11\/insert_on_duplicate_key-300x220.jpg 300w, https:\/\/examples.javacodegeeks.com\/wp-content\/uploads\/2020\/11\/insert_on_duplicate_key-768x563.jpg 768w\" sizes=\"(max-width: 820px) 100vw, 820px\" \/><figcaption>Insert into &#8230; on DUPLICATE KEY Update clause <\/figcaption><\/figure>\n<\/div>\n<h2 class=\"wp-block-heading\" id=\"h-6-summary\">6. Summary<\/h2>\n<p>In the article, we saw the most common options used with the  INSERT INTO query in MySQL. The complete documentation of the INSERT INTO Clause is available <a href=\"https:\/\/dev.mysql.com\/doc\/refman\/8.0\/en\/insert.html\" target=\"_blank\" rel=\"noreferrer noopener\">here<\/a>.<\/p>\n<h2 class=\"wp-block-heading\" id=\"h-7-download-the-source-code\">7. Download the Source Code<\/h2>\n<p>In this article, we saw examples of the Insert into Query using my MySQL RDBMS. Attached are all the queries and also the creation scripts used.<\/p>\n<div class=\"download\"><strong>Download<\/strong><br \/> You can download the full source code of this example here: <a href=\"https:\/\/examples.javacodegeeks.com\/wp-content\/uploads\/2020\/11\/SQL_INSERT_EXAMPLE_Queries.zip\"><strong>SQL Insert Query Example <\/strong><\/a><\/div>\n<p><strong>Last updated on Sept. 29th, 2021<\/strong><\/p>\n","protected":false},"excerpt":{"rendered":"<p>1. Introduction In this article, we will look at one of the Data Manipulation Language (DML) constructs or statements called Insert query using the MySQL RDBMS. 2. What is Data Manipulation Language? In SQL, Data Manipulation language consists of SQL data-change statements that modify data but not the underlying schema or database objects. The commands &hellip;<\/p>\n","protected":false},"author":232,"featured_media":1204,"comment_status":"open","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[53],"tags":[647],"class_list":["post-97227","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-sql","tag-mysql"],"yoast_head":"<!-- This site is optimized with the Yoast SEO plugin v26.5 - https:\/\/yoast.com\/wordpress\/plugins\/seo\/ -->\n<title>SQL Insert Query Example - Java Code Geeks<\/title>\n<meta name=\"description\" content=\"The commands included in the data manipulation language are: SQL Insert - add new records\/tuples in table or tables...\" \/>\n<meta name=\"robots\" content=\"index, follow, max-snippet:-1, max-image-preview:large, max-video-preview:-1\" \/>\n<link rel=\"canonical\" href=\"https:\/\/examples.javacodegeeks.com\/sql-insert-query-example\/\" \/>\n<meta property=\"og:locale\" content=\"en_US\" \/>\n<meta property=\"og:type\" content=\"article\" \/>\n<meta property=\"og:title\" content=\"SQL Insert Query Example - Java Code Geeks\" \/>\n<meta property=\"og:description\" content=\"The commands included in the data manipulation language are: SQL Insert - add new records\/tuples in table or tables...\" \/>\n<meta property=\"og:url\" content=\"https:\/\/examples.javacodegeeks.com\/sql-insert-query-example\/\" \/>\n<meta property=\"og:site_name\" content=\"Examples Java Code Geeks\" \/>\n<meta property=\"article:publisher\" content=\"https:\/\/www.facebook.com\/javacodegeeks\" \/>\n<meta property=\"article:published_time\" content=\"2020-11-24T09:00:00+00:00\" \/>\n<meta property=\"article:modified_time\" content=\"2021-09-29T07:14:11+00:00\" \/>\n<meta property=\"og:image\" content=\"https:\/\/examples.javacodegeeks.com\/wp-content\/uploads\/2012\/12\/java-logo.jpg\" \/>\n\t<meta property=\"og:image:width\" content=\"150\" \/>\n\t<meta property=\"og:image:height\" content=\"150\" \/>\n\t<meta property=\"og:image:type\" content=\"image\/jpeg\" \/>\n<meta name=\"author\" content=\"Reshma Sathe\" \/>\n<meta name=\"twitter:card\" content=\"summary_large_image\" \/>\n<meta name=\"twitter:creator\" content=\"@javacodegeeks\" \/>\n<meta name=\"twitter:site\" content=\"@javacodegeeks\" \/>\n<meta name=\"twitter:label1\" content=\"Written by\" \/>\n\t<meta name=\"twitter:data1\" content=\"Reshma Sathe\" \/>\n\t<meta name=\"twitter:label2\" content=\"Est. reading time\" \/>\n\t<meta name=\"twitter:data2\" content=\"9 minutes\" \/>\n<script type=\"application\/ld+json\" class=\"yoast-schema-graph\">{\"@context\":\"https:\/\/schema.org\",\"@graph\":[{\"@type\":\"Article\",\"@id\":\"https:\/\/examples.javacodegeeks.com\/sql-insert-query-example\/#article\",\"isPartOf\":{\"@id\":\"https:\/\/examples.javacodegeeks.com\/sql-insert-query-example\/\"},\"author\":{\"name\":\"Reshma Sathe\",\"@id\":\"https:\/\/examples.javacodegeeks.com\/#\/schema\/person\/079aa9a12c7b8ebea3391ebeb6036a74\"},\"headline\":\"SQL Insert Query Example\",\"datePublished\":\"2020-11-24T09:00:00+00:00\",\"dateModified\":\"2021-09-29T07:14:11+00:00\",\"mainEntityOfPage\":{\"@id\":\"https:\/\/examples.javacodegeeks.com\/sql-insert-query-example\/\"},\"wordCount\":1252,\"commentCount\":0,\"publisher\":{\"@id\":\"https:\/\/examples.javacodegeeks.com\/#organization\"},\"image\":{\"@id\":\"https:\/\/examples.javacodegeeks.com\/sql-insert-query-example\/#primaryimage\"},\"thumbnailUrl\":\"https:\/\/examples.javacodegeeks.com\/wp-content\/uploads\/2012\/12\/java-logo.jpg\",\"keywords\":[\"mysql\"],\"articleSection\":[\"sql\"],\"inLanguage\":\"en-US\",\"potentialAction\":[{\"@type\":\"CommentAction\",\"name\":\"Comment\",\"target\":[\"https:\/\/examples.javacodegeeks.com\/sql-insert-query-example\/#respond\"]}]},{\"@type\":\"WebPage\",\"@id\":\"https:\/\/examples.javacodegeeks.com\/sql-insert-query-example\/\",\"url\":\"https:\/\/examples.javacodegeeks.com\/sql-insert-query-example\/\",\"name\":\"SQL Insert Query Example - Java Code Geeks\",\"isPartOf\":{\"@id\":\"https:\/\/examples.javacodegeeks.com\/#website\"},\"primaryImageOfPage\":{\"@id\":\"https:\/\/examples.javacodegeeks.com\/sql-insert-query-example\/#primaryimage\"},\"image\":{\"@id\":\"https:\/\/examples.javacodegeeks.com\/sql-insert-query-example\/#primaryimage\"},\"thumbnailUrl\":\"https:\/\/examples.javacodegeeks.com\/wp-content\/uploads\/2012\/12\/java-logo.jpg\",\"datePublished\":\"2020-11-24T09:00:00+00:00\",\"dateModified\":\"2021-09-29T07:14:11+00:00\",\"description\":\"The commands included in the data manipulation language are: SQL Insert - add new records\/tuples in table or tables...\",\"breadcrumb\":{\"@id\":\"https:\/\/examples.javacodegeeks.com\/sql-insert-query-example\/#breadcrumb\"},\"inLanguage\":\"en-US\",\"potentialAction\":[{\"@type\":\"ReadAction\",\"target\":[\"https:\/\/examples.javacodegeeks.com\/sql-insert-query-example\/\"]}]},{\"@type\":\"ImageObject\",\"inLanguage\":\"en-US\",\"@id\":\"https:\/\/examples.javacodegeeks.com\/sql-insert-query-example\/#primaryimage\",\"url\":\"https:\/\/examples.javacodegeeks.com\/wp-content\/uploads\/2012\/12\/java-logo.jpg\",\"contentUrl\":\"https:\/\/examples.javacodegeeks.com\/wp-content\/uploads\/2012\/12\/java-logo.jpg\",\"width\":150,\"height\":150,\"caption\":\"Bipartite Graph\"},{\"@type\":\"BreadcrumbList\",\"@id\":\"https:\/\/examples.javacodegeeks.com\/sql-insert-query-example\/#breadcrumb\",\"itemListElement\":[{\"@type\":\"ListItem\",\"position\":1,\"name\":\"Home\",\"item\":\"https:\/\/examples.javacodegeeks.com\/\"},{\"@type\":\"ListItem\",\"position\":2,\"name\":\"Java Development\",\"item\":\"https:\/\/examples.javacodegeeks.com\/category\/java-development\/\"},{\"@type\":\"ListItem\",\"position\":3,\"name\":\"Core Java\",\"item\":\"https:\/\/examples.javacodegeeks.com\/category\/java-development\/core-java\/\"},{\"@type\":\"ListItem\",\"position\":4,\"name\":\"sql\",\"item\":\"https:\/\/examples.javacodegeeks.com\/category\/java-development\/core-java\/sql\/\"},{\"@type\":\"ListItem\",\"position\":5,\"name\":\"SQL Insert Query Example\"}]},{\"@type\":\"WebSite\",\"@id\":\"https:\/\/examples.javacodegeeks.com\/#website\",\"url\":\"https:\/\/examples.javacodegeeks.com\/\",\"name\":\"Java Code Geeks\",\"description\":\"Java Examples and Code Snippets\",\"publisher\":{\"@id\":\"https:\/\/examples.javacodegeeks.com\/#organization\"},\"alternateName\":\"JCG\",\"potentialAction\":[{\"@type\":\"SearchAction\",\"target\":{\"@type\":\"EntryPoint\",\"urlTemplate\":\"https:\/\/examples.javacodegeeks.com\/?s={search_term_string}\"},\"query-input\":{\"@type\":\"PropertyValueSpecification\",\"valueRequired\":true,\"valueName\":\"search_term_string\"}}],\"inLanguage\":\"en-US\"},{\"@type\":\"Organization\",\"@id\":\"https:\/\/examples.javacodegeeks.com\/#organization\",\"name\":\"Exelixis Media P.C.\",\"url\":\"https:\/\/examples.javacodegeeks.com\/\",\"logo\":{\"@type\":\"ImageObject\",\"inLanguage\":\"en-US\",\"@id\":\"https:\/\/examples.javacodegeeks.com\/#\/schema\/logo\/image\/\",\"url\":\"https:\/\/examples.javacodegeeks.com\/wp-content\/uploads\/2022\/06\/exelixis-logo.png\",\"contentUrl\":\"https:\/\/examples.javacodegeeks.com\/wp-content\/uploads\/2022\/06\/exelixis-logo.png\",\"width\":864,\"height\":246,\"caption\":\"Exelixis Media P.C.\"},\"image\":{\"@id\":\"https:\/\/examples.javacodegeeks.com\/#\/schema\/logo\/image\/\"},\"sameAs\":[\"https:\/\/www.facebook.com\/javacodegeeks\",\"https:\/\/x.com\/javacodegeeks\"]},{\"@type\":\"Person\",\"@id\":\"https:\/\/examples.javacodegeeks.com\/#\/schema\/person\/079aa9a12c7b8ebea3391ebeb6036a74\",\"name\":\"Reshma Sathe\",\"image\":{\"@type\":\"ImageObject\",\"inLanguage\":\"en-US\",\"@id\":\"https:\/\/examples.javacodegeeks.com\/#\/schema\/person\/image\/\",\"url\":\"https:\/\/examples.javacodegeeks.com\/wp-content\/uploads\/2020\/08\/reshma_sathe-96x96.png\",\"contentUrl\":\"https:\/\/examples.javacodegeeks.com\/wp-content\/uploads\/2020\/08\/reshma_sathe-96x96.png\",\"caption\":\"Reshma Sathe\"},\"description\":\"I am a recent Master of Computer Science degree graduate from the University Of Illinois at Urbana-Champaign.I have previously worked as a Software Engineer with projects ranging from production support to programming and software engineering.I am currently working on self-driven projects in Java, Python and Angular and also exploring other frontend and backend technologies.\",\"sameAs\":[\"www.linkedin.com\/in\/reshma-sathe\"],\"url\":\"https:\/\/examples.javacodegeeks.com\/author\/reshma-sathe\/\"}]}<\/script>\n<!-- \/ Yoast SEO plugin. -->","yoast_head_json":{"title":"SQL Insert Query Example - Java Code Geeks","description":"The commands included in the data manipulation language are: SQL Insert - add new records\/tuples in table or tables...","robots":{"index":"index","follow":"follow","max-snippet":"max-snippet:-1","max-image-preview":"max-image-preview:large","max-video-preview":"max-video-preview:-1"},"canonical":"https:\/\/examples.javacodegeeks.com\/sql-insert-query-example\/","og_locale":"en_US","og_type":"article","og_title":"SQL Insert Query Example - Java Code Geeks","og_description":"The commands included in the data manipulation language are: SQL Insert - add new records\/tuples in table or tables...","og_url":"https:\/\/examples.javacodegeeks.com\/sql-insert-query-example\/","og_site_name":"Examples Java Code Geeks","article_publisher":"https:\/\/www.facebook.com\/javacodegeeks","article_published_time":"2020-11-24T09:00:00+00:00","article_modified_time":"2021-09-29T07:14:11+00:00","og_image":[{"width":150,"height":150,"url":"https:\/\/examples.javacodegeeks.com\/wp-content\/uploads\/2012\/12\/java-logo.jpg","type":"image\/jpeg"}],"author":"Reshma Sathe","twitter_card":"summary_large_image","twitter_creator":"@javacodegeeks","twitter_site":"@javacodegeeks","twitter_misc":{"Written by":"Reshma Sathe","Est. reading time":"9 minutes"},"schema":{"@context":"https:\/\/schema.org","@graph":[{"@type":"Article","@id":"https:\/\/examples.javacodegeeks.com\/sql-insert-query-example\/#article","isPartOf":{"@id":"https:\/\/examples.javacodegeeks.com\/sql-insert-query-example\/"},"author":{"name":"Reshma Sathe","@id":"https:\/\/examples.javacodegeeks.com\/#\/schema\/person\/079aa9a12c7b8ebea3391ebeb6036a74"},"headline":"SQL Insert Query Example","datePublished":"2020-11-24T09:00:00+00:00","dateModified":"2021-09-29T07:14:11+00:00","mainEntityOfPage":{"@id":"https:\/\/examples.javacodegeeks.com\/sql-insert-query-example\/"},"wordCount":1252,"commentCount":0,"publisher":{"@id":"https:\/\/examples.javacodegeeks.com\/#organization"},"image":{"@id":"https:\/\/examples.javacodegeeks.com\/sql-insert-query-example\/#primaryimage"},"thumbnailUrl":"https:\/\/examples.javacodegeeks.com\/wp-content\/uploads\/2012\/12\/java-logo.jpg","keywords":["mysql"],"articleSection":["sql"],"inLanguage":"en-US","potentialAction":[{"@type":"CommentAction","name":"Comment","target":["https:\/\/examples.javacodegeeks.com\/sql-insert-query-example\/#respond"]}]},{"@type":"WebPage","@id":"https:\/\/examples.javacodegeeks.com\/sql-insert-query-example\/","url":"https:\/\/examples.javacodegeeks.com\/sql-insert-query-example\/","name":"SQL Insert Query Example - Java Code Geeks","isPartOf":{"@id":"https:\/\/examples.javacodegeeks.com\/#website"},"primaryImageOfPage":{"@id":"https:\/\/examples.javacodegeeks.com\/sql-insert-query-example\/#primaryimage"},"image":{"@id":"https:\/\/examples.javacodegeeks.com\/sql-insert-query-example\/#primaryimage"},"thumbnailUrl":"https:\/\/examples.javacodegeeks.com\/wp-content\/uploads\/2012\/12\/java-logo.jpg","datePublished":"2020-11-24T09:00:00+00:00","dateModified":"2021-09-29T07:14:11+00:00","description":"The commands included in the data manipulation language are: SQL Insert - add new records\/tuples in table or tables...","breadcrumb":{"@id":"https:\/\/examples.javacodegeeks.com\/sql-insert-query-example\/#breadcrumb"},"inLanguage":"en-US","potentialAction":[{"@type":"ReadAction","target":["https:\/\/examples.javacodegeeks.com\/sql-insert-query-example\/"]}]},{"@type":"ImageObject","inLanguage":"en-US","@id":"https:\/\/examples.javacodegeeks.com\/sql-insert-query-example\/#primaryimage","url":"https:\/\/examples.javacodegeeks.com\/wp-content\/uploads\/2012\/12\/java-logo.jpg","contentUrl":"https:\/\/examples.javacodegeeks.com\/wp-content\/uploads\/2012\/12\/java-logo.jpg","width":150,"height":150,"caption":"Bipartite Graph"},{"@type":"BreadcrumbList","@id":"https:\/\/examples.javacodegeeks.com\/sql-insert-query-example\/#breadcrumb","itemListElement":[{"@type":"ListItem","position":1,"name":"Home","item":"https:\/\/examples.javacodegeeks.com\/"},{"@type":"ListItem","position":2,"name":"Java Development","item":"https:\/\/examples.javacodegeeks.com\/category\/java-development\/"},{"@type":"ListItem","position":3,"name":"Core Java","item":"https:\/\/examples.javacodegeeks.com\/category\/java-development\/core-java\/"},{"@type":"ListItem","position":4,"name":"sql","item":"https:\/\/examples.javacodegeeks.com\/category\/java-development\/core-java\/sql\/"},{"@type":"ListItem","position":5,"name":"SQL Insert Query Example"}]},{"@type":"WebSite","@id":"https:\/\/examples.javacodegeeks.com\/#website","url":"https:\/\/examples.javacodegeeks.com\/","name":"Java Code Geeks","description":"Java Examples and Code Snippets","publisher":{"@id":"https:\/\/examples.javacodegeeks.com\/#organization"},"alternateName":"JCG","potentialAction":[{"@type":"SearchAction","target":{"@type":"EntryPoint","urlTemplate":"https:\/\/examples.javacodegeeks.com\/?s={search_term_string}"},"query-input":{"@type":"PropertyValueSpecification","valueRequired":true,"valueName":"search_term_string"}}],"inLanguage":"en-US"},{"@type":"Organization","@id":"https:\/\/examples.javacodegeeks.com\/#organization","name":"Exelixis Media P.C.","url":"https:\/\/examples.javacodegeeks.com\/","logo":{"@type":"ImageObject","inLanguage":"en-US","@id":"https:\/\/examples.javacodegeeks.com\/#\/schema\/logo\/image\/","url":"https:\/\/examples.javacodegeeks.com\/wp-content\/uploads\/2022\/06\/exelixis-logo.png","contentUrl":"https:\/\/examples.javacodegeeks.com\/wp-content\/uploads\/2022\/06\/exelixis-logo.png","width":864,"height":246,"caption":"Exelixis Media P.C."},"image":{"@id":"https:\/\/examples.javacodegeeks.com\/#\/schema\/logo\/image\/"},"sameAs":["https:\/\/www.facebook.com\/javacodegeeks","https:\/\/x.com\/javacodegeeks"]},{"@type":"Person","@id":"https:\/\/examples.javacodegeeks.com\/#\/schema\/person\/079aa9a12c7b8ebea3391ebeb6036a74","name":"Reshma Sathe","image":{"@type":"ImageObject","inLanguage":"en-US","@id":"https:\/\/examples.javacodegeeks.com\/#\/schema\/person\/image\/","url":"https:\/\/examples.javacodegeeks.com\/wp-content\/uploads\/2020\/08\/reshma_sathe-96x96.png","contentUrl":"https:\/\/examples.javacodegeeks.com\/wp-content\/uploads\/2020\/08\/reshma_sathe-96x96.png","caption":"Reshma Sathe"},"description":"I am a recent Master of Computer Science degree graduate from the University Of Illinois at Urbana-Champaign.I have previously worked as a Software Engineer with projects ranging from production support to programming and software engineering.I am currently working on self-driven projects in Java, Python and Angular and also exploring other frontend and backend technologies.","sameAs":["www.linkedin.com\/in\/reshma-sathe"],"url":"https:\/\/examples.javacodegeeks.com\/author\/reshma-sathe\/"}]}},"_links":{"self":[{"href":"https:\/\/examples.javacodegeeks.com\/wp-json\/wp\/v2\/posts\/97227","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/examples.javacodegeeks.com\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/examples.javacodegeeks.com\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/examples.javacodegeeks.com\/wp-json\/wp\/v2\/users\/232"}],"replies":[{"embeddable":true,"href":"https:\/\/examples.javacodegeeks.com\/wp-json\/wp\/v2\/comments?post=97227"}],"version-history":[{"count":0,"href":"https:\/\/examples.javacodegeeks.com\/wp-json\/wp\/v2\/posts\/97227\/revisions"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/examples.javacodegeeks.com\/wp-json\/wp\/v2\/media\/1204"}],"wp:attachment":[{"href":"https:\/\/examples.javacodegeeks.com\/wp-json\/wp\/v2\/media?parent=97227"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/examples.javacodegeeks.com\/wp-json\/wp\/v2\/categories?post=97227"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/examples.javacodegeeks.com\/wp-json\/wp\/v2\/tags?post=97227"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}