Rob Gleasure robgleasure.com

Slides:



Advertisements
Similar presentations
Concepts of Database Management Seventh Edition
Advertisements

Chapter 8 Special-Purpose Languages. SQL SQL stands for "Structured Query Language". Allows the user to pose complex questions of a database. It also.
Structured Query Language Part I Chapter Three CIS 218.
1ISM - © 2010 Houman Younessi Lecture 3 Convener: Houman Younessi Information Systems Spring 2011.
SQL Intermediate Workshop Authored by Jay Mussan-Levy.
HAP 709 – Healthcare Databases SQL Data Manipulation Language (DML) Updated Fall, 2009.
Analyzing Data For Effective Decision Making Chapter 3.
INLS 623– S QL Instructor: Jason Carter. SQL SELECT DISTINCT SELECT DISTINCT column_name, column_name FROM table_name ;
CPS120: Introduction to Computer Science Lecture 19 Introduction to SQL.
Structure Query Language SQL. Database Terminology Employee ID 3 3 Last name Small First name Tony 5 5 Smith James
Using Special Operators (LIKE and IN)
Concepts of Database Management Seventh Edition
BY SATHISH SQL Basic. Introduction The language Structured English Query Language (SEQUEL) was developed by IBM Corporation, Inc., to use Codd's model.
Information Technologies and Microsoft SQL Server Day 2 by Alper Özpınar
6 1 Lecture 8: Introduction to Structured Query Language (SQL) J. S. Chou, P.E., Ph.D.
PL / SQL By Mohammed Baihan. What is PL/SQL? PL/SQL stands for Procedural Language extension of SQL. PL/SQL is a combination of SQL along with the procedural.
Concepts of Database Management Eighth Edition Chapter 3 The Relational Model 2: SQL.
In this session, you will learn to: Use functions to customize the result set Summarize and group data Objectives.
Database Fundamental & Design by A.Surasit Samaisut Copyrights : All Rights Reserved.
DATA RETRIEVAL WITH SQL Goal: To issue a database query using the SELECT command.
Lecture 8 – SQL Joins – assemble new views from existing tables INNER JOIN’s The Cartesian Product Theta Joins and Equi-joins Self Joins Natural Join.
A Guide to SQL, Eighth Edition Chapter Eight SQL Functions and Procedures.
ITEC 3220A Using and Designing Database Systems Instructor: Prof. Z. Yang Course Website: 3220a.htm
CS 111 – Nov. 8 Databases Database Management Systems (DBMS) Structured Query Language (SQL) Commitment –Please review sections 9.1 – 9.2.
IS6146 Databases for Management Information Systems Lecture 4: SQL IV – SQL Functions and Procedures Rob Gleasure robgleasure.com.
IS2803 Developing Multimedia Applications for Business (Part 2) Lecture 5: SQL I Rob Gleasure robgleasure.com.
SQL LANGUAGE TUTORIAL Prof: Dr. Shu-Ching Chen TA: Hsin-Yu Ha.
Create Stored Procedures and Functions Database Management Fundamentals LESSON 2.4.
Concepts of Database Management, Fifth Edition Chapter 3: The Relational Model 2: SQL.
COM621: Advanced Interactive Web Development Lecture 11 MySQL – Data Manipulation Language.
SQL SQL Ayshah I. Almugahwi Maryam J. Alkhalifa
How to: SQL By: Sam Loch.
Rob Gleasure robgleasure.com
Web Systems & Technologies
SQL Query Getting to the data ……..
Structured Query Language
Rob Gleasure robgleasure.com
Rob Gleasure robgleasure.com
Rob Gleasure robgleasure.com
Prof: Dr. Shu-Ching Chen TA: Hsin-Yu Ha
Lab 13 Databases and SQL.
Querying in Access Objectives: Learn how to use the Access Query Design Tool manipulate data in Access: Sorting data Aggregating Data Performing Calculations.
Instructor: Craig Duckett Lecture 09: Tuesday, April 25th, 2017
PL/SQL LANGUAGE MULITPLE CHOICE QUESTION SET-1
The Database Exercises Fall, 2009.
Structured Query Language – The Basics
Prof: Dr. Shu-Ching Chen TA: Yimin Yang
Structured Query Language
MENAMPILKAN DATA DARI SATU TABEL (Chap 2)
Prof: Dr. Shu-Ching Chen TA: Hsin-Yu Ha
Chapter # 7 Introduction to Structured Query Language (SQL) Part II.
SQL LANGUAGE and Relational Data Model TUTORIAL
Chapter 4 Summary Query.
Prof: Dr. Shu-Ching Chen TA: Haiman Tian
Introduction To Structured Query Language (SQL)
Copyright © 2012 Pearson Education, Inc. Publishing as Prentice Hall
Database systems Lecture 3 – SQL + CRUD
Access: SQL Participation Project
Rob Gleasure robgleasure.com
Structured Query Language
Rob Gleasure robgleasure.com
Introduction To Structured Query Language (SQL)
Section 4 - Sorting/Functions
Rob Gleasure robgleasure.com
MIS2502: Data Analytics SQL – Getting Information Out of a Database Part 1: Basic Queries Aaron Zhi Cheng
Shelly Cashman: Microsoft Access 2016
Chapter Name SQL: Data Manipulation
Grouping and Aggregating Data
Group Operations Part IV.
Presentation transcript:

Rob Gleasure R.Gleasure@ucc.ie robgleasure.com IS6246 Databases for Management Information Systems Lecture 4: SQL IV – SQL Functions and Procedures Rob Gleasure R.Gleasure@ucc.ie robgleasure.com

IS6246 Today’s session SQL Functions SQL Aggregate Functions SQL Scalar Functions Creating Procedures in Oracle Exercise

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

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()

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; https://www.w3schools.com/sql/trysql.asp?filename=trysql_select_avg

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; https://www.w3schools.com/sql/trysql.asp?filename=trysql_select_sum

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; https://www.w3schools.com/sql/trysql.asp?filename=trysql_select_count Note null values will not be included but duplicates will unless DISTINCT is added, e.g. SELECT COUNT(DISTINCT CustomerID) AS NumberOfCustomer FROM Orders;

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…

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;

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; https://www.w3schools.com/sql/trysql.asp?filename=trysql_select_top&ss=-1

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; https://www.w3schools.com/sql/trysql.asp?filename=trysql_select_min

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; https://www.w3schools.com/sql/trysql.asp?filename=trysql_select_groupby

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; https://www.w3schools.com/sql/trysql.asp?filename=trysql_select_having

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()

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; https://www.w3schools.com/sql/trymysql.asp?filename=trysql_func_mysql_ucase2

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; https://www.w3schools.com/sql/func_sqlserver_len.asp

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;; https://www.w3schools.com/sql/trysql.asp?filename=trysql_func_mysql_round3

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 '(___)%'; https://www.w3schools.com/sql/trymysql.asp?filename=trysql_func_mysql_mid2

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; https://www.w3schools.com/sql/trymysql.asp?filename=trysql_func_mysql_now Kind of counterintuitive this isn’t an aggregate variable

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

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 */ /

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 := 12345678; /* … or from SQL queries*/ SELECT MAX(EmployeeID) AS EmployeeID FROM Employees; END; / Every line ends with a semi-colon

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 < 10000000) THEN / * Take some action */ ELSE / * Take some other action */ END IF; END; /

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; /

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

Obviously Just Scratching the Surface Here… There’s a great tutorial at Great tutorial at http://plsql-tutorial.com, please have a look through it at your leisure

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)?

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