0% found this document useful (0 votes)
2 views28 pages

Lecture Week 4-Databases

The document provides an overview of various SQL concepts including arithmetic, assignment, comparison, and logical operators, as well as string functions, aggregate functions, and nested queries. It also covers SQL procedures, triggers, events, and the use of the PARTITION BY clause with window functions. Examples are provided throughout to illustrate the application of these concepts in SQL queries.

Uploaded by

Layan Mahasneh
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views28 pages

Lecture Week 4-Databases

The document provides an overview of various SQL concepts including arithmetic, assignment, comparison, and logical operators, as well as string functions, aggregate functions, and nested queries. It also covers SQL procedures, triggers, events, and the use of the PARTITION BY clause with window functions. Examples are provided throughout to illustrate the application of these concepts in SQL queries.

Uploaded by

Layan Mahasneh
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 28

LO1: MS SQL server

Databases-Week 4
Definition: Used to perform mathematical
calculations.
Operators:

+ (Addition)

- (Subtraction)
Arithmetic * (Multiplication)
Operators / (Division)

% (Modulo)

Example:
SELECT 10 + 5 AS Addition, 10 - 5 AS
Subtraction;
Definition: Used to assign a value to a variable.

Operator:

= (Assigns a value to a variable or field)

Assignmen Example:

t Operators BEGIN --group multiple SQL statements


DECLARE @EmployeeCount INT; --@ is required in
DECLARE

SET @EmployeeCount = (SELECT COUNT(*) FROM


Employee);
SELECT @EmployeeCount AS TotalEmployees; --print
the results
END;
Definition: Used to compare values.

Operators:

= (Equal to)
Compariso != or <> (Not equal to)
n
Operators > (Greater than)

< (Less than)

Example:

SELECT CASE WHEN 5 > 3 THEN 'True' ELSE 'False'


END AS Result;
Definition: Shortcuts that combine
arithmetic and assignment.
Operators:

+=, -=, *=, /=, %= (Add and assign,


Compound etc.)

Operators Example:

DECLARE @x INT = 10;

SET @x += 5;
Definition: Used to combine multiple conditions
in queries.
Operators:

AND (True if both conditions are true)

Logical OR (True if either condition is true)


Operators NOT (Negates a condition)

Example:

SELECT CASE WHEN (5 > 3 AND 10 > 5) THEN


'True' ELSE 'False' END AS Result;
-- Create the Employees table
CREATE TABLE Employees (
EmployeeID INT PRIMARY KEY,
Name VARCHAR(100)

Set
);
-- Insert sample data into Employees
INSERT INTO Employees (EmployeeID,

Operators
• Definition: Used to combine Name)
result sets. VALUES
(1, 'Alice'),
• Operators:
(2, 'Bob'),
• UNION (Without duplicates) (3, 'Charlie');
-- Create the Managers table
• UNION ALL (With duplicates) CREATE TABLE Managers (
• INTERSECT (Common rows) ManagerID INT PRIMARY KEY,
Name VARCHAR(100)
• EXCEPT (Rows not in second );
set). -- Insert sample data into Managers
INSERT INTO Managers (ManagerID, Name)
• Example
VALUES
A={1,2,3}, B={2,3,4} (1, 'David'),
(2, 'Eve'),
A UNION B = {1,2,3,4} (3, 'Alice'); -- Note: Alice appears in both
tables
A UNION ALL B={1,2,3,2,3,4}
-- Run the UNION query
A INTESECT B = {2,3} SELECT Name FROM Employees
UNION
A EXCEPT B ={1} SELECT Name FROM Managers;
Definition: Used to join strings.

Operator:
String
Concatenati + (String concatenation)
on Operator
Example:

SELECT 'Hello'+ ' '+ FirstName + ' ' +


LastName
FROM Employees AS Greeting;
-- Create the Employees table
CREATE TABLE Employees (
EmployeeID INT PRIMARY KEY,
Name VARCHAR(100),
Aggregate • Definition: Perform
calculations on a );
Salary DECIMAL(10, 2)

Functions set of values.


-- Insert sample data into
• Functions: Employees
INSERT INTO Employees
• SUM(), AVG(), (EmployeeID, Name, Salary)
COUNT(), MIN(), VALUES
MAX() (1, 'Alice', 50000.00),
(2, 'Bob', 55000.00),
(3, 'Charlie', 60000.00),
(4, 'David', 65000.00),
(5, 'Eve', 70000.00);

-- Run the aggregation query


