Database Management System (DBMS)
ASIF……
Database: It is an organized collection of data so that it can be easily accessed. To manage these databases,
DBMS (Database Management System) are used.
Types of Database Management System (DBMS):
1. Relational Database Management System (RDBMS)
2. Non – Relational Database Management System (NRDBMS)
1 Relational Database Management System (RDBMS):
In this DBMS data stored in table format.
Roll No Name Class
1 Aadil Khalid 5th
2 Farooque 8th
3 Saqib Baloch 9th
4 Aqib Hussain
For Example: MySQL, Oracle
2 Non-Relational Database Management System (RDBMS):
In this DBMS data is stored in key-value pair.
For Example: Mongo DB, Redis
SQL: It stands for Structured Query Language. SQL is used for update, delete and insert data in table or
Relational Database.
SQL Create Command: It is used for create tables.
Syntax:
CREATE TABLE tablename (
Column1 datatype,
Column2 datatype,
…....................................... so on
);
SQL Keywords are Case-insensitive.
In MySQL, case-insensitive is an option you can turn on and off.
For Example:
CREATE TABLE user (
First_Name VARCHAR,
Last_Name VARCHAR,
Email_id VARCHAR,
Password VARCHAR,
);
First_Name Last_Name Email_id Password
SQL INSERT INTO Command:
It is used to insert data into tables.
Syntax:
INSERT INTO TableName (Column1, Column2 …….)
VALUES (Value1, Value2 …….);
● A row of database table is known as record or a tuple.
● A column of database table is known as attribute.
For Example:
INSERT INTO USER (FirstName, LastName, Email_id, Password)
Values (Asif, Ali, asifali12@[Link], Asif123@);
FirstName LastName Email_id Password
Asif Ali asifali12@[Link] Asif123@
SQL SELECT Command:
It is used to retrieves data from the table.
Syntax:
SELECT Column1, Column2
FROM tablename;
To select complete table, use * (Asterisk)
SELECT *
FROM tablename;
Example:
FirstName LastName Password
Asif Ali Asif123@
Arif Ahmed Arif786@
Aqib Hussain Aqib234@
Command:
SELECT FirstName
FROM User;
Output:
FirstName
Asif
Arif
Aqib
SQL Constraints:
These constraints also known as Integrity Constraints.
SQL Constraints: Constraints are the rules and restrictions applied on the data in a table.
NOT NULL: Value cannot be null in a column.
UNIQUE: Value cannot be same in a column.
PRIMARY KEY: Used uniquely identify a row.
FOREIGN KEY: References a row in another table.
CHECK: Satisfies a specific condition.
DEFAULT: Set default value.
CREATE INDEX: Used to speed up the read process.
SQL QUERY EXECUTION ORDER:
FROM JOIN WHERE GROUP BY HAVING SELECT ORDER BY
LIMIT
Difference between ALTER and UPDATE.
ALTER UPDATE
It is a DDL. It is a DML.
It is used for adding, deleting and modifying It is used for updating the data in the existing table.
attributes of the table.
Changes are made to the table structure. Changes are made to the data.
By default, all the values in the tuple are initialized It sets the specified value to the tuple if UPDATE
as null if the ALTER command is used. command is used.
SQL SELECT DISTINCT:
It is used to return only unique values from a specified column in a table.
Syntax:
SELECT DISTINCT column_name
FROM table_name;
Example:
First Name Last Name Password
Asif Ali 123
Arif Ahmed Xyz
Aqib Hussain Abc
Command:
SELECT DISTINCT Password
FROM user;
Output:
Password
123
Xyz
Abc
SQL WHERE CLAUSE:
It is used to FILTER rows in a table based on a specified condition.
Syntax:
SELECT column_name
FROM table_name
WHERE condition;
Example:
First Name Last Name Age
Asif Ali 19
Arif Ahmed 20
Aqib Hussain 21
Command:
SELECT First_Name, Last_Name
FROM user
WHERE age > 20;
Output:
First Name Last Name
Aqib Hussain
SQL AND:
The AND operator returns true if both conditions are true otherwise false.
Syntax:
WHERE condition1 AND condition2;
SQL OR:
It is returns true if either condition is true and false if both condition are false.
Syntax:
WHERE condition1 OR condition2
SQL NOT:
It returns the opposite of a condition.
Syntax:
WHERE NOT condition;
AND, OR, NOT operators are used to combine conditions in a WHERE clause to create more complex
filtering conditions.
SQL ORDER By:
It is used to sort the result of a query in ascending or ascending order.
Syntax:
SELECT column1, column2, …….
FROM table_name
ORDER By column1[ASC] [DESC], column2[ASC][DESC],………
ASC: It is used to set the result in ascending order.
DESC: It is used to sort the result in descending order.
Example:
First Name Last Name Age
Asif Ali 49
Arif Ahmed 20
Aqib Hussain 21
Command:
SELECT *
FROM user;
ORDER By Age;
Output:
First Name Last Name Age
Asif Ali 20
Arif Ahmed 21
Aqib Hussain 49
INSERT INFO:
It is used to insert data into a table.
Syntax:
INSERT INTO tablename (column1, column2, .......... )
Values (Value1, Value2,............ );
Note:
These must be the same number of columns specified.
Example:
First Name Last Name Age
Asif Ali 10
Arif Ahmed 15
Aqib Hussain 20
Command:
INSERT INTO user (First Name, Last Name, Age)
VALUES (Ahmed, Ali, 25);
Output:
First Name Last Name Age
Asif Ali 10
Arif Ahmed 15
Aqib Hussain 20
Ahmed Ali 25
SQL NULL VALUES:
It is used represent missing or unknown data.
Note: Null is different from zero or empty string.
INSERT NULL VALUE:
INSERT INTO tablename (column1, column2, …….)
VALUES (value1, Null, ....... )
TO CHECK FOR NULL VALUE:
IS NULL:
SELECT column1, column2, …………
FROM table_name
WHERE column2 is NULL
IS NOT NULL:
SELECT column1, column2, ……….
FROM table_name
WHERE column1 is not Null;
SQL UPDATE:
It is used to modify existing data in table.
Syntax:
UPDATE table_name
SET column1=value1, column2=value2,…………
WHERE some_column=some_value;
SET:
It is used to specify the column and values to update.
Example:
First Name Last Name Age
Asif Ali 10
Arif Ahmed 15
Aqib Hussain 20
Command:
UPDATE users
SET age = age + 1;
Output:
First Name Last Name Age
Asif Ali 11
Arif Ahmed 16
Aqib Hussain 21
SQL DELETE:
It is used to remove existing record from a table in a SQL database.
Syntax:
DELETE FROM tablename WHERE condition;
Note:
The operation is not reversible so be careful when using DELETE statements.
SQL WILDCARDS:
Wildcards are special characters used in SQL ‘LIKE’ operator to search for a specific pattern in a column of a
table.
The percent sign (%) represents zero, one or multiple characters.
The underscore (_) represents one, single character.
SQL LIKE:
It is used to search for a specific pattern in a column of a table.
Syntax:
SELECT column1, column2,…………
FROM table_name
WHERE column_name LIKE pattern;
SQL IN:
It is used to specify multiple values in a WHERE clause for filtering data.
Syntax:
SELECT column1, column2,…………
FROM table_name
WHERE column_name IN (value1, value2);
SQL BETWEEN:
It is used to filter data based on a range of values in a WHERE clause.
Syntax:
SELECT column1, column2,…………
FROM table_name
WHERE column_name BETWEEN value1 and value2;
SQL ALIAS (AS):
It is used to give a temporary name to a table or a column in a query.
Syntax:
SELECT column_name AS alias_name
FROM table_name;
SQL Practice Queries:
1. [Link] 2. [Link]
1. SQL SELECT STATEMENT
□ SELECT CustomerName,Address,City
FROM Customers;
□ SELECT patient_id,first_name,birth_date
FROM patients;
2. SQL SELECT DISTINCT
□ SELECT DISTINCT City
FROM Customers;
SELECT DISTINCT country
FROM Customers;
3. SQL ALIASES
□ SELECT CustomerName AS name
FROM Customers;
SELECT CustomerID AS ID
FROM Customers;
4. SQL
□ SELECT CustomerName+Postalcode+Address+City
FROM Customers;
□ SELECT CustomerName+' '+City+' '+Postalcode+' '+Address
FROM Customers;
□ SELECT CustomerName, contactname, Address, City, Postalcode, Country
FROM Customers
WHERE CustomerName='Around the Horn';
5. SQL COUNT FUNCTION
SELECT COUNT (ContactName) AS ContactName
FROM Customers
WHERE ContactName='Maria Anders';
6. SQL ORDER BY
□ SELECT *
FROM Products
ORDER BY ProductID desc;
□ SELECT *
FROM Customers
ORDER BY Address,Postalcode;
7. WHERE + ORDER BY
SELECT CustomerName, contactname, Address, City, Postalcode, Country
FROM Customers
WHERE Country='Germany'
ORDER BY Postalcode;
8. SQL BETWEEN
□ SELECT *
FROM patients
WHERE birth_date between'1939-09-02'and'1945-08-03'
ORDER BY birth_date;
9. SQL OR
SELECT *
FROM Customers
Where Country='Mexico'
OR Country='UK';
10. SQL IN
SELECT ProductName,Price,SupplierID
FROM Products
WHERE Price BETWEEN 30 AND 40
AND SupplierID IN (4,5,6);
11. SQL AND
SELECT *
FROM patients
WHERE Weight between 70 and 100;
SELECT *
FROM patients
WHERE height between 160 and 180
AND gender='M'
AND city in ('Delhi','Hamilton')
AND allergies=('Ragweed');
12. ARITHMETIC OPERATIONS (+,-,*,/,%)
❖ + ADDITION
□ SELECT price+10
FROM Products;
❖ - SUBTRICATION
□ SELECT price-5
FROM Products;
❖ ● MULTIPLICATION
□ SELECT price* 3
FROM products;
❖ / DIVISION
□ SELECT Price/3
FROM products;
❖ % PERCENTAGE
□ SELECT Price,Price*10/100
FROM Products;
❖ PERCENTAGE –
□ SELECT ProductName,Price,Price*10/100 AS Discount,Price-(10/100*price) as
DiscountedPrice
FROM Products;
❖ PERCENTAGE +
SELECT ProductName,Price,Price*18/100 AS Salestax,Price+(18/100*price) as TotalPrice
FROM Products;
13. SQL NOT
SELECT *
FROM Customers
WHERE not Country='Germany';
14. SQL LIKE
SELECT *
FROM Customers
WHERE CustomerName LIKE 'b%';
15. SQL WILDCARD
SELECT company_name
FROM customers
WHERE company_name like ('%/South');
16. SQL FUNCTIONS
❖ LOWER CASE
SELECT customer_id,company_name
FROM customers where lower(customer_id)='bolid';
17. SQL CONCAT
SELECT concat(height,'CM') as height,concat(weight,'kg')as weight
FROM patients;
18. SQL LENGTH
SELECT CustomerName, LENGTH(CustomerName) AS LengthOfalphabat
FROM Customers
WHERE length(CustomerName)=10;
1. WRITE QUERY THATS SHOW A PRODUCTS THAT VALUE MORE THEN 10$
□ SELECT SupplierID,ProductName,Price
FROM Products
WHERE Price > 10 Order by SupplierID;
2. Write a query that shows details of all customers expect in Berlin
□ SELECT * FROM Customers
WHERE City<>'Berlin';
3. Write A query that show a patience allergic to penicillin
□ SELECT first_name,allergies
FROM patients where allergies = 'Penicillin';
4. Write a query that shows complete details that have weight > 80
□ SELECT first_name,last_name,gender,birth_date,weight
FROM patients
WHERE weight>80
ORDER By weight;
5. Write a query that shows complete details whose height is > 180
□ SELECT count(height)
FROM patients
WHERE height>180;
6. Write a query that shoes details all cardiologist
□ SELECT doctor_id,first_name,last_name,speciality
FROM doctors
WHERE specialty='Cardiologist';
7. Write a query that shows the details that neither over weight
□ SELECT *
FROM patients
WHERE weight between 70 and 100;
8. Write a query that shows the details the patients born during world war 2
□ SELECT *
FROM patients
WHERE birth_date between'1939-09-02'and'1945-08-03' order by birth_date;
9. Write a query that display all products whose price is more then 20 and supplied by no2
□ SELECT *
FROM Products
WHERE SupplierID=2 AND Price>20;
10. Write a query that displays the details that shows productname,price ,disprice10%,and price after
add sell tax final price on the discount price
□ SELECT ProductName,Price,Price*10/100 as Discount,Price-(10/100*Price) as
DiscountedPrice,DiscountedPrice*18/100 as salestax,DiscountedPrice+3.24 AS TotalPrice
From Products;
11. Our client running promotion 5% cash back on listed price on all products
□ SELECT ProductName,Price,Price*5/100 as Cashback
From Products;
12. Write a query that shows product name and price price have 60%cost and 40% profit
□ SELECT ProductName,Price,Price*40/100 AS Profit,Price*60/100 AS Cost
FROM Products;
13. Write query that shows other countries without germany
□ SELECT *
FROM Customers
WHERE not Country='Germany';
14. Write a query that shows the patients that are diagnosis by Cardiac Arrest Asthma Exacerbation
Cancer
□ SELECT *
FROM admissions
WHERE diagnosis in ('Cardiac Arrest','Asthma Exacerbation','Cancer');
15. Write a query that shows product from categoryID 2,4,6 supplied by supplierID 1,3,5
□ SELECT *
FROM Products
WHERE CategoryID in (2,4,6) and SupplierID IN (1,3,5);
16. Write a query that shows product within the price range of 10 to 50
□ SELECT *
FROM Products
WHERE Price between 10 and 50;
17. Write a query that shows the details of all patients who are born in millennium and reside in delhi
hamilton and toronto
□ SELECT *
FROM patients
WHERE year (birth_date)>=2000 and city in ('Delhi','Hamilton','Toronto');
18. Write a query that shows the name of all patients that height between 160 and 180
SELECT first_name,height
FROM patients
WHERE height between 160 and 180;
19. Write a query that shows that display the height of male and females separately
□ SELECT first_name,height,gender
FROM patients
WHERE height between 160 and 180 and gender='M';
SELECT first_name,height,gender
FROM patients
WHERE height between 160 and 180 and gender='F';
20. Write a query that displays all the details of products that show supplied by supplier 1 and price
between 15 and 20
SELECT *
FROM Products
WHERE SupplierID=1 and Price Between 10 and 20;
21. Write a query thats shows the name of all customers names that lives in mexico or london
□ SELECT *
FROM Customers
WHERE City in ('Mexico','London');
□ SELECT *
FROM Customers
WHERE City=('London') OR Country=('Mexico');
22. Write a details of all female patients live in Ontario and allergic to penicillin
□ SELECT first_name,allergies,gender,province_id
FROM patients
WHERE gender=('F') and allergies=('Penicillin') and province_id='ON';
23. Write a query that show all the product available in stock
□ SELECT product_name,unit_price,unit_price*units_in_stock as totalvalue,units_in_stock
FROM products;
24. Write a query that displays the name of all product and 10times of price
□ SELECT product_name,unit_price*10 as price
FROM products;
25. Write a query that reduce price off all product reduce by 2
□ SELECT product_name,unit_price-2 as NewPrice
FROM products;
26. Write a query that shows the product name and county which have been discontinued
□ SELECT product_name,discontinued
FROM products
WHERE discontinued>0;
27. Write a query that shows the total value of units on order
□ SELECT product_name,unit_price,units_on_order,unit_price*units_on_order
FROM products;
28. Write a query of customers that shows length is 6 or > 6 and have H in there name
□ SELECT CustomerName,Length(CustomerName)as length_of_Alphabate
FROM Customers
WHERE Length(CustomerName)>6 and CustomerName like'h%';
29. Write a query extract 4 character long sub section name starting form 3rd position
□ SELECT CustomerName,left(CustomerName,CHARINDEX(' ',CustomerName)) as First_Name
FROM Customers;
30. Write a query that shows the price with decimal value
□ SELECT left(price,2)
FROM Products;
31. Write a query that shows the details of product with lowest price
□ SELECT *
FROM Products
WHERE Price=(select min(Price) from Products);
32. Write a query that shows the product price and name with highest price
□ SELECT CustomerName
FROM Customers
WHERE length(CustomerName)=(select max(length(CustomerName))
FROM Customers);
Create a database in my SQL
Command
□ Create a database zurain_for_joins_class ;
□ Use sarfraz_for_joins_class;
Create a table
Command
□ Create a table my_students(name varchar(25),phone int(11));
To show table structure
□ Desc myfriends;
Insert record into a table
□ Insert into myfriends(name, phone) values (‘ali’, 123);
Alter table
□ Alter table myfriends
□ Add column city varchar(50):
Alter a column name
□ Alter table myfriends
□ Rename city to county;
Alter table name
□ Alter table order rename to orders;
□ Update a record in a column
□ Update myfriends Set city=’sehwan_sharif’;
□ Where name=’ali’;
Course: Database Administrator Batch – II
Name: Shahid Ahmed
CNIC: 41306-3281800-7
Date: 31-10-2025
Day: Friday
DBA Mini Project
Task 1 and 2: Table Creation and Insert Values:
Create the following tables for a simple online store database:
1. Customers Table:
CREATE TABLE customers (
customer_id INT PRIMARY KEY AUTO_INCREMENT,
first_name VARCHAR(50),
last_name VARCHAR(50),
email VARCHAR(100) UNIQUE,
address VARCHAR(255),
registration_date DATE
);
Insert Values:
INSERT INTO customers (customer_id, first_name, last_name, email, phone, address,
registration_date)
VALUES
(1, 'John', 'Doe', '[Link]@[Link]', '555-1234', '123 Elm St', '2023-01-15'),
(2, 'Jane', 'Smith', '[Link]@[Link]', '555-5678', '456 Oak St', '2023-03-20'),
(3, 'Alice', 'Johnson', '[Link]@[Link]', '555-8765', '789 Pine St', '2023-05-
10')
ON DUPLICATE KEY UPDATE
first_name = VALUES(first_name),
last_name = VALUES(last_name),
email = VALUES(email),
phone = VALUES(phone),
address = VALUES(address),
registration_date = VALUES(registration_date);
Output:
2. Products Table:
CREATE TABLE IF NOT EXISTS products (
product_id INT PRIMARY KEY AUTO_INCREMENT,
product_name VARCHAR(100) NOT NULL,
category VARCHAR(50),
price DECIMAL(10, 2) CHECK (price >= 0),
stock_quantity INT CHECK (stock_quantity >= 0),
date_added DATE
);
Insert Values:
INSERT INTO products (product_id, product_name, category, price, stock_quantity,
date_added)
VALUES
(1, 'Laptop', 'Electronics', 899.99, 50, '2023-02-15'),
(2, 'Smartphone', 'Electronics', 499.99, 100, '2023-04-10'),
(3, 'Headphones', 'Accessories', 69.99, 200, '2023-06-01'),
(4, 'Coffee Maker', 'Appliances', 89.99, 75, '2023-07-15')
ON DUPLICATE KEY UPDATE
product_name = VALUES(product_name),
category = VALUES(category),
price = VALUES(price),
stock_quantity = VALUES(stock_quantity),
date_added = VALUES(date_added);
Output:
3. Orders Table:
CREATE TABLE IF NOT EXISTS orders (
order_id INT PRIMARY KEY AUTO_INCREMENT,
customer_id INT,
order_date DATE,
total_amount DECIMAL(10, 2) CHECK (total_amount >= 0),
FOREIGN KEY (customer_id) REFERENCES customers(customer_id)
ON DELETE CASCADE
ON UPDATE CASCADE
);
Insert Values:
INSERT INTO orders (order_id, customer_id, order_date, total_amount)
VALUES
(1, 1, '2023-07-01', 999.98),
(2, 2, '2023-08-15', 569.98),
(3, 1, '2023-09-10', 969.98);
Output:
4. Order_items Table:
CREATE TABLE Order_Items (
order_item_id INT PRIMARY KEY,
order_id INT,
product_id INT,
quantity INT,
item_price DECIMAL(10, 2),
FOREIGN KEY (order_id) REFERENCES Orders(order_id),
FOREIGN KEY (product_id) REFERENCES Products(product_id)
);
Insert Values:
INSERT INTO Order_Items (order_item_id, order_id, product_id, quantity, item_price)
VALUES
(1, 1, 1, 1, 899.99),
(2, 1, 3, 1, 69.99),
(3, 2, 2, 1, 499.99),
(4, 2, 4, 1, 69.99),
(5, 3, 1, 1, 899.99),
(6, 3, 2, 1, 499.99);
Output:
Task 3: Data Retrieval using SQL Operators and Functions:
1. Retrieve all customers who registered after March 1, 2023.
SELECT *
FROM Customers
WHERE registration_date > '2023-03-01';
2. List all products with stock quantities greater than 50 and price less than 100.
SELECT *
FROM Products
WHERE stock_quantity > 50
AND price < 100;
3. Get the total number of orders placed by a customer with customer_id = 1.
SELECT COUNT(*) AS total_orders
FROM Orders
WHERE customer_id = 1;
4. Calculate the total revenue generated by each product based on quantity sold.
-- Calculate total revenue generated by each product
SELECT
p.product_id,
p.product_name,
SUM([Link] * oi.item_price) AS total_revenue
FROM Order_Items AS oi
JOIN Products AS p
ON oi.product_id = p.product_id
GROUP BY
p.product_id,
p.product_name
ORDER BY
total_revenue DESC;
5. Get the total value of all orders placed on the date '2023-07-01'.
SELECT SUM([Link] * oi.item_price) AS total_order_value
FROM Orders o
JOIN Order_Items oi ON o.order_id = oi.order_id
WHERE o.order_date = '2023-07-01';
6. List the 3 most expensive products.
SELECT *
FROM Products
ORDER BY price DESC
LIMIT 3;
7. Update the price of a product with product_id = 3 to 79.99.
UPDATE Products
SET price = 79.99
WHERE product_id = 3;
8. Delete all products in the 'Appliances' category.
DELETE FROM Products
WHERE category = 'Appliances';
9. Find customers who have placed more than one order.
SELECT customer_id, COUNT(*) AS order_count
FROM Orders
GROUP BY customer_id
HAVING COUNT(*) > 1;
9. Retrieve all orders placed in the year 2023.
SELECT *
FROM Orders
WHERE YEAR(order_date) = 2023;
The End