0% found this document useful (0 votes)
10 views180 pages

Database All 2

The document provides an overview of database technology in business, focusing on fundamental concepts such as data, information, and knowledge, as well as the structure and management of databases. It explains the components of a Database Management System (DBMS), the relational data model, and the importance of keys in database design. Additionally, it includes practical examples of defining and constructing a database for a local clinic, detailing the necessary tables and their attributes.

Uploaded by

anastasia
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
10 views180 pages

Database All 2

The document provides an overview of database technology in business, focusing on fundamental concepts such as data, information, and knowledge, as well as the structure and management of databases. It explains the components of a Database Management System (DBMS), the relational data model, and the importance of keys in database design. Additionally, it includes practical examples of defining and constructing a database for a local clinic, detailing the necessary tables and their attributes.

Uploaded by

anastasia
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 180

Database Technology

in Business
Department of Information Technology
Fundamental Concepts
Data, Information, Knowledge
• Data
– facts that have implicit meaning
• Information
– Data accompanied with semantics (i.e. the meaning
of data or the context)
– Outcome of a data processing
• Knowledge
– An outcome of reasoning based on credible
information
Database
A database is a collection of related data that has
the following properties:
1. It represents a selected part of the real world,
called the mini-world;
2. It is a logically coherent collection of data with
some inherent meaning;
3. It is designed and used for a specific purpose;
4. It has an intended group of users.
Examples of a database
• Banking database v e.g. clients, accounts,
money transfers;
• Company database v e.g. employees,
departments, payroll;
• Public administration database v e.g. names,
addresses, real estates, taxes;
• Healthcare database v e.g. patients, doctors,
treatments, prescriptions.
Database Management System (1)
A Database Management System (DBMS) is a
collection of software that facilitates the following
operations on the database:
1. defining a database t specifying the datatypes
and structures of data;
2. constructing a database t storing the data;
3. manipulating a database t querying and updating
the database;
4. sharing a database t controlling the simultaneous
user access to the database.
Database Management System (2)
SELECT
1101000011
names FROM
students;

Data Daniels
Jackson
Johnson
Database Walker

Database User
Management
System
Database System
• Database System
Database Management System
+
Database

