Download presentation
Presentation is loading. Please wait.
1
Rob Gleasure R.Gleasure@ucc.ie robgleasure.com
IS6246 Databases for Management Information Systems Lecture 4: SQL IV – SQL Functions and Procedures Rob Gleasure robgleasure.com
2
IS6246 Today’s session SQL Functions SQL Aggregate Functions
SQL Scalar Functions Creating Procedures in Oracle Exercise
3
SQL Functions Sometimes there are complex tasks or calculations we will need to perform again and again Rather than spell them out each time, we refer to these functions by name
4
Aggregate Functions Aggregate functions return a value calculated from data in one or more columns This means they return a single value, often in a single row e.g. AVG (), COUNT(), FIRST(), LAST(), MAX(), MIN(), SUM()
5
AVG() Returns the average value of a numeric column, either directly or stored in a variable Syntax: SELECT AVG(col_name) AS var_name FROM table_name E.g. SELECT AVG(Price) AS PriceAverage FROM Products;
6
SUM() Returns the sum of values in a numeric column, either directly or stored in a variable Syntax: SELECT SUM(col_name) AS var_name FROM table_name E.g. SELECT SUM(Price) AS PriceSum FROM Products;
7
COUNT() Returns the number of rows that matches a specified criteria
Syntax: SELECT COUNT(col_name) AS var_name FROM table_name E.g. SELECT COUNT(CustomerID) AS NumberOfCustomer FROM Orders; Note null values will not be included but duplicates will unless DISTINCT is added, e.g. SELECT COUNT(DISTINCT CustomerID) AS NumberOfCustomer FROM Orders;
8
FIRST() and LAST() Returns the returns the first and last value of the selected column, respectively Syntax: SELECT FIRST(Col_Name) AS Var_Name FROM Table_Name; E.g. SELECT FIRST(CustomerName) AS FirstCustomer FROM Customers; Unfortunately this only works for MS Access…
9
First() and Last() Oracle Workarounds
To get the first record in Oracle, we use the following Syntax: SELECT Col_Name FROM Table_Name WHERE ROWNUM <=1; E.g. SELECT CustomerName FROM Customers WHERE ROWNUM <=1; We can get the last by reverse ordering the records SELECT CustomerName FROM Customers WHERE ROWNUM <=1 ORDER BY CustomerID DESC;
10
TOP and ROWNUM Let you return the first n rows, or some specific number row E.g. SELECT TOP 3 * FROM Customers WHERE Country='Germany'; SELECT * FROM Customers WHERE ROWNUM <= 3;
11
MAX() and MIN() Returns the largest or smallest value of the selected column, respectively Syntax: SELECT MAX(col_name) AS var_name FROM table_name E.g. SELECT MAX(Price) AS HighestPrice FROM Products;
12
GROUP BY Sometimes we want to retrieve some computed value (average, min, max, etc.) but we want to retrieve these values in groups The syntax for these queries uses GROUP BY, as follows SELECT column_name, aggregate_function(column_name2) FROM table_name WHERE column_name condition GROUP BY column_name;
13
HAVING The WHERE condition can’t be used with aggregate functions, so we use a different term HAVING E.g. SELECT column_name, aggregate_function(column_name) FROM table_name WHERE column_name operator value GROUP BY column_name HAVING aggregate_function(column_name) condition;
14
Scalar Functions Aggregate functions return multiple values calculated from data in one or more columns This means they return a separate value for each row on which they are called, i.e. the same number of rows in returned by the query e.g. UCASE(), LCASE(), MID(), LEN(), ROUND(), and NOW()
15
UCASE() and LCASE() Returns the value of a field in upper or lowercase, respectively Syntax: SELECT UCASE(column_name) FROM table_name; E.g. SELECT UCASE(SupplierName) AS UC_SNm FROM Suppliers;
16
LEN() Returns the returns the length of the value in a text field
Syntax: SELECT LEN (column_name) FROM table_name; E.g. SELECT CustomerName,City, LEN(PostalCode) as LengthOfPostCode FROM Customers;
17
ROUND() Returns a numeric field rounded to the number of decimals specified Syntax: SELECT ROUND(column_name,decimals) FROM table_name; E.g. SELECT ProductName, ROUND(Price,0) AS RoundedPrice FROM Products;;
18
MID() Returns the characters within a text field Syntax: E.g.
The first character = 1 Specifying the length is optional Returns the characters within a text field Syntax: SELECT MID(col_name,start,length) AS var_nm FROM table_name; E.g. SELECT MID(Phone,2,3) AS ThreeDigitAreaCode FROM Suppliers WHERE Phone LIKE '(___)%';
19
NOW() Returns the current time and data in the format
Month/Day/Year Hour:Minute:Second AM/PM Syntax: SELECT NOW() FROM table_name; E.g. SELECT ShipperName, NOW() AS Shippers11Feb FROM Shippers; Kind of counterintuitive this isn’t an aggregate variable
20
Creating New Procedures
As you might imagine, we can also create new functions (called procedures) where we have recurring actions that are not captured in the standard SQL functions This requires the use of programming languages that extend SQL to allow programmatic necessities such as Variables and constants Loops and conditions Triggers and exceptions In MS Access, the language used is T-SQL In Oracle, the language used is PL/SQL
21
Basic Structure of PL/SQL
/* These things on either side of this text indicate comments, meaning all this text is ignored */ DECLARE /* Variables are declared in here */ BEGIN /* SQL queries may be called here, as may other in- built functions such as printing things to the screen or combining or manipulating data */ END; /* That backslash after this in the bottom-left indicates to execute the block */ /
22
Variables in PL/SQL DECLARE
/* Variables are declared by stating a name, a type, and optionally a size, e.g. below */ EmployeeID number(8); BEGIN /* Values may be set for variables either directly */ EmployeeID := ; /* … or from SQL queries*/ SELECT MAX(EmployeeID) AS EmployeeID FROM Employees; END; / Every line ends with a semi-colon
23
Conditional Statements in PL/SQL
DECLARE EmployeeID number(8); BEGIN SELECT MAX(EmployeeID) AS EmployeeID FROM Employees; /* Based on some conditions, we may choose to take alternative actions using IF/ELSE IF statements, e.g. below*/ IF (EmployeeID < ) THEN / * Take some action */ ELSE / * Take some other action */ END IF; END; /
24
Iterative Statements in PL/SQL
DECLARE EmployeeID_check number(8); Counter number(2); BEGIN Counter := 0; /* We may also want to repeat some action until some condition is met, e.g. below */ WHILE (Counter < 20) LOOP SELECT MAX(EmployeeID) AS EmployeeID FROM Employees; DELETE FROM Employees WHERE EmployeeID = EmployeeID_check; Counter := Counter + 1; END LOOP; END; /
25
Triggers in PL/SQL /* We can also triggers things cur on specific actions, e.g. below */ CREATE TRIGGER deleted_employee_trigger BEFORE DELETE ON Employees; FOR EACH ROW BEGIN /* This query will fire when an employee is deleted and save their ID and the date they’re deleted into a backup table */ INSERT INTO Deleted_Employees (EmployeeID,DateDeleted) VALUES (:old.EmployeeID, NOW()); END; / This is the way we refer to the previous values in the record causing the trigger
26
Obviously Just Scratching the Surface Here…
There’s a great tutorial at Great tutorial at please have a look through it at your leisure
27
Exercise Consider the following problems, what queries best solve them? We want to select the average Quantity for each ProductID in the OrderDetails table? We want to create the same result but with the ProductName from the Products table instead of the ProductID (Hint – use LEFT JOIN)?
28
Exercise We want to create the same result but with the AverageQuantity rounded to two decimal places? We want the same result but displayed according to the first three letters of the ProductName in upper case, e.g. CompanyAbbrev AverageQuantity ALI 30.09 ANI 40
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.