Lecture Week 2-Databases
Lecture Week 2-Databases
Databases-Week 2
SQL Database Management
1 2 3
• CREATE • ALTER TABLE: • DROP TABLE:
TABLE: Create a Modify an Delete an
new table with existing table entire table.
specified (add/remove
columns. columns).
Managing Columns in SQL Tables
• ADD: Add a new column to • DROP COLUMN: Remove an • ALTER COLUMN: Modify an
a table. existing column from a table. existing column (e.g., change
its name or data type).
Inserting and Modifying Data in SQL
SUMMARY
• VARCHAR(n): Variable-length string with a
maximum of 'n' characters.
• INT: Integer values. (4 bytes 4,294,967,295)
• BIGINT: Large integer values. (8 bytes
18,446,744,073,709,551,615)
• REAL : float data when memory efficiency is a
SQL Data concern (4 bytes 7 digits of precision)
INSERT Command
• Purpose: Adds new rows of data into a table.
• Usage: Inserts values into specified columns of a table.
UPDATE Command
DELETE Command
• Purpose: Merges data from two tables, usually to perform an `INSERT`, `UPDATE`,
or `DELETE` based on conditions.
• Usage: Useful for synchronizing two datasets by inserting new records or updating
existing ones.
MERGE INTO bonuses AS target
USING employee AS source
ON (target.id = source.id)
WHEN MATCHED THEN UPDATE SET target.bonus = target.bonus +
source.salary*.01
DELETE WHERE (source.salary > 8000)
WHEN NOT MATCHED THEN
INSERT (id, username, bonuses) VALUES (source.id, source.username,
source.salary*.01);.
-- No need for INSERT INTO as MERGE already knows which table to use.
SQL Code
CREATE DATABASE Students1;
USE Students1; ALTER TABLE StudentsInfo ADD BloodGrp
CREATE TABLE StudentsInfo varchar(8000);
( ALTER TABLE StudentsInfo DROP COLUMN
StudentsID int, BloodGrp;
StudentsName varchar(8000), ALTER TABLE StudentsInfo ADD DOB DATE;
StudentsParent varchar(8000),
PhoneNumber bigint, ALTER TABLE StudentsInfo ALTER COLUMN DOB
StudentsAddress datetime;
varchar(8000), ALTER TABLE StudentsInfo DROP COLUMN DOB;
StudentsCountry
INSERT INTO StudentsInfo VALUES
varchar(8000),
('20241000','Adel','Zeyad','314577898','Shafa
StudentsCity varChar(8000)
Badran Al Bahrea Circle', 'Jordan', 'Amman');
);
TRUNCATE TABLE StudentsInfo;-- delete all
rows, only the data is removed
• Primary Key
commonly
• Purpose: It ensures that each record in the table can
be uniquely identified. For example, a `CustomerID` in
a customers table.
used in
• Foreign Key:
• Definition: A foreign key is a field (or a collection of
fields) in one table that uniquely identifies a row of
keys have multiple unique keys, and they can accept NULLs,
but each NULL is considered distinct.
• Purpose: It prevents duplicate values in specific
commonly columns.
• StudentID is the Primary Key (must be unique and non-null).
• Email and PhoneNumber are Unique Keys — no two
used in students can have the same email or phone number, but they
can be null.
s
`Users` table is unique, you can apply a `UNIQUE`
constraint.