• IT System
Database System
+
U [~o]]}v
Database Access Language
• DBMS provides data access through a query
language
• Query language allows to declare data
properties (finding and processing data is the
task of DBMS)
• SQL (pronounced: 1li d]1o}] ]dl`/o )
– Structured Query Language (declarative language)
Relational Data Model
Relational Data Model
• Provides a database as a collection of tables (relations)
• Tables t logical structures in which data is stored
• Popular u}o(}}˙ [}]}v
• Implemented through a Relational Database Management
System (RDBMS)
Database

Table: EMPLOYEES Table: DEPARTMENTS


EMP_ID EMP_FIRST_NAME EMP_LAST_NAME EMP_SALARY DEP_ID DEP_NAME DEP_LOCATION
100 John Smith 12000 10 Executive Room 306
101 Jessica Torn 9000 20 Marketing Room 201
102 Joe Ford 9000 30 Sales Room 205
Table
• Logical structure for storing data
– Two-dimensional structure composed of rows
and columns
• Table = Relation
Table: EMPLOYEES
EMP_ID FIRST_NAME LAST_NAME SALARY DEP_ID
10 John Brown 1500,00 1
20 Maria Kowalsky 4000,00 1
30 Ursula White 3500,00 2
40 Sergio Garcia 7000,00 2
Table Characteristics
• Row
{ Each row represents a single occurrence
{ Other names: tuple, record
• Column
{ Each column represents an attribute
{ Each column has a distinct name
{ Other name: attribute, field
Table: EMPLOYEES
EMP_ID EMP_FIRST_NAME EMP_LAST_NAME EMP_SALARY EMP_DEP_ID
100 John Smith 12000 10
101 Jessica Torn 9000 10
102 Joe Ford 9000 10
row
103 Diana Wilson 8000 = tuple
= record

column field null value


= attribute
Determination
• ^A determines B_
– Knowing the value of attribute A it is possible to uniquely look up
(determine) the value of attribute B
– Emp_Id determines Emp_Last_Name
– Emp_Id determines Emp_First_Name, Emp_Last_Name,
Emp_Salary
– Emp_Id, Emp_Last_Name determine Emp_First_Name,
Emp_Salary
• Notation
– AWB
– Emp_Id W Emp_First_Name, Emp_Last_Name, Emp_Salary
Table: EMPLOYEES
EMP_ID EMP_FIRST_NAME EMP_LAST_NAME EMP_SALARY EMP_DEP_ID
100 John Smith 12000 10
101 Jessica Torn 9000 10
102 John Ford 9000 10
103 Diana Smith 8000
Keys
• Key
– an attribute or a set of attributes that determine (identify)
other attributes
• Emp_Id determines Emp_First_Name, Emp_Last_Name,
Emp_Salary, Emp_Dep_Id
• Emp_Id W Emp_First_Name, Emp_Last_Name,
Emp_Salary, Emp_Dep_Id

Table: EMPLOYEES
EMP_ID EMP_FIRST_NAME EMP_LAST_NAME EMP_SALARY EMP_DEP_ID
100 John Smith 12000 10
101 Jessica Torn 9000 10
102 John Ford 9000 10
103 Diana Smith 8000
Superkey
• An attribute (or combination of attributes) that uniquely identifies
each row in a table
• Examples
– Emp_Id
– Emp_Id, Emp_Last_Name
– Emp_Id, Emp_Last_Name, Emp_Salary
– Emp_Id t with or without additional attributes can be a
superkey
Table: EMPLOYEES
EMP_ID EMP_FIRST_NAME EMP_LAST_NAME EMP_SALARY EMP_DEP_ID
100 John Smith 12000 10
101 Jessica Torn 9000 10
102 John Ford 9000 10
103 Diana Smith 8000
Primary Key
• Primary key
– A minimal superkey selected to uniquely identify any given
row in a particular table
– May not contain null values
Table: EMPLOYEES
EMP_ID EMP_FIRST_NAME EMP_LAST_NAME EMP_SSN EMP_SALARY EMP_DEP_ID
100 John Smith 481-20-4585 12 000 10
101 Jessica Torn 772-18-2289 9 000 10
102 John Ford 573-75-0204 9 000 10
Null value 103 Diana Smith 441-80-2888 8 000

• Null = Void
• Not a zero
• Not a space
• Even not a zero-length string
Foreign Key
• Attribute whose values match the primary key values in the related
table
• In some cases foreign key may be null

Table: EMPLOYEES
EMP_ID EMP_FIRST_NAME EMP_LAST_NAME EMP_SALARY EMP_DEP_ID
100 John Smith 12 000 10
101 Jessica Torn 9 000 20
EMP_DEP_ID – foreign key 102 John Ford 9 000 10
103 Diana Smith 8 000 30
in the EMPOYEES table
DEP_ID – primary key
in the DEPARTMENTS Table: DEPARTMENTS
table DEP_ID DEP_NAME DEP_LOCATION
10 Marketing 4th Floor
20 Sales 1st Floor
30 Human Resources 5th Floor
Unique Key
• Unique key
– An attribute (or a combination of attributes) whose
all values in a given table must be unique
– May contain null values
• Primary and unique key
– Both keys have to be unique
– Primary key may not contain null values
Unique key may contain null values
Relational Keys t Summary
Key Type Definition
Superkey An attribute (or combination of attributes) that uniquely
identifies each row in a table

Candidate key A minimal superkey; A superkey that does not contain a


subset of attributes that is a superkey itself

Primary key A candidate key selected to uniquely identify all other


attribute values in any given row; Cannot contain null entries

Foreign key An attribute (or combination of attributes) in one table whose


values must either match the primary key in associated table
or be null

Unique key An attribute (or combination of attributes) whose values are


either unique or null
Exercise
• Start SQL Developer
• Analyze the available tables
References
• R. Elmasri, Sh. Navathe, Fundamentals of
database systems 6th edition, Addison-Wesley,
2011
• J. Price, Oracle Database 12c SQL, McGraw-Hill
Education, 2013
• C. Coronel, S. Morris, Database Systems: Design,
Implementation, & Management 12th Edition,
Course Technology, 2016
Thank you!
Database Technology
in Business
Department of Information Technology
DEFINING AND CONSTRUCTING A
DATABASE
Business case
• The local clinic must keep records of patients,
treatments, doctors and prescriptions.
• This is very important to enable a complete
review of patients' treatment history.
• There is also a need to create statistics for
doctors' performance.
DEFINING THE DATABASE
Definig the database
t the entities

Treatment
Prescription
Patient Doctor
Definig the database
t the relationships

can go for many can provide many


must relate to one must relate to one

Treatment
can result in many
Patient
must realate to one Doctor

Prescription
Definig the database
t the tables

Treatment
Prescription
Patient Doctor

Patients Doctors Treatments Prescriptions


Definig the database
- the PATIENTS table
• Create PATIENTS table
• Create attributes (columns):
– PAT_ID (NUMBER 9)
– FIRST_NAME (VARCHAR2 64 BYTES) NOT NULL
– LAST_NAME (VARCHAR2 64 BYTES) NOT NULL
Social – BIRTH_DATE (DATE) NOT NULL
Security – SSN (VARCHAR2 64 BYTES) NOT NULL
Number
– ADDRESS (VARCHAR2 256 BYTES) NOT NULL
– PHONE (VARCHAR2 64 BYTES)
• Create constraints A value uniquely identifing
– Primary Key -> PAT_ID any given row in a
– Unique -> SSN particular table
An attribute whose values
are either unique or null
Definig the database
- the PATIENTS table
SQL Developer (1)
Definig the database
- the PATIENTS table
SQL Developer (2)
Definig the database
- the PATIENTS table
SQL statements (example)
-- DDL for Table PATIENTS -- Constraints for Table PATIENTS
CREATE TABLE "PATIENTS" ALTER TABLE "PATIENTS" ADD CONSTRAINT
"PATIENTS_PK" PRIMARY KEY ("PAT_ID") ENABLE;
( "PAT_ID" NUMBER(9,0),
ALTER TABLE "PATIENTS" ADD CONSTRAINT
"FIRST_NAME" VARCHAR2(64 BYTE), "PATIENTS_UK1" UNIQUE ("SSN")
"LAST_NAME" VARCHAR2(64 BYTE), ENABLE;
"BIRTH_DATE" DATE, ALTER TABLE "PATIENTS" MODIFY ("PAT_ID" NOT
"SSN" VARCHAR2(64 BYTE), NULL ENABLE);
"ADDRESS" VARCHAR2(256 BYTE), ALTER TABLE "PATIENTS" MODIFY
"PHONE" VARCHAR2(64 BYTE) ("FIRST_NAME" NOT NULL ENABLE);
); ALTER TABLE "PATIENTS" MODIFY ("LAST_NAME"
NOT NULL ENABLE);
ALTER TABLE "PATIENTS" MODIFY ("BIRTH_DATE"
NOT NULL ENABLE);
ALTER TABLE "PATIENTS" MODIFY ("SSN" NOT
NULL ENABLE);
ALTER TABLE "PATIENTS" MODIFY ("ADDRESS"
NOT NULL ENABLE);
Definig the database
- the DOCTORS table
• Create DOCTORS table
• Create attributes (columns):
– DOC_ID (NUMBER 9)
– FIRST_NAME (VARCHAR2 64 BYTES) NOT NULL
– LAST_NAME (VARCHAR2 64 BYTES) NOT NULL
Doctor – HIRE_DATE (DATE) NOT NULL
Certificate – DCN (VARCHAR2 64 BYTES) NOT NULL
Number
– SALARY (NUMBER 12,2) NOT NULL
– PHONE (VARCHAR2 64 BYTES)
• Create constraints
– Primary Key -> DOC_ID
– Unique -> DCN
Definig the database
- the DOCTORS table
SQL Developer (1)
Definig the database
- the DOCTORS table
SQL Developer (2)
Definig the database
- the TREATMENTS table
• Create TREATMENTS table
• Create attributes (columns):
– TRE_ID (NUMBER 9)
– VISIT_DATE (DATE) NOT NULL
– DESCRIPTION (VARCHAR2 1024 BYTES)
– PAT_ID (NUBER 9) NOT NULL
– DOC_ID (NUMBER 9) NOT NULL
• Create constraints Relates to
Attribute whose
values match the
– Primary Key -> TRE_ID patients primary key values in
– Foreign Key -> PAT_ID the related table
Relates to
– Foreign Key -> DOC_ID doctors
Definig the database
- the TREATMENTS table
SQL Developer (1)
Definig the database
- the TREATMENTS table
SQL Developer (2)
Definig the database
- the PRESCRIPTIONS table
• Create PRESCRIPTIONS table
• Create attributes (columns):
– PRE_ID (NUMBER 9)
– VALIDITY_DATE (DATE) NOT NULL
– DESCRIPTION (VARCHAR2 1024 BYTES)
– TRE_ID (NUBER 9) NOT NULL
• Create constraints
– Primary Key -> PRE_ID Relates to
– Foreign Key -> TRE_ID treatments
Definig the database
- the PRESCRIPTIONS table
SQL Developer (1)
Definig the database
- the PRESCRIPTIONS table
SQL Developer (2)
CREATING THE DATABASE
Creating the database
- the PATIENTS table
SQL Developer (example)
Creating the database
- the DOCTORS table
SQL Developer (example)
Creating the database
- the TREATMENTS table
SQL Developer (example)
Creating the database
- the PRESCRIPTIONS table
SQL Developer (example)
Example queries
Select patients born after 1967

Select treatments including prescriptions


Relational Keys t Summary
Key Type Definition
Primary key A value selected to uniquely identify all other attribute values
in any given row; Cannot contain null entries

Foreign key An attribute (or combination of attributes) in one table whose


values must either match the primary key in associated table
or be null
Unique key An attribute (or combination of attributes) whose values are
either unique or null
References
• Creating and Using Database Objects in Oracle databasse
https://docs.oracle.com/cd/B28359_01/appdev.111/b28
843/tdddg_creating.htm
• Getting Started with Oracle SQL Developer 4.0
https://www.oracle.com/webfolder/technetwork/tutoria
ls/obe/db/sqldev/r40/sqldev4.0_GS/sqldev4.0_GS.html
• J. Price, Oracle Database 12c SQL, McGraw-Hill
Education, 2013
• C. Coronel, S. Morris, Database Systems: Design,
Implementation, & Management 12th Edition, Course
Technology, 2016
Thank you!
Database Technology
in Business
Department of Information Technology
SQL Fundamentals I
SQL: Structured Query Language
• SQLv Structured Query Language
• To define, retrieve, and manipulate data stored
in relational databases
• Used by a wide range of users, including those
with little or no programming experience
• Syntax similar to English
SELECT first_name, last_name
FROM EMPLOYEES
WHERE dep_id = 10;
SQL Statement Terms
• Keyword t primary SQL element; e.g.,
– SELECT
– FROM

• Clause t a part of a SQL statement; e.g.,


– SELECT last_name
– FROM employees

• Statement t a combination of two or more


clauses, followed by a semicolon; e.g.,
– SELECT last_name FROM employees;
Performing SQL Statements
1. SQL statement is entered
SELECT last_name
FROM employees; 2. SQL statement is executed

Database

DBMS
3. Resulting data is displayed

LAST_NAME
Smith
Torn
Ford Database
Wilson
Kent

Client Server
side side
SELECT Statement (1/2)
SELECT [DISTINCT]
{*|column|expression
[alias],...}
FROM table
[WHERE condition(s)]
[ORDER BY ...];
• SELECT t specifies columns to be displayed
• FROM table t specifies the table containing the
columns specified in the SELECT clause
• WHERE t limits selection results to rows that meet
a specified condition
SELECT Statement (2/2)
• DISTINCT t remove duplicates from the result
and sorts rows ascending
• * t selects all columns
• column t select a named column
• alias t gives an alternative name for a column
• condition(s) t conditional expression consisting
of column names, constants, and other
expressions
• ORDER BYt sorts rows by the specified values
Guidelines on SQL Statements
• SQL statements are not case sensitive
• You can enter SQL statements on one or more
lines
• Place clauses on separate lines for readability
and ease of editing
• Use tabs and indents to make code more
readable
• To enhance readability enter keywords in
uppercase and all other words in lowercase
Sample database - tables
Tables:
• EMPLOYEES
• DEPARTMENTS
• POSITIONS
• JOB_GRADES
Sample database - relationships

can report can manage


to one many

can relate to many

must hold one


POSITION
can consist of many

can work in one

DEPARTMENT can relate to many


must be assigned to one
JOB_GRADE

EMPLOYEE
Sample database - content
• Display description of a sample table.
Use DESCRIBE keyword.
• Display content of all sample tables.
Use SELECT * clause and FROM keyword.
Selection
• To retrieve selected rows

SELECT *
FROM employees
WHERE emp_id=101 OR emp_id=103;

Table: EMPLOYEES
EMP_ID FIRST_NAME LAST_NAME SALARY DEP_ID
100 John Smith 12000 10
101 Jessica Torn 9000 10
102 Joe Ford 9000 10
selected
103 Diana Wilson 8000 10 rows
Selection - exercises
• Display all information about employee with id
equal to 104.

• Display all information about employees with


salary equal to 3100.

• Display all information about employees with


last_name equal to 'Brown'.
Projection
• To retrieve selected columns

SELECT first_name, salary


FROM employees;

Table: EMPLOYEES
EMP_ID FIRST_NAME LAST_NAME SALARY DEP_ID
100 John Smith 12000 10
101 Jessica Torn 9000 10
102 Joe Ford 9000 10
103 Diana Wilson 8000 10

selected
columns
Projection - exercises
• Display the last name and hire date for each
employee.

• Display the name and location for each


department.
Selection & Projection
• To retrieve selected rows & columns

SELECT first_name, salary


FROM employees
WHERE emp_id=101 OR emp_id=103;
Table: EMPLOYEES
EMP_ID FIRST_NAME LAST_NAME SALARY DEP_ID
100 John Smith 12000 10
101 Jessica Torn 9000 10
102 Joe Ford 9000 10
selected
103 Diana Wilson 8000 10 rows

selected
columns
Selection & Projection exercises
• Display the last name and allowance for each
employee working in department with dep_id
equal to 30.

• Display the last name, dep_id and salary for


each employee with the first name equal to
'Nicole'.
Basic Operators
• Arithmetic operators: +, t , *, /
SELECT last_name, (salary+100)*12
FROM employees;

• Concatenation operator: ||
SELECT 'First name: ' || first_name,
'Last name: ' || last_name
FROM employees;
Basic Operators - exercises
• Display the first name, last name, and annual
salary for all employees.

• Display the full name (concatenation of first


and last name), and hire date for all employees
who work in department 40.
Comparison Operators (1/2)
• Basic operators: =, >, >=, <, <=, <>
SELECT ... WHERE dep_id = 40;
SELECT ... WHERE salary >= 5500;
SELECT ... WHERE last_name = 'Foster';

• Y BETWEEN a AND b t value belongs to the closed


interval between a and b
SELECT ... WHERE salary BETWEEN 3000 and 8000;

• Y IN (set) t value belongs to the set


SELECT ... WHERE pos_id IN (2, 4, 5);

• Y IS NULL t value is void (does not exist)


SELECT ... WHERE manager_id IS NULL;
Comparison Operators (2/2)
• Y LIKE pattern
value consistent with the pattern, that is a
string, where:
% represents any sequence of 0 or more characters
_ represents one single character

SELECT ... WHERE first_name LIKE 'To%';


SELECT ... WHERE last_name LIKE 'Bro_';
Comparison Operators - exercises
• Display the last name, manager id and salary for all
employees whose salary is in the range from 4000
to 7000.
• Display the last name and salary for all employees
who do not get allowance.
• Display the last name and dep_id for all employees
who work in department 10 or 40 or 50.
• Display the first name and allowance of all
employees whose first name contains the letter 'a'
in the second position.
References
• J. Price, Oracle Database 12c SQL, McGraw-Hill
Education, 2013
• Oracle 12c Documentation
http://www.oracle.com/pls/db121/homepage
Thank you!
SQL Fundamentals II
Logical Operators
• Logical operators: AND, OR, NOT
• Examples:
• SELECT ... WHERE salary >= 3000 AND dep_id = 30
• SELECT ... WHERE dep_id = 30 OR manager_id = 100
• SELECT ... WHERE jg_id NOT IN (6,9)
• SELECT ... WHERE allowance IS NOT NULL
• SELECT ... WHERE manager_id NOT LIKE '10%'
• SELECT ... WHERE salary NOT BETWEEN 4000 AND 15000
Logical Operators - exercises
• Display the last name and salary of all employees
whose last name begins with 'T' or 'B'.
• Display the first name, last name and manager id
for all employees whose first name does not
contain the letter 'i' and the third letter is 'n'.
• Display the last name of all employees who work in
department 30 and who are paid an allowance.
Aliases
• Aliases for columns:
SELECT last_name AS "Last Name",
salary "Salary"
FROM employees;
• Aliases for tables:
SELECT jg_id, jg.name
FROM job_grades jg;
Aliases - exercise
• Display the first name, last name, salary and the
the salary multiplied by 12 for all employees who
get allowance. Label the salary multiplied by 12 as
cannual salary_X
• Display the last name and dep_id for all employees
with salary less then 5000. Label the dep_id as
cDepartment_X
ORDER BY (1/2)
• To sort query results
SELECT ...
FROM table
[ORDER BY {column|expression|alias}
[ASC|DESC]];

• ORDER BY t determines the order of rows


resulting from the query execution
• ASCt ascending order (default)
• DESC t descending order
ORDER BY (2/2)
• Examples:
SELECT last_name, dep_id
FROM employees
ORDER BY dep_id;
SELECT last_name "Name", dep_id "Dept"
FROM employees
ORDER BY "Dept", "Name" DESC;
SELECT last_name, dep_id
FROM employees
ORDER BY 2 DESC, pos_id ASC;
ORDER BY - exercise
• Display the last name and salary of all employees
who work in department 20 or 30, sorted by
salary.
• Display the last name of all employees who do not
get allowance, sorted by hire date.
• Display the last name and department id of all
employees whose jg_id is neither 5 nor 6, sorted
by department id in ascending order and by last
name in descending order.
DESCRIBE
• To display table structure
• Command of SQL Developer software
• Syntax:
DESC[RIBE] tablename
• Examples:
DESCRIBE employees
DESC job_grades
References
• J. Price, Oracle Database 12c SQL, McGraw-Hill
Education, 2013
• Oracle 12c Documentation
http://www.oracle.com/pls/db121/homepage
Thank you!
Database Technology
in Business
Department of Information Technology
Database Technology
in Business
Department of Information Technology
SQL Functions I
SQL Functions
• Perform an operation on input datav column(s)
and
Return the result as a single value
• Two types:
– Single-rowv returns one result per each row
– Multiple-row (Group-row)v returns one result per
group of rows
• Syntax
function_name ({column | expression}
[, arg1[, arg2]])
Single-row Functions (1/2)
• Syntax
function_name ({column | expression}
[, arg1[, arg2]])
• function_name t (v]}v[vu
• column t }ouv[vu
• expression t character string or
calculated expression
• arg1, arg2 t (v]}v[Puv
Single-row Functions (2/2)
• Act (operate) on every row
and
Return one value for each row
• Can be used in SELECT, WHERE, ORDER BY
clauses
• Can be nested
Types of Single-row Functions*
• Character functions
– Convert the case of character strings
– Perform operations on character strings
• Number functions
• Date functions
• Data type conversion functions
• Functions to deal with null values
• Conditional function DECODE
Case Conversion Functions
• Functions
– LOWER (expr) t to lowercase
– UPPER (expr) t to uppercase
– INITCAP (expr) t the first character to uppercase,
the remaining characters to lowercase
• Examples
SELECT UPPER(last_name), LOWER(last_name)
FROM employees;
SELECT first_name, last_name
FROM employees
WHERE LOWER(last_name)='brown';
SELECT LOWER(name), INITCAP(LOWER(name))
FROM departments;
Character Manipulation Functions
• LENGTH (expr) t returns the number of characters in the expr
SELECT UPPER(last_name) AS "Name", LENGTH(first_name)
FROM employees
ORDER BY LENGTH(last_name);
• SUBSTR (expr, m [, n]) t returns substring of the expr starting at position
m and n characters long; if m < 0 then the count n starts from the end;
if n is omitted then all characters to the end are returned
SELECT SUBSTR('lavender',4,3)
FROM dual;

SELECT SUBSTR(name,1,4)
FROM departments;

SELECT SUBSTR(first_name,1,1) || '.' || last_name AS "Name"


FROM employees
WHERE LENGTH(last_name) IN (6,7);
Exercise
• Write a query that displays the last names
in uppercase, the first names in lower case and
the length of the first name (label the
column cF] Name CZN}_ for all
employees whose last name starts with a letter
in the range <'B','N'>.
Single-row Number Functions
• ROUND (expr [, n]) t rounds the expr to n decimal places;
if n is omitted then the expr is rounded to integer;
if n < 0 then the expr is rounded to decimal places left to the decimal point
SELECT salary/3, ROUND(salary/3, 2),
ROUND(salary/3), ROUND(salary/3, -2)
FROM employees;

• TRUNC (expr [, n]) t truncates the expr to n decimal places;


the default for n is 0 (used if n is omitted)
if n < 0 then the expr is truncated to decimal places left to the decimal point
SELECT salary/3, TRUNC(salary/3, 2),
TRUNC(salary/3), TRUNC(salary/3, -2)
FROM employees;

• MOD (m, n) t returns the remainder of m over n


SELECT ROUND(salary/3), MOD( ROUND(salary/3), 10)
FROM employees;
Exercise
• For each employee, display the employee id,
last name, salary, salary increased by 12,3%
and rounded to an integer (labeled as "New
Salary"), and the difference between the new
and old salary (labeled as "Increase"). Sort the
results by the increase column.
NULL Value
• Column contains NULL if it lacks the data value
• NULL is neither 0 nor space (' ')
– 0  number
– space (' ')  one-length character string
– NULL  emptiness, vacuum, nothingness
• If any column value in an expression is null,
the whole result is null
SELECT last_name, salary + allowance
FROM employees;
• NVL (expr1, expr2) function
– if the expr1 is null then the expr2 is used as a replacement
SELECT last_name, salary + NVL(allowance, 0)
FROM employees;
Excercise
• ˙C Z]o˙Zuo}˙[ last
names and sums of salary and allowance. Label
Z}ouvc Full sallary".
Data Type Conversion Functions
• TO_CHAR (number | date, [fmt], [nlsparams])
– Converts a number or date to a character string with format model
fmt
• TO_NUMBER (char, [fmt], [nlsparams]) t
– Converts a character string containing digits to a number with format
model fmt
• TO_DATE (char, [fmt], [nlsparams]) t
– Converts a character string representing a date to a date value with
format model fmt
• nlsparams
– Specifies regional settings like decimal character, digit group separator,
currency symbol, date format, etc.
– If omitted the default is used
Data Type Conversion Functions
in Action (1/2)
• Examples
SELECT first_name, last_name,
TO_CHAR(hire_date, 'fmDD Month YYYY',
'nls_date_language = French') "Date(FR)",
TO_CHAR(hire_date, 'Ddspth "of" Month YYYY HH:MI:SS AM',
'nls_date_language = American') "Date time (US)"
FROM employees;

SELECT first_name, last_name,


TO_CHAR(hire_date, 'DD-Mon-yyyy',
'nls_date_language = Polish')
FROM employees
WHERE hire_date < TO_DATE('15-May-01', 'DD-Mon-RR',
'nls_date_language = American');
Data Type Conversion Functions
in Action (2/2)
SELECT TO_CHAR(hire_date, 'Month DDTH, YYYY') FROM employees;
SELECT TO_CHAR(hire_date, 'YYYY-MON-DD') FROM employees;
SELECT TO_CHAR(SYSDATE,'HH24:MI:SS') FROM dual;
SELECT TO_CHAR(SYSDATE,'HH12:MI:SS a.m.') FROM dual;
SELECT TO_CHAR(salary,'$99,999') FROM employees;
SELECT TO_NUMBER('1500,75') FROM dual;
SELECT TO_NUMBER('$1500.75','L9999.99', 'nls_currency = $')
FROM dual;
SELECT TO_DATE('February 17, 1997, 11:30 A.M.',
'Month dd, YYYY, HH:MI A.M.',
'nls_date_language = American')
FROM dual;
SELECT TO_DATE('Maj 23, 1999', 'Month DD, YYYY',
'nls_date_language = Polish')
FROM dual;
Excercise
• ˙C Z]o˙Zuo}˙[ last
names and department id. If an employee does
not have department id assigned, [No
Department [ should be displayed. Label the
}ouvc Department".
• ˙C Z]o˙Zuo}˙[ last
names and hire dates (label the column c Hire
date_ for all employees hired before 1 Jan
2001. Format the dates to appear similar to
1999-JAN-01.
References
• J. Price, Oracle Database 12c SQL, McGraw-Hill
Education, 2013
• Oracle 12c Documentation
http://www.oracle.com/pls/db121/homepage
Thank you!
Database Technology
in Business
Department of Information Technology
SQL Functions II
DUAL Table
SYSDATE Function
• DUAL table
used to display the value of a constant or expression
that is not based on any table
SELECT MOD(1900, 45)
FROM dual;
• SYSDATE function
returns the current date and time (on a database
server)
SELECT SYSDATE
FROM dual;
Arithmetic Operations on Dates
• Dates are timestampsv they always store date and time
• Arithmetic operators can be used to process dates
Operation Returned type Description
date + number date Adds days to date
date - number date Subtracts days from date
date + number/24 date Adds hours to date
date - number/24 date Subtracts hours from date
date – date number Subtracts two days resulting in the
number of days between them

SELECT hire_date, hire_date+1, hire_date-1,


hire_date+12/24,
LAST_DAY(hire_date)-hire_date
FROM employees;
Date Functions (1/2)
• MONTHS_BETWEEN (date1, date2) t calculates the number of months
between two dates; the result can be positive or negative

SELECT MONTHS_BETWEEN(SYSDATE,
TO_DATE('2020-01-01','YYYY-MM-DD')) "months from the
beginning of 2020"
FROM dual;

• ADD_MONTHS (date, n) t adds n calendar months to the date; n must be


integer

SELECT ADD_MONTHS(SYSDATE,6) six


" monthsfromtoday„
FROM dual;
Date Functions (2/2)
• LAST_DAY (date) t calculates the date of the last day of the month that
contains date
SELECT LAST_DAY(SYSDATE) "Lastdayofthecurrentmonth„
FROM dual;

SELECT last_name, hire_date "Hire date",


MONTHS_BETWEEN (SYSDATE, hire_date)
"Working period (months)",
ADD_MONTHS (hire_date, 6) "Review date",
LAST_DAY(hire_date) "Last day of the month
after hiring"
FROM employees;
Exercises
• Display the last name, and calculate the
number of months between today and the hire
date, for all employees with the letter 'B',
'D' or 'F' as the first letter of their last
name. Label the column "Months employed".
Truncate the number of months to a whole
number. Order the results by the number of
months employed.
Exercises
• Display the last names and hire dates of all
employees who have been with the company
for more than 25 years.
• D]o˙Zuo}˙[ last name, hire date,
and salary review date, which is exactly after
six months of service. Label the column as
"Review date". Format the dates to appear
]u]o}^M}v˙UT`v]Z}(O}U
_X
References
• J. Price, Oracle Database 12c SQL, McGraw-Hill
Education, 2013
• Oracle 12c Documentation
http://www.oracle.com/pls/db121/homepage
Thank you!
Grouping Data
SQL Group Functions
GROUP BY Clause
• Divides table rows into groups based on values in the specified
column(s)
SELECT ...
FROM table
[GROUP BY expression];
– expression – specifies columns whose values determine the basis for
grouping rows

