What is INSERT INTO command in MySQL?
If we want to insert some data into the table we can use the INSERT INTO command to insert new records.
We can insert multiple or one records at a time.
The syntax for MySQL INSERT INTO command is as follows.
INSERT INTO schema.table_name (column_name1, column_name2, column_name3, …) VALUES (value1, value2, value3, …);
If values need to be inserted in the order of the database columns then we can skip the column names, so the syntax can be updated as follows.
INSERT INTO schema.table_name VALUES (value1, value2, value3, …);
Syntax to insert multiple values at once.
INSERT INTO schema.table_name (column_name1, column_name2, column_name3, …)
VALUES (value1, value2, value3, …), (value1, value2, value3, …), (value1, value2, value3, …), …;
We will see the example to insert into the student table we have created in MySQL SELECT Statement.
We will insert one row by using the query as follows.
insert into students (roll_num, name, marks, class, gender) values(18, “PJS”, 432, 3, “F”);
Query without column names:
insert into students values(19, “PJS”, 432, 3, “F”);
Query to insert multiple values at once:
We will insert 3 records in the table at once. We can also skip the column names as in the above query if the sequence of the insert values is the same as the table column.
insert into students (roll_num, name, marks, class, gender)
values(20, “KJN”, 422, 3, “F”), (21, “LLS”, 352, 3, “F”),(22, “PJM”, 352, 3, “M”);
We can also insert some column values as required. The query for this is as follows.
insert into students (roll_num, name) values(23, “KJN”);
Here we have inserted roll_num which is the Primary key and name. If the column value is not marked as NOT NULL while creating the table, we can skip that column value while inserting any row data in the table.
If that column value is mandatory, we will get an error if we try to skip that value.
We will make Marks as NOT NULL and will try to insert the data.
Before making any column as NN, make sure the table does not have any records where that column value is null. If yes then either delete that record or update the value else we will get an error as follows while updating the table column settings.
To update the column settings, Go to the table settings as follows.
Select the NN checkbox for the marks column and then click on apply.
Once the column setting is successfully updated we can try to rerun the same query with roll_num and name, without marks.
insert into students (roll_num, name) values(23, “KJN”);
We will get an error if we try to run the above query as “Error Code: 1364. Field ‘marks’ doesn’t have a default value”