A SQL INSERT INTO Statement
In SQL, the INSERT INTO statement is used to insert new rows into a database table.
It allows you to add data to a table, specifying the values for each column in the table.
Let’s create a simple database table called Students.
CREATE TABLE Students (
StudentID INT PRIMARY KEY,
FirstName VARCHAR(55),
LastName VARCHAR(55),
Age INT
);
Now, let’s insert or add some data into the “Students” table using the INSERT INTO statement:
1. Example of an INSERT INTO statement:
You can use the below SQL query to insert a single row of data into the Students table.
INSERT INTO Students (StudentID, FirstName, LastName, Age)
VALUES (1, ‘John’, ‘Pandit’, 23);
This query inserts a new student with a StudentID of 1, FirstName ‘John’, LastName ‘Pandit’, and Age 23 into the Students table.
2. Example of an INSERT INTO statement:
You can also insert or add multiple rows of data in a single INSERT INTO statement.
INSERT INTO Students (StudentID, FirstName, LastName, Age)
VALUES
(2, ‘Alice’, ‘Verma’, 24),
(3, ‘Bob’, ‘Mahi’, 25),
(4, ‘Emily’, ‘Sharma’, 26);
This query inserts three new students into the Students table at once.
3. Example of an INSERT INTO statement:
Inserting data from another table.
You can also insert data into a table from another table (table structure should be the same) by using a SELECT statement. For example, let’s say you have another table called NewStudents with the same structure and you want to copy data from it to the Students new created table:
INSERT INTO Students (StudentID, FirstName, LastName, Age)
SELECT StudentID, FirstName, LastName, Age
FROM NewStudents;
This query inserts data into the Students table by selecting and copying records from the NewStudents table.
Conclusion
Please be aware that you must have the proper permissions and that the column data types and order must match the database’s structure in order to insert data into a table.
To preserve data integrity and prevent data duplication or errors, you should also exercise caution when inputting data.