• Guidelines for using GROUP BY:


– If a SELECT clause includes a group function, it isn’t allowed to select
individual columns which aren’t included in the GROUP BY clause
– It is allowed to use WHERE clause to exclude rows before grouping
– It isn’t allowed to use a column alias in the GROUP BY clause
– By default, rows are sorted by ascending order of the columns
included in the GROUP BY clause
GROUP BY in Action
SELECT dep_id
FROM employees
GROUP BY dep_id;

EMP_ID FIRST_NAME LAST_NAME SALARY DEP_ID


100 John Smith 15500 10
101 Jessica Torn 8800 10
emp_dep_id=10
102 Nick Ford 9800 10
103 Diana Wilson 7900 10
104 Jennifer Kent 5800 20
105 David Brown 3100 20 emp_dep_id=20
106 Nicole Foster 1800 20
107 Steven Anderson 5900 30
108 Lisa Davis 4200 30 emp_dep_id=30
109 Anne Taylor 3100 30
Group Functions
• Process groups of rows returning a single result for
each group
These groups can be
– the whole table
– the table split into groups
• Guidelines for group functions
– DISTINCT – group functions do not process duplicates
– ALL – group functions process all values including duplicates (the default
approach)
– Possible data types for group function’s arguments: NUMBER, CHAR,
VARCHAR2, DATE
– All group functions except COUNT(*) ignore NULL
Group Function Review (1/2)
• COUNT ({ * | [DISTINCT | ALL] expr })
– counts the number of rows for which the expr is not null
– *  indicates counting all rows including duplicates and nulls
SELECT COUNT(*), COUNT(dep_id),
COUNT( NVL(dep_id,0) ),
COUNT(DISTINCT dep_id),
COUNT(DISTINCT NVL(dep_id,0))
FROM employees;
• AVG ([DISTINCT | ALL] expr)
– Calculates average for the expr
SELECT AVG(allowance), AVG( NVL(allowance,0) )
FROM employees
WHERE dep_id = 30;
Group Function Review (2/2)
• MAX ([DISTINCT | ALL] expr) – calculates max of the expr
• MIN ([DISTINCT | ALL] expr) – calculates min of the expr
• SUM ([DISTINCT | ALL] expr) – calculates sum of the expr
SELECT MAX(salary), MIN(salary), SUM(salary)
FROM employees
WHERE dep_id=30;
SELECT MIN(last_name), MAX(last_name)
FROM employees;

