IS6146 Databases for Management Information Systems Lecture 4: SQL IV – SQL Functions and Procedures Rob Gleasure robgleasure.com.

Slides:



Advertisements
Similar presentations
AN INTRODUCTION TO PL/SQL Mehdi Azarmi 1. Introduction PL/SQL is Oracle's procedural language extension to SQL, the non-procedural relational database.
Advertisements

Copyright © by Royal Institute of Information Technology Introduction To Structured Query Language (SQL) 1.
Fundamentals, Design, and Implementation, 9/e COS 346 Day 11.
Chapter 8 Special-Purpose Languages. SQL SQL stands for "Structured Query Language". Allows the user to pose complex questions of a database. It also.
Introduction to Structured Query Language (SQL)
Tools of the trade TSQL CIS 407. SQL Server Tools Books on line! Don’t use sql server authentication –Use windows authentication (safer) for developer.
Structured Query Language Part I Chapter Three CIS 218.
Introduction to Structured Query Language (SQL)
Concepts of Database Management Sixth Edition
1ISM - © 2010 Houman Younessi Lecture 3 Convener: Houman Younessi Information Systems Spring 2011.
SQL Intermediate Workshop Authored by Jay Mussan-Levy.
Microsoft Access 2010 Chapter 7 Using SQL.
Basic Commands Prepared By: RAHUL PATEL. Create Table Command CREATE TABLE CUSTOMER ( CustomerId int IDENTITY(1,1) PRIMARY KEY, CustomerNumber int NOT.
CPS120: Introduction to Computer Science Information Systems: Database Management Nell Dale John Lewis.
CS&E 1111 AcQueries Querying in Access Sorting data Aggregating Data Performing Calculations Objectives: Learn how to use the Access Query Design Tool.
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.
Concepts of Database Management Seventh Edition Chapter 3 The Relational Model 2: SQL.
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.
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.
MySQL Tutorial. Databases A database is a container that groups together a series of tables within a single structure Each database can contain 1 or more.
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.
Web Systems & Technologies
SQL Query Getting to the data ……..
Structured Query Language
Rob Gleasure robgleasure.com
Rob Gleasure robgleasure.com
Prof: Dr. Shu-Ching Chen TA: Hsin-Yu Ha
Lab 13 Databases and SQL.
PL/SQL LANGUAGE MULITPLE CHOICE QUESTION SET-1
Structured Query Language – The Basics
Prof: Dr. Shu-Ching Chen TA: Hsin-Yu Ha
Prof: Dr. Shu-Ching Chen TA: Yimin Yang
MENAMPILKAN DATA DARI SATU TABEL (Chap 2)
Prof: Dr. Shu-Ching Chen TA: Hsin-Yu Ha
Rob Gleasure robgleasure.com
SQL LANGUAGE and Relational Data Model TUTORIAL
Chapter 4 Summary Query.
Prof: Dr. Shu-Ching Chen TA: Haiman Tian
Copyright © 2012 Pearson Education, Inc. Publishing as Prentice Hall
Database systems Lecture 3 – SQL + CRUD
Rob Gleasure robgleasure.com
Rob Gleasure robgleasure.com
Introduction To Structured Query Language (SQL)
Query Functions.
Section 4 - Sorting/Functions
Rob Gleasure robgleasure.com
Chapter Name SQL: Data Manipulation
Presentation transcript:

IS6146 Databases for Management Information Systems Lecture 4: SQL IV – SQL Functions and Procedures Rob Gleasure robgleasure.com

IS6146 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 SQL provides us with a set of inbuilt functions for common needs  Aggregate functions return a value calculated from data in a column, e.g. AVG (), COUNT(), FIRST(), LAST(), MAX(), MIN(), SUM()  Scalar functions return an adapted value for each column e.g. UCASE(), LCASE(), MID(), LEN(), ROUND(), and NOW()

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;

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; nt_all 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; &ss=-1 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 E.g. SELECT CustomerName FROM Customers WHERE ROWNUM <=1 ORDER BY CustomerID DESC;

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;

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

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

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; e&ss=-1

MID() 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 '(___)%'; &ss=-1 The first character = 1 Specifying the length is optional

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; ss=-1

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

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; &ss=-1

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

Iterative Statements in PL/SQL DECLARE EmployeeID 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; 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 please have a look through it at your leisure

Exercise Consider the following problems, what queries best solve them? 1. We want to select the average Quantity for each ProductID in the OrderDetails table? 2. We want to create the same result but with the ProductName from the Products table instead of the ProductID (Hint – use LEFT JOIN)?

Exercise 3. We want to create the same result but with the AverageQuantity rounded to two decimal places? 4. We want the same result but displayed according to the first three letters of the ProductName in upper case, e.g. CompanyAbbrevAverageQuantity ALI ANI 40