SQL Training ORACLE SQL Functions. Confidential & Proprietary Copyright © 2009 Cardinal Directions, Inc. Lesson Objectives Write SQL Statements using:

Slides:



Advertisements
Similar presentations
Structured Query Language (SQL)
Advertisements

Copyright  Oracle Corporation, All rights reserved. 2 Single-Row Functions.
Objectives After completing this lesson, you should be able to do the following: Describe various types of conversion functions that are available in.
Copyright © 2007, Oracle. All rights reserved Using Single-Row Functions to Customize Output Modified: October 21, 2014.
Subquery. Subquery or Inner query or Nested query A subquery is a query within another query. The outer query is called as main query and The inner query.
Chapter 11 Group Functions
Copyright © by Royal Institute of Information Technology Introduction To Structured Query Language (SQL) 1.
Databases Lab 5 Further Select Statements. Functions in SQL There are many types of functions provided. The ones that are used most are: –Date and Time.
Introduction to Oracle9i: SQL1 Selected Single-Row Functions.
Databases Week 1, lab 2 Simple selects. About the environment We are using SQL Server for the moment. The server we are using is: –Cian.student.comp.dit.ie.
Chapter 3: Using SQL Queries to Insert, Update, Delete, and View Data
Relational Databases.  So far we have looked at retrieving data from multiple tables and the different ways to join the relations/tables that are required.
Databases Tutorial 2 Further Select Statements. Objectives for Week Data types Sort retrieved data Formatting output.
Sorting data and Other selection Techniques Ordering data results Allows us to view our data in a more meaningful way. Rather than just a list of raw.
DATABASES AND SQL. Introduction Relation: Relation means table(data is arranged in rows and columns) Domain : A domain is a pool of values appearing in.
Single-Row Functions. SQL Functions Functions are a very powerful feature of SQL and can be used to do the following: Perform calculations on data Modify.
3-1 Copyright  Oracle Corporation, All rights reserved. SQL Functions FunctionInput arg 1 arg 2 arg n Function performs action OutputResultvalue.
Using SQL Queries to Insert, Update, Delete, and View Data Date Retrieval from a single table & Calculations © Abdou Illia MIS Spring 2015.
SQL Training SQL Statements – Part 1. Confidential & Proprietary Copyright © 2009 Cardinal Directions, Inc. Lesson Objectives Explain the role of SQL.
Oracle FUNCTIONS. Comment ScreenShot (in 10g) General Example of null Foreign Key: create table deptcs( deptno NUMBER(4) primary key, hiredate DATE,
Chapter 10 Selected Single-Row Functions Oracle 10g: SQL.
Chapter 5 Selected Single-Row Functions. Chapter Objectives  Use the UPPER, LOWER, and INITCAP functions to change the case of field values and character.
SINGLE-ROW FUNCTIONS Lecture 9. SQL Functions Functions are very powerful feature of SQL and can be used to do the following:  Perform a calculation.
Functions Oracle Labs 5 & 6. 2/3/2005Adapted from Introduction to Oracle: SQL and PL/SQL 2 SQL Functions Function arg n arg 2 arg 1. Input Resulting Value.
MIT5314: Database ApplicationsSlide # 1 More SQL Dr. Peeter KirsFall, 2003 More SQL (With a little more on Database Design)
SQL: Data Manipulation Presented by Mary Choi For CS157B Dr. Sin Min Lee.
SQL Training Insert, Update & Delete. Insert, Update, Delete.
Single Row Functions Week 2. Objectives –Describe types of single row functions in SQL –Describe and use character, number, date, general and conversion.
Oracle 11g: SQL Chapter 10 Selected Single-Row Functions.
SQL Oracle PL/SQL. Select SELECT column1, column2,...columnN FROM table_name WHERE condition; SELECT column1, column2,...columnN FROM table_name WHERE.
Chapter 3 Selected Single-Row Functions and Advanced DML & DDL.
5. Simple SQL using Oracle1 Simple SQL using Oracle 5. Working with Tables: Data management and Retrieval 6. Working with Tables: Functions and Grouping.
Chapter 12: String Manipulation Introduction to Programming with C++ Fourth Edition.
EXPRESSION Transformation. Introduction ►Transformations help to transform the source data according to the requirements of target system and it ensures.
In this session, you will learn to: Use functions to customize the result set Summarize and group data Objectives.
Advanced SELECT Queries CS 146. Review: Retrieving Data From a Single Table Syntax: Limitation: Retrieves "raw" data Note the default formats… SELECT.
SQL Training Join Statements. Joining Tables Confidential & Proprietary Copyright © 2009 Cardinal Directions, Inc. Relationships (Cardinalities) Most.
IFS Intro to Data Management Chapter 5 Getting More Than Simple Columns.
Conversion Functions.
Single Row Functions. Objectives –Use character, number, and date functions –Use conversion functions –Describe types of single row functions in SQL.
Queries SELECT [DISTINCT] FROM ( { }| ),... [WHERE ] [GROUP BY [HAVING ]] [ORDER BY [ ],...]
Retrieving Data Using the SQL SELECT Statement. Objectives After completing this lesson, you should be able to do the following: – List the capabilities.
5. Simple SQL using Oracle1 Simple SQL using Oracle 5. Working with Tables: Data management and Retrieval 6. Working with Tables: Functions and Grouping.
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.
SQL Functions. SQL functions are built into Oracle Database and are available for use in various appropriate SQL statements. These functions are use full.
SQL Aggregation Oracle and ANSI Standard SQL Lecture 9.
Single-Table Queries 2: Advanced Topics CS 320. Review: Retrieving Data From a Single Table Syntax: Limitation: Retrieves "raw" data SELECT field1, field2,
Academic Year 2015 Autumn. MODULE CC2006NI: Data Modelling and Database Systems Academic Year 2015 Autumn.
Oracle & SQL. Oracle Data Types Character Data Types: Char(2) Varchar (20) Clob: large character string as long as 4GB Bolb and bfile: large amount of.
Sorting data and Other selection Techniques Ordering data results Allows us to view our data in a more meaningful way. Rather than just a list of raw.
Lecture3b - Chapter 3: Using SQL Queries to Insert, Update, Delete, and View Data Guide to Oracle 10g ITBIS373 Database Development.
3 Copyright © 2004, Oracle. All rights reserved. Using Single-Row Functions to Customize Output.
Database Design lecture 3_2 Slide 1 Database Design Lecture 3_2 Data Manipulation in SQL Simple SQL queries References: Text Chapter 8 Oracle SQL Manual.
Retrieving Information Pertemuan 3 Matakuliah: T0413/Current Popular IT II Tahun: 2007.
1 ORACLE I 3 – SQL 1 Salim Phone: YM: talim_bansal.
Single Row Functions Part I Week 2. Objectives –Describe types of single row functions in SQL –Describe and use character, number and date SQL functions.
SQL Query Getting to the data ……..
In this session, you will learn to:
Chapter 10 Selected Single-Row Functions Oracle 10g: SQL
Computations Done on table data
Using Single-Row Functions to Customize Output
Chapter # 7 Introduction to Structured Query Language (SQL) Part II.
Chapter 4 Summary Query.
Aggregating Data Using Group Functions
Copyright © 2012 Pearson Education, Inc. Publishing as Prentice Hall
Section 4 - Sorting/Functions
Lecture 5 SQL FUNCTIONS.
Trainer: Bach Ngoc Toan– TEDU Website:
Introduction to SQL Server and the Structure Query Language
Presentation transcript:

SQL Training ORACLE SQL Functions

Confidential & Proprietary Copyright © 2009 Cardinal Directions, Inc. Lesson Objectives Write SQL Statements using: – Aggregate Functions (max, min, avg) – Common CHAR and DATE functions Page 2 At the end of this section you will be able to:

Aggregate Functions

Confidential & Proprietary Copyright © 2009 Cardinal Directions, Inc. Select – Aggregate Functions The following aggregate functions can be applied to multiple values retrieved from a table. FunctionPurpose MINYields the minimum value in a column MAXYields the maximum value in a column AVGComputes the average value for a column SUMComputes the total value for a column COUNTLists the number of rows in a query, or lists the number of distinct column values Page 4

Group By and Having

Confidential & Proprietary Copyright © 2009 Cardinal Directions, Inc. Group By Page 6 Show the number of components used to build ProductCode HG C (ProductID = 15) SELECT Product.ProductID, Product.ProductDescription, Sum(RequiredQTY) as NumComponents From Product, Manifest Where Product.ProductID = Manifest.ProductID and Product.ProductID = 15 Group By Product.ProductID, Product.ProductDescription; PRODUCTIDPRODUCTDESCRIPTIONNUMCOMPONENTS 15HomeGen Natural Gas, 240v 60Hz43 All fields in the SELECT clause that are not part of an aggregate function must be included in the GROUP BY clause.

Confidential & Proprietary Copyright © 2009 Cardinal Directions, Inc. Group By Problem: How many vendors are in each country? Show by Country and Region. SELECT c.countryname, r.regionname, count(vendorid) as NbrVendors FROM country c, region r, province p, vendor v WHERE c.countryid = r.countryid and r.regionid = p.regionid and p.provinceid = v.provinceid GROUP BY ____________ ORDER BY 1,2 desc; What goes in the GROUP BY clause? Page 7 ?

Confidential & Proprietary Copyright © 2009 Cardinal Directions, Inc. Group By Problem: How many vendors are in each country? Show by Country and Region. SELECT c.countryname, r.regionname, count(vendorid) as NbrVendors FROM country c, region r, province p, vendor v WHERE c.countryid = r.countryid and r.regionid = p.regionid and p.provinceid = v.provinceid GROUP BY c.countryname, r.regionname ORDER BY 1,2 desc; Page 8

Confidential & Proprietary Copyright © 2009 Cardinal Directions, Inc. Group By Problem: What is the average, min and max hourly rate by user location? SELECT userLocation, avg(hourlyRate) as Avg_Hourly_Rate, min(hourlyRate) as Min_Hourly_Rate, max(hourlyRate) as Max_Hourly_Rate FROM User GROUP BY userLocation ORDER BY avg(hourlyRate); USERLOCATIONAVG_HOURLY_RATEMIN_HOURLY_RATEMAX_HOURLY_RATE Boston San Francisco Bangkok Page 9

Confidential & Proprietary Copyright © 2009 Cardinal Directions, Inc. Group By and Having Problem: Retrieve all products containing less than 40 components. SELECT Product.PRODUCTID, Sum(RequiredQTY) AS NumComponents FROM Product, Manifest WHERE Product.ProductID = Manifest.ProductID GROUP BY Product.PRODUCTID HAVING Sum(RequiredQTY) < 40; WHERE  Filters out Rows that don’t satisfy the search conditions. HAVING  Filters out Groups that don’t satisfy the search conditions. PRODUCT ID NUMCOMPONE NTS rows selected. Page 10

Confidential & Proprietary Copyright © 2009 Cardinal Directions, Inc. Group By and Having Problem: Which customers have more than 9 users? SELECTct.customerTypeDescription as CustomerType, c.customerName as Customer, count(*) as NbrUsers FROM CustomerType ct, Customer c, Users u WHERE ct.customertypeid = c.customertypeid and c.customerid = u.customerid GROUP BY ______________________ HAVING ______________________ ORDER BY 1,3 desc; 12 Rows CUSTOMERTYPECUSTOMERNBRUSERS ConsumerThe Coca-Cola Company31 ConsumerKellogg Co.28 ConsumerKraft Foods Inc.20 ConsumerProctor & Gamble Company20 ConsumerUnilever plc15 MediaGMR Marketing15 MediaVML12 MediaProximity Worldwide12 MediaResolution Media11 MediaLatinWorks11 MediaBurson-Marsteller10 MediaChime Communications10 Page 11

Useful Functions

Confidential & Proprietary Copyright © 2009 Cardinal Directions, Inc. Arithmetic Expressions Problem: Multiply the vendor price by 1.05 where ComponentID < 10 and VendorID = 1 VENDORIDCOMPONENTIDVENDORPRICENEWPRICE rows selected. SELECT VendorID, ComponentID, VendorPrice, VendorPrice * 1.05 as NewPrice From VendorComponent Where VendorID =1 and ComponentID < 10; Page 13

Confidential & Proprietary Copyright © 2009 Cardinal Directions, Inc. Select – Scalar Functions A scalar row function returns a single result row for every row of a queried table or view. Single row functions can appear in select lists (provided the SELECT statement does not contain a GROUP BY clause) and WHERE clauses. Number Functions: Number functions accept numeric input and return numeric values. ROUND Syntax ROUND(n[,m]) Returns n rounded to m places right of the decimal point. If m is omitted, to 0 places. m can be negative to round off digits left of the decimal point. m must be an integer. SELECT ComponentID, Avg(VendorPrice) As Avg, ROUND(Avg(VendorPrice)) As Round FROM VendorComponent Group By ComponentID Order By ComponentID; COMPONENTIDAVGROUND rows selected. Note: not all rows are displayed in this report due to size constraints of this page. Page 14

Confidential & Proprietary Copyright © 2009 Cardinal Directions, Inc. Some Useful Scalar Functions ABSSyntax ABS(n) Returns the absolute value of n CEILSyntax CEIL(n) Returns smallest integer greater than or equal to n. FLOORSyntax FLOOR(n) Returns largest integer equal to or less than n. ROUNDSyntax ROUND(n[,m]) Returns n rounded to m places right of the decimal point. TRUNCSyntax TRUNC(n[,m])Returns n truncated to m decimal places. Page 15

Confidential & Proprietary Copyright © 2009 Cardinal Directions, Inc. Some Useful Character Functions SUBSTRSyntax SUBSTR(char, m [,n]) Returns a portion of char, beginning at character m, n characters long. If m is 0, it is treated as 1. If m is positive, Oracle counts from the beginning of char to find the first character. If m is negative, Oracle counts backwards from the end of char. If n is omitted, Oracle returns all characters to the end of char. If n is less than 1, a null is returned. Select substr(VendorFirstName,1,1) || ', ' || VendorLastName from Vendor; UPPERSyntax UPPER(char)Returns char, with all letters uppercase. Select * from Vendor where Upper(City) = ‘BOSTON’; Page 16

Confidential & Proprietary Copyright © 2009 Cardinal Directions, Inc. Some Useful Character Functions LENGTHSyntax LENGTH(char)Returns the length of char in characters. If char has datatype CHAR, the length includes all trailing blanks. If char is null, this function returns null. LOWERSyntax LOWER(char)Returns char, with all letters lowercase. The return value has the same datatype as the argument char (CHAR or VARCHAR2). LTRIM Syntax LTRIM(char [,set] Removes characters from the left of char, with all the leftmost characters that appear in set removed. Set defaults to a single blank. Oracle begins scanning char from its first character and removes all characters that appear in set until reaching a character not in set and then returns the result. REPLACE Syntax REPLACE(char, search_string[,replacement_string]) Returns char with every occurrence of search_string replaced with replacement_string. If replacement_string is omitted or null, all occurrences of search_string are removed. If search_string is null, char is returned. Page 17

Confidential & Proprietary Copyright © 2009 Cardinal Directions, Inc. TO_CHAR Function The TO_CHAR function converts a number or date to a string. The syntax for the to_char function is: to_char(value,[format_mask]). The value field can be either a number or a date. Example – Numbers: to_char( ,’9999.9’)would return ‘1210.7’ to_char( ,’ ’)would return ‘ ’ to_char( ,’$9,999.99’)would return ‘$1,210.73’ Example – Dates: to_char(actualEndDate,’mm/dd/yyyy’)would return ‘05/17/2009’ to_char(actualEndDate,’Month DD, YYYY’)would return ‘May 17, 2009’ to_char(actualEndDate,’YYYY’)would return ‘2009’ to_char(actualEndDate,’MM’)would return ‘05’ to_char(actualEndDate,’DD’)would return ‘17’ to_char(actualEndDate,’D’)would return ‘1’ or Sunday to_char(actualEndDate,’SSSSS’)would return ‘30370’ Page 18

Confidential & Proprietary Copyright © 2009 Cardinal Directions, Inc. Date Conversion Examples SELECT factoryid, to_char(actualEndDate,'mm/dd/yyyy') as ShortDate, to_char(actualEndDate,'Month DD, YYYY') as LongDate, to_char(actualEndDate,'YYYY') as Year, to_char(actualEndDate,'MM') as Month, to_char(actualEndDate,'DD') as Day, to_char(actualEndDate,'D') as DayOfWeek, to_char(actualEndDate,'SSSSS') as SecondsAfterMidnight, cast(actualEndDate as TimeStamp) as Timestamp FROM factory WHERE to_char(actualEndDate,'MM') = 5 and to_char(actualEndDate,'DD') = 17 and to_char(actualEndDate,'YYYY') = 2009; FACTORYIDSHORTDATELONGDATEYEARMONTHDAYDAYOFWEEKSECONDSAFTERMIDNIGHTTIMESTAMP /17/ May MAY AM /17/ May MAY AM /17/ May MAY AM /17/ May MAY AM /17/ May MAY AM Page 19

Confidential & Proprietary Copyright © 2009 Cardinal Directions, Inc. Date Conversion Parameters ParameterExplanationParameterExplanation YEARYear, spelled outW Week of month (1-5) where week 1 starts on the first day of the month and ends on the seventh. YYYY4-digit yearIW Week of year (1-52 or 1-53) based on the ISO standard. YYY Last 3, 2, or 1 digit(s) of year. DDay of week (1-7). YYDAYName of day. YDDDay of month (1-31). IYY Last 3, 2, or 1 digit(s) of ISO year. DDDDay of year (1-366). IYDYAbbreviated name of day. IJ Julian day; the number of days since January 1, 4712 BC. IYYY4-digit year based on the ISO standardHHHour of day (1-12). QQuarter of year (1, 2, 3, 4; JAN-MAR = 1).HH12Hour of day (1-12). MMMonth (01-12; JAN = 01).HH24Hour of day (0-23). MONAbbreviated name of month.MIMinute (0-59). MONTH Name of month, padded with blanks to length of 9 characters. SSSecond (0-59). RMRoman numeral month (I-XII; JAN = I).SSSSSSeconds past midnight ( ). WW Week of year (1-53) where week 1 starts on the first day of the year and continues to the seventh day of the year. FFFractional seconds. ISO date example, 2006-W52-7 (or in compact form 2006W527) is the Sunday of the 52nd week of Page 20

Confidential & Proprietary Copyright © 2009 Cardinal Directions, Inc. Working with Dates SELECT incidentId, openDate FROM Incident WHERE OpenDate Between '11/1/2008' and '11/5/2008'; Problem: What incidents were opened Nov 1 and Nov 5, 2008? Page 21

Confidential & Proprietary Copyright © 2009 Cardinal Directions, Inc. Working with Dates SELECT incidentID, openDate FROM Incident WHERE openDate Between '1-Nov-2008' and '5-Nov-2008'; Problem: What incidents were opened between Nov 1 and Nov 5, 2008? But what if the dates aren’t in this format? 53 Rows INCIDENTIDOPENDATE 502-Nov Nov Nov Nov Nov Nov Nov Nov Nov Page 22

Confidential & Proprietary Copyright © 2009 Cardinal Directions, Inc. Working with Dates SELECT incidentID, openDate FROM Incident WHERE openDate Between to_date('11/1/2008', 'MM/DD/YYYY') and to_date('11/5/2008','MM/DD/YYYY'); Problem: What incidents were opened between Nov 1 and Nov 5, 2008? 53 Rows INCIDENTIDOPENDATE 502-Nov Nov Nov Nov Nov Nov Nov Nov Nov In Oracle, the to_date function converts a string to a date Page 23

Confidential & Proprietary Copyright © 2009 Cardinal Directions, Inc. Date Arithmetic Problem: How many minutes did Nielsen engineers work on incidents 1-10? SELECT i.incidentID, round(sum(ia.checkout - ia.checkin) * 1440) as actualTimeMinutes FROM IncidentAction ia, Incident i WHERE i.incidentID = ia.incidentID and i.incidentID between 1 and 10 GROUP BY i.incidentID; INCIDENTIDACTUALTIMEMINUTES Note: Date1 – Date2 = DaysDiff Page 24

Workshop

Confidential & Proprietary Copyright © 2009 Cardinal Directions, Inc. Individual SQL Workshop 2 – Starter DB Page 26

Confidential & Proprietary Copyright © 2009 Cardinal Directions, Inc. 8 rows selected. Problem 1 – Aggregate Functions Problem: List all the Regions in the United States (CountryID = 1). Count the number of Provinces in each Region. Order by RegionName. COUNTRYNAMEREGIONNAMENBRPROVINCES United StatesAlaska2 United StatesMidatlantic8 United StatesMidwest12 United StatesMountain4 United StatesNortheast8 United StatesNorthwest2 United StatesSoutheast8 United StatesSouthwest6 Page 27

Confidential & Proprietary Copyright © 2009 Cardinal Directions, Inc. 12 rows selected. Problem 2 – Aggregate Functions Problem: For all Products whose ProductID less than or equal to 12, calculate the Cost of the Components, and their Margin Amount (Product Price – Component Cost). Order the Report by MarginAmt in descending sequence. Note: In the Manifest Table is a field named RequiredQty. This field contains the number of components required to build the homegen. For example, if the component was a wheel, then RequiredQty for the wheel component would equal 4. Also in the VendorComponent table is the field VendorCost. VendorCost contains price we pay the Vendor for each component. PRODUCTIDPRODUCTDESCRIPTIONFUELSOURCEDESCRIPTIONPRODUCTPRICECOMPONENTCOSTMARGINAMT 4HomeGen LP Gas, 110v 50HzLP Gas HomeGen Natural Gas, 220v 50HzNatural Gas HomeGen Propane, 240v 60HzPropane HomeGen Butane, 240v 60HzButane HomeGen Propane, 110v 50HzPropane HomeGen LP Gas, 240v 60HzLP Gas HomeGen Natural Gas, 110v 50HzNatural Gas HomeGen Butane, 110v 50HzButane HomeGen Natural Gas, 240v 60HzNatural Gas HomeGen Propane, 220v 50HzPropane HomeGen LP Gas, 220v 50HzLP Gas HomeGen Butane, 220v 50HzButane Page 28

Confidential & Proprietary Copyright © 2009 Cardinal Directions, Inc. Problem 3 – Select SUBSTR and Concatenation Problem: Select all vendors in the Vendor table where the city starts with the character ‘B’. In the report, concatenate the first character of the first name of the vendor with their last name. Order the report in ascending sequence on the VendorID column. 5 rows selected. VENDORIDNAMECITYPROVINCEABBREVIATIONCOUNTRYNAMECURRENCYNAME 3W, MartinBelpreOHUnited StatesUS Dollar 8R, RascoeBrooklynNYUnited StatesUS Dollar 9R, BenoitBronxvilleNYUnited StatesUS Dollar 12F, BarbutoBostonMAUnited StatesUS Dollar 20A, PfeifferBirminghamALUnited StatesUS Dollar Page 29

Confidential & Proprietary Copyright © 2009 Cardinal Directions, Inc. Problem 4 – Select using GROUP BY and Column Functions Problem: Group all PowerRating(s) represented in the Product column. Include a Count of the number of rows in each grouping. Calculate the Average, Maximum, Minimum ProductPrice column. Include Order the report in ascending sequence by PowerRating. Note: To arrive at the “proper” AVGPRICE, you will have to round your average. 7 rows selected. POWERRATINGCOUNTAVGPRICEMINPRICEMAXPRICE Page 30

Confidential & Proprietary Copyright © 2009 Cardinal Directions, Inc. Problem 5 – Select using GROUP BY and HAVING Problem: Group all PowerRating(s) represented in the Product table. Then display a Count of the rows in the group, and calculate the Average, Maximum and Minimum ProductPrice column. Only include in the report products that have a ProductDescription that contains the characters 'Butane'. Only include in the report those groups that have greater than or equal to 3 rows Only include in the report those groups that have an Average ProductPrice amount greater than or equal to 7000 dollars. Order the report in ascending sequence by PowerRating. Note: To arrive at the “proper” AVGPRICE, you will have to round your average. 6 rows selected. POWERRATINGCOUNTAVGPRICEMINPRICEMAXPRICE Page 31