• STDDEV ([DISTINCT | ALL] expr) – standard deviation of the expr


• VARIANCE ([DISTINCT | ALL] expr) – variance of the expr,
SELECT STDDEV(salary), VARIANCE(salary)
FROM employees
WHERE dep_id = 30;
Group Functions
for the whole Table
Table: EMPLOYEES
EMP_ID FIRST_NAME LAST_NAME SALARY DEP_ID
100 John Smith 15500 10
101 Jessica Torn 8800 10
102 Nick Ford 9800 10
103 Diana Wilson 7900 10
104 Jennifer Kent 5800 20
105 David Brown 3100 20
106 Nicole Foster 1800 20
107 Steven Anderson 5900 30
108 Lisa Davis 4200 30
109 Anne Taylor 3100 30

Result:
SELECT AVG(salary) AVG(salary)
FROM employees; 6590,00
One value for the whole table
Group Functions with
GROUP BY clause
EMP_ID FIRST_NAME LAST_NAME SALARY DEP_ID
100 John Smith 15500 10
101 Jessica Torn 8800 10
102 Nick Ford 9800 10
emp_dep_id=10
103 Diana Wilson 7900 10
104 Jennifer Kent 5800 20
105 David Brown 3100 20 emp_dep_id=20
106 Nicole Foster 1800 20
107 Steven Anderson 5900 30
108 Lisa Davis 4200 30 emp_dep_id=30
109 Anne Taylor 3100 30

