SQL Insert Data
How to Insert Data in SQL?
The INSERT INTO statement used to add new records (rows) to a table.
It allows you to specify the values to be inserted into each column of the table.
Syntax:
Let's see the syntax how you can insert data in a table.
INSERT INTO table_name (column1, column2, column3, ...)
VALUES (value1, value2, value3, ...);
- table_name: The name of the table where you want to insert data.
- column1, column2, column3, ...: The columns in the table where you want to insert data.
- VALUES: The keyword indicating the values that you want to insert.
- value1, value2, value3, ...: The actual values you want to insert into the corresponding columns.
Example:
Let's assume we have a table named students with columns student_id, first_name, last_name, and age.
Example 1: Insert a Single Record
INSERT INTO students (student_id, first_name, last_name, age)
VALUES (1, 'John', 'Doe', 20);
This inserts a new student with the specified values into the students table.
Example 2: Insert Multiple Records
INSERT INTO students (student_id, first_name, last_name, age)
VALUES
(2, 'Jane', 'Smith', 22),
(3, 'Bob', 'Johnson', 21),
(4, 'Alice', 'Williams', 19);
This inserts multiple students into the students table in a single INSERT INTO statement.
Example 3: Omitting the Column Names
If you are inserting values for all columns and in the order they are defined in the table, you can omit the column names.
INSERT INTO students
VALUES (5, 'Eva', 'Anderson', 23);
In this case, make sure the values are provided in the same order as the columns in the table.
Example 4: Auto-incrementing Primary Key
Assuming student_id is an auto-incrementing primary key:
INSERT INTO students (first_name, last_name, age)
VALUES ('Michael', 'Brown', 24);
The database will automatically generate a unique student_id for this record.
Tips:
- Make sure the values match the data types and constraints defined for each column.
- If a column is auto-incremented or has a default value, you may not need to provide a value for that column in the INSERT INTO statement.
- Test your INSERT INTO statements with a subsequent SELECT statement to verify that the data has been inserted correctly.