LO1: MS SQL server
Databases-Week 2
SQL Database Management
• CREATE DATABASE: • DROP DATABASE: • USE: Selects the
Creates a new Deletes an existing database to work with.
database. database.
Creating and Modifying Tables in SQL
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
• INSERT INTO: INSERT • UPDATE: UPDATE • DELETE FROM:
NEW ROWS INTO A EXISTING RECORDS. DELETE RECORDS
TABLE. FROM A TABLE.
Database Table Column Row
CREATE DATABASE CREATE ADD INSERT INTO
TABLE VALUES
DROP DATABASE DROP TABLE DROP COLUMN DELETE
FROM
WHERE
USE ALTER ALTER COLUMN UPDATE
TABLE SET
WHERE
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)
Types • FLOAT: float data higher precision is required (4
or 8 bytes . 8 bytes gives15 digits of precision)
Explained • Decimal(a,b): up to a digits in total, with b
digits after the decimal point. Used for exact
values. Perfect for when precision matters, like
in financial data or scientific calculations (a>b)
• DATE: Date in 'YYYY-MM-DD' format.
• DATETIME: Date and time in 'YYYY-MM-DD
HH:MM:SS' format.
Data •Data Manipulation • USE Command
Commands (DML) in
Manipulati SQL are used to insert, • Purpose: Selects a
specific database to
update, retrieve, and
on delete data within a work with.
database • Usage: Once a
Command database is selected
with `USE`, all
s (DML) subsequent SQL
commands will be
executed within that
database.
•USE my_database;
Data Manipulation Commands (DML)
INSERT Command
• Purpose: Adds new rows of data into a table.
• Usage: Inserts values into specified columns of a table.
INSERT INTO Users (username, email, age)
Data Manipulation Commands (DML)
UPDATE Command
• Purpose: Modifies existing data in a table.
• Usage: Updates the values of specified columns for rows that meet a
given condition.
UPDATE Users
WHERE username = 'john_doe';
Data Manipulation Commands (DML)
DELETE Command
• Purpose: Removes rows from a table.
• Usage: Deletes rows that match a given
condition.
DELETE FROM Users WHERE age
< 18;
Data Manipulation Commands (DML)
MERGE 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
Types of • Definition: A primary key is a unique identifier for a
record in a database table. Each table can have only
one primary key.
keys • Characteristics: It must contain unique values, and it
cannot contain NULLs.
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
databases another table.
• Characteristics: It creates a link between two tables.
The values in the foreign key column(s) must match
values in the referenced table's primary key column(s).
• Purpose: It maintains referential integrity
• Unique Key:
• Definition: A unique key ensures that all values in a
Types of column or a group of columns are unique across the
table.
• Characteristics: Unlike the primary key, a table can
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.
databases • Composite Key:
• Definition: A composite key (or compound key) is a
primary key that consists of two or more columns.
• Characteristics: Each column that makes up the
composite key can be non-unique individually, but the
combination of all the columns must be unique.
• Purpose: It is used when a single column is not
sufficient to uniquely identify records. For example, a
combination of `OrderID` and `ProductID` might be
used as a composite key in an order details table.
SQL code
--Create Orders table
--Create Customers table
CREATE TABLE Orders (
CREATE TABLE Customers ( OrderID INT, -- Part of Composite Key
-- Primary Key ProductID INT, -- Part of Composite Key
CustomerID INT PRIMARY CustomerID INT, -- Foreign Key
KEY, OrderDate DATE,
FirstName VARCHAR(50), Quantity INT,
LastName VARCHAR(50), PRIMARY KEY (OrderID, ProductID),
-- Unique Key -- Composite Key (OrderID + ProductID)
Email VARCHAR(100) FOREIGN KEY (CustomerID) REFERENCES
UNIQUE, Customers(CustomerID)
-- Foreign Key referencing Customers table
PhoneNumber VARCHAR(15)
);
);
In relational databases, constraints are rules applied to
columns in a table to ensure data integrity and adherence
to certain conditions:
• NOT NULL Constraint
• Purpose: Ensures that a column cannot have a
`NULL` value.
Constraint • Usage: Applied when a column is required to
always have a value.
• Example: If you have a `Users` table and you want
s to ensure that every user has a username, you can
define the `username` column with a `NOT NULL`
constraint.
CREATE TABLE Users (
id INT PRIMARY KEY,
username VARCHAR(50) NOT NULL,
email VARCHAR(100)
);
• CHECK Constraint
• Purpose: Ensures that all values in a column satisfy
a specific condition.
• Usage: Applied to enforce domain integrity by
specifying a condition that must be true for the
column values.
Constraint • Example: To ensure that the age of users is greater
than 18, you can use a `CHECK` constraint.
s CREATE TABLE Users (
id INT PRIMARY KEY,
username VARCHAR(50) NOT NULL,
email VARCHAR(100),
age INT CHECK (age > 18)
);
•DEFAULT Constraint
• Purpose: Provides a default value for a column when
no value is specified during an insert operation.
• Usage: Applied to assign default values to columns,
reducing the need to explicitly specify values for every
insert.
Constraint • Example: If you want the `status` column to default to
'active' when no status is provided, you can use a
`DEFAULT` constraint.
s CREATE TABLE Users (
id INT PRIMARY KEY,
username VARCHAR(50) NOT NULL,
email VARCHAR(100),
status VARCHAR(20) DEFAULT 'active’
);
•UNIQUE Constraint
• Purpose: Ensures that all values in a column (or a
combination of columns) are distinct from each
other.
• Usage: Applied to enforce the uniqueness of values.
Useful for columns like email addresses or
Constraint usernames where duplicates are not allowed.
• Example: To ensure that every email address in the
s
`Users` table is unique, you can apply a `UNIQUE`
constraint.
CREATE TABLE Users (
id INT PRIMARY KEY,
username VARCHAR(50) NOT NULL UNIQUE,
email VARCHAR(100) UNIQUE
);