Result:
DEP_ID AVG(salary)
SELECT dep_id, AVG(salary)
10 10500,00
FROM employees
GROUP BY dep_id; 20 3566,67
30 4400,00

Separate value for each group


Excercises
• Display the highest, lowest, sum, and average
salary of all employees. Label the columns
"Maximum", "Minimum", "Sum", and "Average",
respectively.
• Display the maximum salary, the minimum salary,
and the difference between them for staff who
were hired in 2001. Label the columns "Minimum",
"Maximum", and "Difference".
• Display the jg_id and the highest, lowest, sum, and
average salary of employees for each jg_id. Label
the columns "Job grade", "Maximum", "Minimum",
"Sum", and "Average", respectively.
Exercises
• Write a query to display the department id and
the number of people who earn an allowance
for each department.
• Write a query that displays the department id
and the difference between the highest and
lowest salaries for each department. Label the
column "Difference".
HAVING Clause
• Specifies condition to filter groups
SELECT ...
FROM table
[GROUP BY expression]
[HAVING condition];
– condition – restricts the groups of rows for which the specified condition
is true

• Example:
SELECT dep_id, AVG(salary)
FROM employees
GROUP BY dep_id
HAVING MAX(salary) > 6000;
Group Functions in Action
• No grouping column in a SELECT clause
SELECT AVG(salary), MIN(salary), MAX(salary)
FROM employees
GROUP BY dep_id;
• Grouping by more than one column
SELECT dep_id, jg_id, AVG(salary)
FROM employees
GROUP BY dep_id, jg_id;
• Group functions in ORDER BY clause
SELECT dep_id, AVG(salary)
FROM employees
GROUP BY dep_id
ORDER BY AVG(salary);
Exercises
• Display the manager_id and the salary of the
lowest paid employee for that manager. Exclude
anyone whose manager is not known. Exclude any
groups where the minimum salary is less than
3000. Sort the output in descending order of salary.
• Write a query that displays the total number of
employees hired each year. Label the first column
as "Employees hired" and the other one as "Year".
• Create a query to display the jg_id, the average
salary for that grade based on department id for
departments 20, 30, and 50, giving each column an
appropriate heading
References
• J. Price, Oracle Database 12c SQL, McGraw-Hill
Education, 2013
• Oracle 12c Documentation
http://www.oracle.com/pls/db121/homepage
Thank you!
Database Technology
in Business
Department of Information Technology
Summary of previous topics
Tables
• Data in the relational databases are stored in
tables.
• A table is a data structure that consists of
columns and rows.
• Each column has a name and a data type
assigned.
Data types
• Examples of data types:
– NUMBER
– VARCHAR2
– DATE
• The data stored in the column must match the data
type specified for this column e.g.
– ZvucJ}Zv_vv}]v}co˙ _}ouv`]Z
NUMBER(7,2) data type
– the number vv}]v}co˙ _}ouv`]Z
NUMBER(7,2) data type. This data type accepts a total
number of seven digits with two digits reserved for decimal
part and five digits for the integer part.
Out of the scope of the
NUMBER(7,2) datatype 120 000, 00 This number requires at least
NUMBER(8,2) datatype

