What is SQL INSERT Command?

The SQL Insert command is a SQL DML (Data Manipulation Language) command used to insert data into any table in the database. If you wish, you can add data to the tables in a very simple way via phpMyAdmin. But you cannot always use this method, for example in a web project you cannot manually add the information in the user registration form to the database.

Using SQL INSERT Command

SQL Insert command has a simple usage like other SQL commands. There are basically two uses.

First Usage

INSERT INTO table_name VALUES (value1,value2,value3, )

With this usage method, data is added to the tables we created before, in the same way as the order of the columns in the table.

Now let’s write our codes, for this, let’s look at the structure of our table named students that we created in the previous blog posts. If you wish, you can reach the lesson that we created our table named students from here.

Let’s take a look at the general structure of our table.

Table Structure

Now we add the data in the same way as the order of the columns in our table named students.

INSERT INTO students VALUES ('Baransel', 'Arslan', 88.9, 3, '15.03.2022')

As you can see, we are adding the data in the same way as the column order in the table. Otherwise, we will get error. The point we need to pay attention to here is that we write the characteristic values in single quotes. Another point to note is; We did not add the student_id column because we previously stated that we want to add the student_id column automatically when creating the table, with the IDENTITY statement. You can access that article here if you wish.

We saw the first use of the SQL insert command. Now let’s look at the second use case. The second use is more used than the first use, and it is safer to use.

Second Usage

INSERT INTO table_name (column1,column2,column3, ) VALUES(value1,value2,value3, )

There is another point that we should pay attention to here. Column values and the order of the values we want to add must be the same. We will not add any data to the date column here.

INSERT INTO students (student_name, student_surname, student_average_grade, class_no) VALUES ('Baransel', 'Arslan', 88.9, 3)

Thus, we left the date column blank. However, you cannot leave the primary key columns blank, for example, since the class_no column is the primary key, you will get an error when you leave it blank.