Day 6: INSERT Statement
Introduction:
The
INSERTstatement is used to add new rows of data to a table. This is fundamental for populating your database with meaningful information.
Key Concepts:
Inserting Single Rows: Adding one row of data at a time.
Inserting Multiple Rows: Adding multiple rows of data in a single statement.
Inserting Data with Default Values: Using default values for certain columns.
SQL Commands and Examples:
Inserting a Single Row:
The basic syntax for inserting a single row into a table.
-- Insert a single row of data into the Courses table
INSERT INTO Courses (CourseID, CourseName, Credits)
VALUES (101, 'Introduction to SQL', 3);
Inserting Multiple Rows:
Adding multiple rows in a single
INSERTstatement can be more efficient.
-- Insert multiple rows of data into the Courses table
INSERT INTO Courses (CourseID, CourseName, Credits)
VALUES
(102, 'Advanced SQL', 4),
(103, 'Database Management Systems', 3);
Inserting Data with Default Values:
If a column has a default value, you can omit it from the
INSERTstatement.
-- Assuming Credits column has a default value of 3
INSERT INTO Courses (CourseID, CourseName)
VALUES (104, 'Data Structures');
Practice Exercise:
Create a table named Students with the following columns:
StudentID(INT, Primary Key)FirstName(VARCHAR)LastName(VARCHAR)Age(INT)
Insert a single student into the Students table.
Insert multiple students into the Students table.
Assume
Agehas a default value of 20 and insert a student without specifying the age.
-- Create the Students table
CREATE TABLE Students (
StudentID INT PRIMARY KEY,
FirstName VARCHAR(255),
LastName VARCHAR(255),
Age INT DEFAULT 20
);
-- Insert a single student
INSERT INTO Students (StudentID, FirstName, LastName, Age)
VALUES (1, 'Alice', 'Johnson', 22);
-- Insert multiple students
INSERT INTO Students (StudentID, FirstName, LastName, Age)
VALUES
(2, 'Bob', 'Smith', 21),
(3, 'Charlie', 'Brown', 23);
-- Insert a student with default age
INSERT INTO Students (StudentID, FirstName, LastName)
VALUES (4, 'Daisy', 'Miller');
Inserting data effectively is vital for database management.
0 Comments