Lecture 5 - Introduction to SQL II
Lecture 5 - Introduction to SQL II
DATA: AN INTRODUCTION
TO SQL SELECT
STATEMENTS (PART 2)
OPIM 5272: BUSINESS PROCESS MODELING AND DATA
MANAGEMENT
UGO ETUDO PH.D
COMPLETE RULES OF PRECEDENCE
Example 1
Integral Values
SUBSTITUTION VARIABLES
Example 2
Quoted Values
SUBSTITUTIO
N VARIABLES
Example 3
Double-Ampersand
Column Names
Expressions
DEFINE
• We can use the define command to set global values for our session
ALTER SESSION SET NLS_DATE_FORMAT = 'dd-mon-yy';
DEFINE h_date = TO_DATE('02/05/2008', 'mm/dd/yyyy');
SELECT first_name, last_name, hire_date
FROM employees
WHERE hire_date > &h_date;
UNDEFINE h_date;
• I show the special case of date here because defining a date has to be
done with the TO_DATE(literal, format) function
FUNCTIONS
Comma
Delimited Function’s
Output
Argument Logic
List
• Functions typically return scalar values although they need not take
arguments
SINGLE ROW FUNCTIONS
Function Purpose
ROUND(column| Rounds the column, expression, or value to n decimal
expression,n) places when n is given or no decimal places when it is not
given, or rounds numbers to the left of the decimal point
when n is negative
MOD(m,n) Modulus: givies the remainder of m after division by n
TRUNC(column| Truncates (slashes) the column expression or value to n
expression,n) decimal places when n is given (behaves similarly but not
identical to round when negative) and if n is not given its
given a default of 0
DATE FUNCTIONS
First, it is important to note that we can add and subtract integers from dates.
By default, when we do this, we are adding or subtracting days. Taking the
arithmetic difference between two dates will result in the number of days
between them.
SELECT first_name, last_name, (sysdate - hire_date) "days since hire"
What is
FROM employees; sysdate?
Function Result
MONTHS_BETWEEN(date1, Gives the number of months between two dates
date2)
ADD_MONTHS(date, n) Add n months to a particular date
NEXT_DAY(date, ‘char’) Returns the next day of the week that corresponds to
char. If char is ‘FRIDAY’ it returns the next Friday
LAST_DAY(date) Returns the last day of the month
CONVERSION FUNCTIONS
We can group by more than one column where repeating combinations of the
respective field values delineate groups:
Here, we will know the total salary burden of each job category within each
department.
• We can also restrict the groups that are returned by passing conditions
on each group using the HAVING clause
Say we only want data for departments with an average salary greater
than 10000:
You cannot
SELECT department_id, AVG(salary) use a
FROM employees column alias
in the
GROUP BY department_id having
clause
HAVING AVG(salary) > 10000;
GROUPING AND AGGREGATION