integer part decimal


(6 digits) part
(2 digits)
SQL queries
• Learn data structure before writing SQL query
DESC employees;
Name Null Type
---------- -------- ------------
EMP_ID NOT NULL NUMBER(38)
FIRST_NAME NOT NULL VARCHAR2(20)
LAST_NAME NOT NULL VARCHAR2(30)
HIRE_DATE NOT NULL DATE
SALARY NOT NULL NUMBER(7,2)
ALLOWANCE NUMBER(7,2)
NULL values
POS_ID NOT NULL NUMBER(38)
accepted JG_ID NOT NULL NUMBER(38)
MANAGER_ID NUMBER(38)
DEP_ID NUMBER(38)
SQL queries
SELECT *
FROM employees;

SELECT and FROM clauses are obligatory in each


select statement.
Semicolon (;) ends each SQL statement.
Projection
SELECT first_name, last_name, salary
FROM employees;

Each column name or expression in select clause must


be separated by comma (,).
The comma cannot be left at the end
of select clause! Coma indicates next
column name or expression.

SELECT last_name, hire_date,


FROM employees;
Structure of SQL query
1. Obligatory SELECT dep_id, AVG(salary)
2. Obligatory FROM employees
3. Optional WHERE dep_id IN (20,30,50)
4. Optional GROUP BY dep_id, jg_id
5. Optional HAVING MIN(salary)> 2000
6. Optional ORDER BY 2 DESC;