SELECT COUNT(*) AS
EmployeeCount,
SUM(Salary) AS TotalSalary,
AVG(Salary) AS AverageSalary
FROM Employees;
Nested Queries
Nested Queries -- Create the Employees table
CREATE TABLE Employees (
EmployeeID INT PRIMARY KEY,

Example FirstName VARCHAR(50) NOT NULL,


LastName VARCHAR(50) NOT NULL,
Salary DECIMAL(10, 2) NOT NULL,

-- Create the Departments table DepartmentID INT,


Age INT,
CREATE TABLE Departments (
FOREIGN KEY (DepartmentID) REFERENCES
DepartmentID INT PRIMARY KEY, Departments(DepartmentID)
);
DepartmentName VARCHAR(100) NOT NULL
-- Insert rows into the Employees table
); INSERT INTO Employees (EmployeeID, FirstName, LastName, Salary,
DepartmentID, Age)
VALUES
-- Insert rows into the Departments table
(1, 'John', 'Doe', 60000.00, 1, 29),
INSERT INTO Departments (DepartmentID, (2, 'Jane', 'Smith', 70000.00, 2, 34),
DepartmentName) (3, 'Alice', 'Johnson', 80000.00, 3, 28),
VALUES (4, 'Bob', 'Williams', 65000.00, 4, 42),
(1, 'Human Resources'), (5, 'Charlie', 'Brown', 55000.00, 5, 30),
(6, 'Emily', 'Davis', 72000.00, 2, 31),
(2, 'Finance'),
(7, 'Michael', 'Wilson', 69000.00, 3, 45),
(3, 'Engineering'), (8, 'Sarah', 'Taylor', 80000.00, 4, 27),
(4, 'Marketing'), (9, 'David', 'Clark', 62000.00, 5, 37),

(5, 'Sales'); (10, 'Laura', 'Miller', 75000.00, 1, 40);


Nested Queries
• Find employees who have a higher salary than the
average salary of their department.

SELECT e.FirstName, e.LastName, e.Salary, e.DepartmentID


FROM Emp e
WHERE Salary > (SELECT AVG(Salary) FROM Emp WHERE DepartmentID =
e.DepartmentID);

Inner Query: Computes the average salary for each department (DepartmentID).
The WHERE DepartmentID = e.DepartmentID ensures that the average salary is calculated
for only the employees within the same department as the current employee e.
Nested Queries
• List departments with more than 2 employees.

SELECT d.DepartmentName, COUNT(e.EmployeeID) AS EmployeeCount


FROM Departments d
JOIN Emp e ON d.DepartmentID = e.DepartmentID
GROUP BY d.DepartmentName
HAVING COUNT(e.EmployeeID) >=2;
Note:
•WHERE is used to filter individual rows before aggregation (before GROUP BY is applied).
•HAVING is used to filter aggregated results (after GROUP BY has been applied).
•WHERE COUNT(e.EmployeeID) >= 2 --this is wrong
Nested Queries
• Find the highest salary in each department.

SELECT d.DepartmentName, MAX(e.Salary) AS


HighestSalary
FROM Departments d
JOIN Emp e ON d.DepartmentID = e.DepartmentID
GROUP BY d.DepartmentName;
Nested Queries
• List employees who are older than the average age of all
employees.
DECLARE @AveAge DECIMAL(5,2);
SET @AveAge = (SELECT AVG(Age) FROM Emp); --Average
age for all employees
SELECT FirstName, LastName, Age
FROM Emp
WHERE Age > @AveAge;
Modify the code to List employees who are older
than the average age of their department
Nested Queries
• Find employees who work in the same department as 'Jane
Smith’.

SELECT e.FirstName, e.LastName, e.DepartmentID


