Lesson Plan: SQL Data Modification and Table Management
Lesson Objectives
[Link] the end of this lesson, students will be able to:
[Link] individual values into a table.
[Link] an existing table structure.
[Link] a database or a table.
[Link] existing records in a table.
Step 1: Inserting Individual Values into a Table
Syntax:
INSERT INTO table_name (column1, column2, ...)
VALUES (value1, value2, ...);
Explanation:
table_name is the target table.
(column1, column2, ...) specifies columns.
VALUES (...) provides values for each column.
Example: Insert a New Student
Example code:
INSERT INTO Students (StudentID, Name, Age, Major)
VALUES (2, 'Bob Williams', 22, 'Mathematics');
🔹 Alternative: Insert Without Column Names (only if inserting values for all columns)
Example code:
INSERT INTO Students
VALUES (3, 'Charlie Brown', 21, 'Physics');
Task 1
🔹 Insert two new records into the Books table with BookID, Title, Author, and PublishedYear.
Step 2: Altering a Table
What if we need to modify a table structure after creation?
🔹 We use ALTER TABLE to:
[Link] a new column
[Link] column type
[Link] a column
Adding a New Column:
Example code :
ALTER TABLE Students
ADD Email VARCHAR(100);
Explanation:
Adds an Email column to store student emails.
Modifying a Column:
Example code :
ALTER TABLE Students
MODIFY COLUMN Age INT NOT NULL;
Explanation:
Changes Age column to ensure values cannot be NULL.
Dropping a Column
Example code:
ALTER TABLE Students
DROP COLUMN Major;
Explanation:
Removes Major column permanently.
Task 2
🔹 Add a column Genre to the Books table.
Step 3: Dropping a Database
This action permanently deletes a database. Use with caution!
SQL Code to Drop a Database
Example code:
DROP DATABASE College;
Explanation:
Deletes the College database and all its tables.
Cannot be undone, so use wisely.
Task 3
🔹 Create a database named SchoolDB, then drop it.
Step 4: Dropping a Table
This permanently deletes a table and its data.
SQL Code to Drop a Table
Example code:
DROP TABLE Students;
Explanation:
Removes the Students table and all its records.
Task 4
🔹 Create a table named Teachers, then drop it.
Step 5: Updating Records
We use UPDATE to modify existing data in a table.
Syntax:
UPDATE table_name
SET column1 = value1, column2 = value2
WHERE condition;
Important Notes:
Always use WHERE to avoid updating all records.
If WHERE is not used, every row in the table gets updated.
Example: Update a Student’s Age
Example code:
UPDATE Students
SET Age = 23
WHERE StudentID = 2;
Explanation:
Changes Bob Williams’ age to 23.
Updating Multiple Columns
Example code:
UPDATE Students
SET Name = 'Robert Williams', Age = 24
WHERE StudentID = 2;
Explanation:
Updates both Name and Age for StudentID = 2.
Task 5
🔹 Update the PublishedYear of a specific book in the Books table.