The order of clauses does matter!


Wrong structure of SQL query
Point mistakes
SELECT dep_id, AVG(salary),
WHERE AVG(salary)<3000; Missed GROUP BY
clause
FROM employees Group function
in WHERE clause
ORDER BY 2 DESC
Wrong order of
the clauses
Functions
FUNCTION(arg1, arg2UYarg
U n) -> return_value

• Each function has specified number of


arguments it can take;
• Each function returns one return value;
• Each argument and return value has a specified
data type.
Functions - example
SUBSTR(char_seq, position,
subst_length) -> return_value

For this function:


• char_seq has a VARCHAR2 datatype
• position has a NUMBER datatype
• subst_length has a NUMBER datatype
• return_value has a VARCHAR2 datatype
Functions - example
NVL(column_name, value_if_null) ->
return_value

For this function:


• column_name has the same data type as specified
for this column;
• value_if_null must have the same data type as
column_name;
• return_value has the same data type as
column_name.
How do I know?
• How do I know what the argument datatype
should be?
• Is this a secret knowledge?
• NO!
AlG}}PoWc}o(v]}v_
• First result:
https://docs.oracle.com/cd/B19306_01/server.102/
b14200/functions001.htm
It contains full specification of all Oracle database
functions 
Functions in functions
• If the function always returns one result of a
specific data type, is it possible to use the function
instead of an argument in other function?
• YES!
• SUBSTR(char_seq, position, subst_length) ->
return_value
• UPPER(char_seq) -> return_value
• SUBSTR(UPPER(char_seq), position,
subst_length) -> return_value
Functions in functions
• How many functions can be nested in one
another?
• So many as You need 
• CONCAT(SUBSTR(UPPER(last_name),1,3),
NVL(RPAD(allowance, LENGTH(allowance)+2,
[¤[U[N}oo}`v[
Functions in functions - example
SELECT
CONCAT(
SUBSTR(UPPER(last_name),1,3),
NVL(
RPAD(
CONCAT(' ',allowance),
LENGTH(allowance)+2,'$'
),
'No allowance'
)
)
FROM employees;
Thank you!
Database Technology
in Business
Department of Information Technology
Joining Tables
Join Operation
• Performed when a query requires data stored
in more than one table Primary
Foreign key key
Tabela: EMPLOYEES Tabela: DEPARTMENTS
ID FIRST_NAME LAST_NAME DEP_ID DEP_ID NAME LOCATION
100 John Smith 10 join 10 Executive Room 306
101 Jessica Torn 10 20 Marketing Room 201
102 Joe Ford 20 30 Sales Room 205

Resulting view
FIRST_NAME LAST_NAME NAME LOCATION
John Smith Executive Room 306
Jessica Torn Executive Room 306
Joe Ford Marketing Room 201
Equijoin
• Values in one column of the first table must be
equal to the values in another column in the
second table

• Syntax
SELECT first_name, last_name, name, location
FROM employees e JOIN departments d
ON (e.dep_id = d.dep_id);
Inner & Outer Join
• Inner join t the join of two tables returning
only matched rows
• Left (right) outer join t the join of two tables
returning both matched and rows unable to be
matched from the left (right) table
• Full outer join t the join of two tables
returning the result of an inner join and the
rows unable to be matched from the left and
right tables
Outer Join Syntax
• Left outer join
SELECT e.last_name, d.name, d.location
FROM employees e LEFT OUTER JOIN departments d
ON (e.dep_id = d.dep_id);

• Full outer join


SELECT e.last_name, d.name, d.location
FROM employees e FULL OUTER JOIN departments d
ON (e.dep_id = d.dep_id);
Self Join
• A table is joined to itself
SELECT e.last_name || ' works for ' || m.last_name
FROM employees e JOIN employees m
ON (e.manager_id = m.emp_id);

Tabela: EMPLOYEES E Tabela: EMPLOYEES M


EMP_ID FIRST_NAME LAST_NAME MANAGER_ID EMP_ID FIRST_NAME LAST_NAME MANAGER_ID
100 John Smith 100 John Smith
101 Jessica Torn 100 101 Jessica Torn 100
102 Nick Ford 100 102 Nick Ford 100
103 Diana Wilson 100 103 Diana Wilson 100
104 Jennifer Kent 101 104 Jennifer Kent 101
105 David Brown 104 105 David Brown 104
106 Nicole Foster 104 106 Nicole Foster 104
107 Steven Anderson 101 107 Steven Anderson 101
108 Lisa Davis 107 108 Lisa Davis 107
109 Anne Taylor 107 109 Anne Taylor 107
110 Patricia Blake 107 110 Patricia Blake 107
111 John Parker 102 111 John Parker 102
112 Nicole Spencer 111 112 Nicole Spencer 111
join
Joining Several Tables
• Equijoin of n tables requires at least n-1 joining
conditions

SELECT e.last_name, d.name, e.salary,


jg.min_salary, jg.max_salary

FROM employees e
JOIN departments d ON (e.dep_id = d.dep_id)
JOIN job_grades jg ON (e.jg_id = jg.jg_id);
Exercises
1. Write a query to display the last name,
department id, and department name for all
employees who work in any department.
Order the results by the department name.
2. Display the last name, salary, and department
name of all employees who earn salary
greater than 4000 and earn an allowance.
3. Display the last name, salary for all employees
working in the department 'Operations'.
Exercises
4. Write a query to display the last name, job grade
name, and department name for all employees
(including those with no department) with the job
grade whose a minimum salary boundary is lower
than 4000.
5. Write a query to display the last name, department
name, and department location for all employees
who work in a room (office) which number is greater
than 200.
6. For employees in departments 20 or 30, display
the last name, department name, the name of
the employee's manager and department name of
their managers.
Exercises
7. Find all employees who joined the company
before their manager and display their last
name, hire date ~ooc emp Z]_
and hire date of their manager (labeled as
cuvPZ]_X
8. Display the last name and department name
for all employees including those who are not
assigned to any department. Replace the null
values in the department name column with
the string 'No department'.
Exercises
9. Display the last name and the last name of the
manager ~oocuvP _UvZ
department name for all employees who work
in the same department as their manager.
10.Create a query that for each employee displays
the last name, department id, and all the last
names of the employees who work in the
same department as a given worker. Give each
column an appropriate label.
References
• J. Price, Oracle Database 12c SQL, McGraw-Hill
Education, 2013
• Oracle 12c Documentation
http://www.oracle.com/pls/db121/homepage
Thank you!
Database Technology
in Business
Department of Information Technology
Subqueries I
Subquery
• SELECT statement embedded in another SELECT
statement (main query)
• Subquery executes and its output is used to
complete the condition in the main query
• Subquery synonyms: embedded query, inner query,
sub-SELECT
• Example
SELECT last_name
FROM employees
WHERE salary > (SELECT salary
FROM employees
WHERE last_name = 'Parker');
Types of Subqueries
• Single-row / Multiple-row
– Return single / multiple row(s)
• Single-column / Multiple-column
– Return single / multiple column value(s)
• Scalar subqueries
– Return exactly one value at one row
Operators for Subquery Conditions
• Single-row operators
– >, =, >=, <, <>, <=
• Multiple-row operators
– >, =, >=, <, <>, <= ANY, ALL
– [NOT] IN
– [NOT] EXISTS
• Guidelines for specifying subqueries:
– Subquery is enclosed in parentheses
– Subquery appears on the right side of the
comparison operator
– Single-row operator can be used with a single-row
subquery only
Subquery Categories
• Non-correlated
– Executed once before the main query
– S˙ [}]} complete the
condition for the main query
• Correlated
– Executed once for each candidate row at the main
query
– S˙ [}]} complete the
condition for the main query and filter its output
Non-correlated Subquery
• S˙ [}] independent from the main query
• Subquery is executed and returns the output
• Main query is executed once using the output returned by
the subquery

Main query
Which employees have a salary Subquery output
greater than Parker does?

Subquery
What’
s Parker’ssalary
?
Non-correlated Subquery Syntax
• Can be used in WHERE, HAVING, FROM
• General syntax in WHERE clause

SELECT select_list
FROM table1 Main query
WHERE expr operator
(SELECT select_list
Subquery
FROM table2);
Examples of Single-row
Non-correlated Subqueries (1/2)
• WZ]Zuo}˙Zo˙PZvPl[o˙ ?
SELECT last_name
FROM employees
WHERE salary > (SELECT salary
FROM employees
WHERE last_name = 'Parker');
• Which employees have the same manager as Torn does?
SELECT last_name, manager_id
FROM employees
WHERE manager_id = (SELECT manager_id
FROM employees
WHERE last_name = 'Torn');
Examples of Single-row
Non-correlated Subqueries (2/2)
• Which employees hired in the same department as the employee
of id=110 earn more than the employee of id=112?

SELECT last_name, dep_id, salary


FROM employees
WHERE dep_id = (SELECT dep_id
FROM employees
WHERE emp_id = 110)
AND salary > (SELECT salary
FROM employees
WHERE emp_id = 112);
Exercises
1. Display the last name, manager id, and
salary for all employees in the same
department as Anderson (excluding
Anderson).
2. Display the department id, last names and job
grade id for all employees who work in the
Engineering department.
3. Display all the employees who have worked
longer than Nichols.
Grouping Functions
in Single-row Subqueries
• Which employees have a salary greater than the average salary of
all employees?
SELECT last_name, salary
FROM employees
WHERE salary > (SELECT AVG(salary)
FROM employees);
• Which employees have a salary equal to the min salary of
employees hired in the department of id=20?
SELECT last_name, salary, dep_id
FROM employees
WHERE salary = (SELECT MIN(salary)
FROM employees
WHERE dep_id = 20);
Single-row Subqueries in
HAVING clause
• At which department the min salary is greater than the min salary in the
department of id=20?
SELECT dep_id, MIN(salary)
FROM employees
GROUP BY dep_id
HAVING MIN(salary) > (SELECT MIN(salary)
FROM employees
WHERE dep_id = 20);
• At which department there is the greatest average salary?
SELECT dep_id, AVG(salary)
FROM employees
GROUP BY dep_id
HAVING AVG(salary) = (SELECT MAX(AVG(salary))
FROM employees
GROUP BY dep_id);
Exercises
4. Display the last name and job grade id for
all the employees with an annual salary
(including allowance) greater than the average
annual remuneration (including allowance).
5. Create a query to display the last names and
salaries for all employees who earn a salary
that is higher than the salary of each employee
with the job grade id equal 9. Sort the results
on salary from highest to lowest.
Exercises at home
6. Display the last name and salary for all employees
who have the same boss as Ford.
7. Display the employee id and last names for all
employees who have a manager Anderson.
8. Display the employee id, last name, and salary for
all employees with a salary above the average
salary.
9. Display position id and minimum salary for
positions with minimum salary higher than
maxiumum salary of position with id equal to 4.
References
• C. Coronel, S. Morris, Database Systems: Design,
Implementation, & Management 12th Edition,
Course Technology, 2016
• J. Price, Oracle Database 12c SQL, McGraw-Hill
Education, 2013
• Oracle 12c Documentation
http://www.oracle.com/pls/db121/homepage
Thank you!

You might also like