FROM Emp e
WHERE e.DepartmentID = (SELECT DepartmentID FROM Emp
WHERE FirstName = 'Jane' AND LastName = 'Smith’);

Modify the code to have the DepartmentName instead


if DepartmentID
LIKE Operator
• The LIKE operator is used in SQL to search for a specified
pattern in a column.
• It is often used with wildcards:
• % represents zero or more characters.
• _ represents a single character.
• Example: selects all employees whose first names start
with 'J’.

SELECT * FROM Employees


WHERE FirstName LIKE 'J%';
HAVING Clause
• The HAVING clause is used to filter records after
aggregation.
• It is typically used after GROUP BY. Note WHERE used
before GROUP BY.
• Example: return departments that have more than 2
employees only.

SELECT DepartmentID, COUNT(*) AS EmployeeCount


FROM EmployeesGROUP BY DepartmentI
DHAVING COUNT(*) > 2; --You cannot use WHERE Clause
String Functions
• TRIM function removes leading and trailing spaces from a string.
• LTRIM removes leading spaces.
• RTRIM removes trailing spaces.
--Insert new records with extra spaces in FirstName
INSERT INTO Employees (EmployeeID, FirstName, LastName, Salary,
DepartmentID, Age)VALUES(11, ' Mark', 'Anderson', 58000.00, 1, 33),(12,
'Anna ', 'Thomas', 62000.00, 3, 29),(13, ' Steve ', 'Harris', 59000.00, 2,
35);
SELECT FirstName, TRIM(FirstName) AS TrimmedString,
LTRIM(FirstName) AS LeftTrimmed, RTRIM(FirstName) AS RightTrimmed
FROM Employees
WHERE EmployeeID IN (11, 12, 13);
String Functions
• REPLACE substitutes occurrences of a substring.
• SUBSTRING extracts part of a string.
• UPPER converts text to uppercase.
• LOWER converts text to lowercase
• LEFT(string, n) returns the first nth character of the string

SELECT FirstName,
REPLACE(FirstName, 'a', 'X') AS ReplacedString,
SUBSTRING(FirstName, 1, 3) AS SubStringExample,
UPPER(FirstName) AS UpperCaseName,
LOWER(LastName) AS LowerCaseName,
LEFT(LastName, 1) AS FirstChaName
FROM Employees;
CASE Statement
• The CASE statement allows conditional logic in SQL queries.
• It is useful for categorizing data into different groups.

SELECT
FirstName,
LastName,
Salary,
CASE
WHEN Salary > 75000 THEN 'High Salary'
WHEN Salary BETWEEN 60000 AND 75000 THEN 'Medium Salary'
ELSE 'Low Salary'
END AS SalaryCategory
FROM Employees;
• To read a table from an MS SQL
Server into a pandas DataFrame

Read using Python, you can use the pyodbc


(Python Open Database
Connectivity)library to establish a
database connection and execute SQL queries.

from MS SQL pip install pyodbc pandas


server using import pyodbc

Python as import pandas as pd


conn =
DataFrame pyodbc.connect('DRIVER={ODBC
Driver 17 for SQL Server};'
'SERVER=SALEEM;'
'DATABASE=Students1;'
'Trusted_connection=yes;')
Read # Define your SQL query
query = "SELECT * FROM
database StudentsInfo”
from MS SQL # Read the table into a
DataFrame
server using df = pd.read_sql(query, conn)
Python as # Close the connection
DataFrame conn.close()
# Show the DataFrame
print(df.head())
Self
reading
SQL Procedures
• A stored procedure is a set of SQL statements that can be executed as a
single unit.
• Example: Retrieve total sales for an employee in an E-commerce Database.

DELIMITER //
CREATE PROCEDURE GetTotalSales(IN emp_id INT)
BEGIN
SELECT SUM(amount) AS TotalSales
FROM Orders
WHERE employee_id = emp_id;
END // --Test the Stored Procedure
DELIMITER ;
CALL GetTotalSales(101);
SQL Triggers
• A trigger is an automatic action executed before or after an event on a table.
• Example: Automatically logs any new order in an E-commerce Database

DELIMITER //
CREATE TRIGGER after_order_insert
AFTER INSERT ON Orders
FOR EACH ROW
BEGIN
INSERT INTO AuditLog (action, order_id, timestamp)
VALUES ('INSERT', NEW.order_id, NOW());
END //
INSERT INTO Orders (customer_id, employee_id,
DELIMITER ; amount, order_date) VALUES (1, 104, 300.00,
'2025-03-25');
SQL Events
• An event is a scheduled task in SQL that runs at a specific time or interval.
• Example: Automatically deletes orders older than one year in an E-commerce
Database.

DELIMITER //
CREATE EVENT DeleteOldOrders
ON SCHEDULE EVERY 1 DAY
DO
BEGIN
DELETE FROM Orders WHERE order_date < NOW() - INTERVAL 1 YEAR;
--NOW() - INTERVAL 1 YEAR: Computes the date exactly one year before today.
END // -- Enable the event scheduler
DELIMITER ; SET GLOBAL event_scheduler = ON;
PARTITION BY
The PARTITION BY clause is used in conjunction with window functions to divide the result set
into partitions (or groups). Common window functions are:
•ROW_NUMBER(): Assigns a unique sequential integer to rows within a partition.
•RANK(): Assigns a rank to rows within a partition, with gaps in rank values for ties.
•DENSE_RANK(): Assigns ranks without gaps for tied rows.
•SUM(), AVG(), COUNT(): Aggregate functions applied to each partition

SELECT EmployeeID, Department, Salary, SUM(Salary) OVER (PARTITION BY


Department) AS TotalSalary
FROM Employees;

•SUM(Salary) calculates the total salary within each department.


•PARTITION BY Department ensures that the sum is calculated for each department, and the
result is repeated for each employee in that department

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy