Chapter 4
Chapter 4
sql
Copy
CREATE TABLE Students (
ID INT PRIMARY KEY,
Name VARCHAR(50),
Age INT,
Grade CHAR(1)
);
sql
Copy
ALTER TABLE Students ADD Email VARCHAR(100); -- Adds a new column
ALTER TABLE Students MODIFY Age FLOAT; -- Modifies column datatype
ALTER TABLE Students DROP COLUMN Grade; -- Deletes a column
sql
Copy
TRUNCATE TABLE Students;
sql
Copy
INSERT INTO Students (ID, Name, Age, Grade) VALUES (1, 'Alice', 18, 'A');
sql
Copy
UPDATE Students SET Age = 19 WHERE ID = 1;
sql
Copy
DELETE FROM Students WHERE ID = 1;
Type Description
INNER JOIN Returns matching records from both tables.
Returns all records from the left table and matching records from the right
LEFT JOIN
table.
RIGHT Returns all records from the right table and matching records from the left
JOIN table.
FULL JOIN Returns all records from both tables, filling gaps with NULL.
sql
Copy
SELECT Name FROM Students WHERE Age > (SELECT AVG(Age) FROM Students);
Constraint Description
PRIMARY KEY Ensures uniqueness for each record.
FOREIGN KEY Establishes relationships between tables.
NOT NULL Ensures a column cannot have NULL values.
UNIQUE Ensures all values in a column are unique.
CHECK Restricts values in a column.
DEFAULT Assigns a default value if none is provided.
Example of Constraints
sql
Copy
CREATE TABLE Students (
ID INT PRIMARY KEY,
Name VARCHAR(50) NOT NULL,
Age INT CHECK (Age >= 18),
Grade CHAR(1) DEFAULT 'B'
);
ACID Properties:
Example of a Transaction
sql
Copy
START TRANSACTION;
UPDATE Accounts SET Balance = Balance - 500 WHERE AccountID = 1;
UPDATE Accounts SET Balance = Balance + 500 WHERE AccountID = 2;
COMMIT; -- Finalizes the transaction
Summary of Chapter 4
SQL is used to interact with databases.
DDL Commands (CREATE, ALTER, DROP) define structure.
DML Commands (INSERT, UPDATE, DELETE) modify data.
DQL Commands (SELECT, WHERE, ORDER BY) retrieve data.
Functions (Aggregate, String) help in data manipulation.
Joins combine data from multiple tables.
Subqueries allow nested queries.
Constraints ensure data integrity.
Transactions & ACID properties maintain database reliability.