+ All Categories
Home > Documents > Introduction to SQL. Contents 1.Relational Databases and Data Models 2.SQL 3.The HR Database Schema...

Introduction to SQL. Contents 1.Relational Databases and Data Models 2.SQL 3.The HR Database Schema...

Date post: 26-Mar-2015
Category:
Upload: zoe-watkins
View: 226 times
Download: 1 times
Share this document with a friend
Popular Tags:
97
Introduction to SQL
Transcript
Page 1: Introduction to SQL. Contents 1.Relational Databases and Data Models 2.SQL 3.The HR Database Schema in Oracle 4.Introducing SELECT Statement The WHERE.

Introduction to SQL

Page 2: Introduction to SQL. Contents 1.Relational Databases and Data Models 2.SQL 3.The HR Database Schema in Oracle 4.Introducing SELECT Statement The WHERE.

Contents

1. Relational Databases and Data Models

2. SQL

3. The HR Database Schema in Oracle

4. Introducing SELECT Statement

•The WHERE Clause

•Sorting with ORDER BY

•Selecting Data From Multiple Tables

Page 3: Introduction to SQL. Contents 1.Relational Databases and Data Models 2.SQL 3.The HR Database Schema in Oracle 4.Introducing SELECT Statement The WHERE.

Contents (2)

5. Selecting Data From Multiple Tables

•Natural Joins

•Join with USING Clause

•Inner Joins with ON Clause

•Left, Right and Full Outer Joins

•Cross Joins

6. Nested SELECT Statements

7. Aggregating Data

•Group Functions and GROUP BY

Page 4: Introduction to SQL. Contents 1.Relational Databases and Data Models 2.SQL 3.The HR Database Schema in Oracle 4.Introducing SELECT Statement The WHERE.

Contents (3)

8. Oracle SQL Functions

9. Oracle Data Types

10. Data Definition Language (DDL)

11. Creating Tables in Oracle

12. Inserting Data

13. Updating Data

14. Deleting Data

Page 5: Introduction to SQL. Contents 1.Relational Databases and Data Models 2.SQL 3.The HR Database Schema in Oracle 4.Introducing SELECT Statement The WHERE.

Relational DatabasesShort Overview

Page 6: Introduction to SQL. Contents 1.Relational Databases and Data Models 2.SQL 3.The HR Database Schema in Oracle 4.Introducing SELECT Statement The WHERE.

Relational Database Concepts

• The relational model consists of the following:

• Collection of tables (called relations)

• Set of operators to act on the relations

• Data integrity for accuracy and consistency

Page 7: Introduction to SQL. Contents 1.Relational Databases and Data Models 2.SQL 3.The HR Database Schema in Oracle 4.Introducing SELECT Statement The WHERE.

Definition of a Database

• A relational database is a collection of relations (two-dimensional tables)

Database Database

Table Name: Table Name: EMPLOYEESEMPLOYEES Table Name: Table Name: DEPARTMENTSDEPARTMENTS

EMPLOYEE_ID

FIRST_NAME

LAST_NAME EMAIL

100 Svetlin Nakov XXX

101 Rosen Spasov YYY

102 Danail Alexiev ZZZ

DEPARTMENT_ID

DEPARTMENT_NAME

MANAGER_ID

10 IT 200

20 Sales 201

50 Finances 124

Page 8: Introduction to SQL. Contents 1.Relational Databases and Data Models 2.SQL 3.The HR Database Schema in Oracle 4.Introducing SELECT Statement The WHERE.

Data Models

Database Database

Model of systemModel of systemin client's mindin client's mind

Table model ofTable model ofentity modelentity model

Entity model ofEntity model ofclient's modelclient's model

Page 9: Introduction to SQL. Contents 1.Relational Databases and Data Models 2.SQL 3.The HR Database Schema in Oracle 4.Introducing SELECT Statement The WHERE.

Entity Relationship Model

• Create an entity relationship diagram from business specifications or narratives

• Scenario

• “. . . Assign one or more employees to a department . . .”

• “. . . Some departments do not yet have assigned employees . . .”

EMPLOYEEEMPLOYEE#* #* numbernumber** namenameoo job titlejob title

DEPARTMENTDEPARTMENT#* #* numbernumber** namenameoo locationlocation

assigned toassigned to

composed ofcomposed of

Page 10: Introduction to SQL. Contents 1.Relational Databases and Data Models 2.SQL 3.The HR Database Schema in Oracle 4.Introducing SELECT Statement The WHERE.

Relating Multiple Tables

• Each row of data in a table is uniquely identified by a primary key (PK)

• You can logically relate data from multiple tables using foreign keys (FK)

Table Name: Table Name: EMPLOYEESEMPLOYEES Table Name: Table Name: DEPARTMENTSDEPARTMENTSEMPLOYEE_ID

FIRST_NAME

LAST_NAME DEPARTMENT_ID

100 Svetlin Nakov 80

101 Rosen Spasov 50

102 Danail Alexiev 90

DEPARTMENT_ID

DEPARTMENT_NAME

10 IT

20 Sales

50 Finances

Primary keyPrimary keyPrimary keyPrimary key Foreign keyForeign keyForeign keyForeign key Primary keyPrimary keyPrimary keyPrimary key

Page 11: Introduction to SQL. Contents 1.Relational Databases and Data Models 2.SQL 3.The HR Database Schema in Oracle 4.Introducing SELECT Statement The WHERE.

Database Terminology

Table Name: Table Name: EMPLOYEESEMPLOYEES

EMPLOYEE_ID FIRST_NAME LAST_NAME SALARY DEPARTMENT_ID

100 Mihail Stoynov 24000 80

101 Miroslav Nachev 17000 50

102 Danail Alexiev 90

103 Radoslav Ivanov 9000 60

104 Rosen Spasov 6000 90

RowRowRowRow

Primary Primary key columnkey column

Primary Primary key columnkey column

ColumnColumnColumnColumnForeign Foreign key columnkey column

Foreign Foreign key columnkey column Null valueNull valueNull valueNull value

FieldFieldFieldField

Page 12: Introduction to SQL. Contents 1.Relational Databases and Data Models 2.SQL 3.The HR Database Schema in Oracle 4.Introducing SELECT Statement The WHERE.

Relational Databases

• A relational database:

• Can be accessed and modified by executing Structured Query Language (SQL) statements

• Uses a set of operations to extract subset of the data

• Contains a collection of tables

• Relationships are defined between the tables

Page 13: Introduction to SQL. Contents 1.Relational Databases and Data Models 2.SQL 3.The HR Database Schema in Oracle 4.Introducing SELECT Statement The WHERE.

Communicating with a DB

Database Database

SQL statement isSQL statement issent to the databasesent to the database

SQL statement isSQL statement isenteredentered

SELECT SELECT department_name department_name FROM departmentsFROM departments

DEPARTMENT_NAME

IT

Sales

Finances

The result is returnedThe result is returned(usually as a table)(usually as a table)

Page 14: Introduction to SQL. Contents 1.Relational Databases and Data Models 2.SQL 3.The HR Database Schema in Oracle 4.Introducing SELECT Statement The WHERE.

The Structured Query Language (SQL)Introduction

Page 15: Introduction to SQL. Contents 1.Relational Databases and Data Models 2.SQL 3.The HR Database Schema in Oracle 4.Introducing SELECT Statement The WHERE.

What is SQL?

• Structured Query Language (SQL)

• Declarative language for query and manipulation of relational data

• SQL consists of:

• Data Manipulation Language (DML)

• SELECT, INSERT, UPDATE, DELETE

• Data Definition Language (DDL)

• CREATE, DROP, ALTER

• GRANT, REVOKE

Page 16: Introduction to SQL. Contents 1.Relational Databases and Data Models 2.SQL 3.The HR Database Schema in Oracle 4.Introducing SELECT Statement The WHERE.

Entity Relationship (E/R) DiagramsThe HR Database Schema in Oracle Express

Page 17: Introduction to SQL. Contents 1.Relational Databases and Data Models 2.SQL 3.The HR Database Schema in Oracle 4.Introducing SELECT Statement The WHERE.

The HR Database Schema in Oracle 10g

COUNTRIES

PK COUNTRY_ID

COUNTRY_NAMEFK1 REGION_ID

LOCATIONS

PK LOCATION_ID

STREET_ADDRESSPOSTAL_CODE

I1 CITYI3 STATE_PROVINCEFK1,I2 COUNTRY_ID

DEPARTMENTS

PK DEPARTMENT_ID

DEPARTMENT_NAMEFK1 MANAGER_IDFK2,I1 LOCATION_ID

REGIONS

PK REGION_ID

REGION_NAME

EMPLOYEES

PK EMPLOYEE_ID

I4 FIRST_NAMEI4 LAST_NAMEU1 EMAIL

PHONE_NUMBERHIRE_DATE

FK3,I2 JOB_IDSALARYCOMMISSION_PCT

FK2,I3 MANAGER_IDFK1,I1 DEPARTMENT_IDJOB_HISTORY

PK,FK2,I2 EMPLOYEE_IDPK START_DATE

END_DATEFK3,I3 JOB_IDFK1,I1 DEPARTMENT_ID

JOBS

PK JOB_ID

JOB_TITLEMIN_SALARYMAX_SALARY

Page 18: Introduction to SQL. Contents 1.Relational Databases and Data Models 2.SQL 3.The HR Database Schema in Oracle 4.Introducing SELECT Statement The WHERE.

SQL Language

Introducing SELECT Statement

Page 19: Introduction to SQL. Contents 1.Relational Databases and Data Models 2.SQL 3.The HR Database Schema in Oracle 4.Introducing SELECT Statement The WHERE.

Capabilities of SQL SELECT

Table 1Table 1 Table 2Table 2

Table 1Table 1 Table 1Table 1

SelectionSelectionTake some of the rowsTake some of the rows

ProjectionProjectionTake some of the columnsTake some of the columns

JoinJoinCombine Combine tables bytables bysome some columncolumn

Page 20: Introduction to SQL. Contents 1.Relational Databases and Data Models 2.SQL 3.The HR Database Schema in Oracle 4.Introducing SELECT Statement The WHERE.

Basic SELECT Statement

• SELECT identifies what columns

• FROM identifies which table

SELECT *|{[DISTINCT] column|expression SELECT *|{[DISTINCT] column|expression [alias],...}[alias],...}FROMFROM tabletable

Page 21: Introduction to SQL. Contents 1.Relational Databases and Data Models 2.SQL 3.The HR Database Schema in Oracle 4.Introducing SELECT Statement The WHERE.

SELECT Example

• Selecting all departments

• Selecting specific columns

SELECT * FROM DEPARTMENTSSELECT * FROM DEPARTMENTS

SELECTSELECT DEPARTMENT_ID,DEPARTMENT_ID, LOCATION_ID LOCATION_ID FROM DEPARTMENTSFROM DEPARTMENTS

DEPARTMENT_ID

DEPARTMENT_NAME MANAGER_ID LOCATION_ID

10 Administration 200 1700

20 Marketing 201 1800

50 Shipping 124 1900

DEPARTMENT_ID LOCATION_ID

10 1700

20 1800

50 1900

Page 22: Introduction to SQL. Contents 1.Relational Databases and Data Models 2.SQL 3.The HR Database Schema in Oracle 4.Introducing SELECT Statement The WHERE.

Arithmetic Operations

• Arithmetic operators are available:

• +, -, *, /

• Example:

SELECT LAST_NAME, SALARY, SALARY + 300SELECT LAST_NAME, SALARY, SALARY + 300FROM EMPLOYEESFROM EMPLOYEES

LAST_NAME SALARY SALARY + 300

King 24000 24300

Kochhar 17000 17300

De Haan 17000 17300

Page 23: Introduction to SQL. Contents 1.Relational Databases and Data Models 2.SQL 3.The HR Database Schema in Oracle 4.Introducing SELECT Statement The WHERE.

The null Value

• A null is a value that is unavailable, unassigned, unknown, or inapplicable

• Not the same as zero or a blank space

• Arithmetic expressions containing a null value are evaluated to null

SELECT LAST_NAME, MANAGER_ID FROM EMPLOYEESSELECT LAST_NAME, MANAGER_ID FROM EMPLOYEES

LAST_NAME MANAGER_ID

King (null)

Kochhar 100

De Haan 100

NULLNULL is displayed as is displayed as empty space or as empty space or as

(null)(null)

NULLNULL is displayed as is displayed as empty space or as empty space or as

(null)(null)

Page 24: Introduction to SQL. Contents 1.Relational Databases and Data Models 2.SQL 3.The HR Database Schema in Oracle 4.Introducing SELECT Statement The WHERE.

Column Alias

• Renames a column heading

• Useful with calculations

• Immediately follows the column name

• There is an optional AS keyword

• Double quotation marks if contains spaces

SELECT LAST_NAME SELECT LAST_NAME "Name""Name", 12*SALARY , 12*SALARY ASAS "Annual Salary""Annual Salary" FROM EMPLOYEES FROM EMPLOYEES

Name Annual Salary

King 288000

Kochhar 204000

Page 25: Introduction to SQL. Contents 1.Relational Databases and Data Models 2.SQL 3.The HR Database Schema in Oracle 4.Introducing SELECT Statement The WHERE.

Concatenation Operator

• Concatenates columns or character strings to other columns

• Is represented by two vertical bars (||)

• Creates a resultant column that is a character expression

SELECT LAST_NAME SELECT LAST_NAME |||| JOB_ID AS "Employees" JOB_ID AS "Employees"FROM EMPLOYEESFROM EMPLOYEES

Employees

KingAD_PRES

KochharAD_VP

De HaanAD_VP

Page 26: Introduction to SQL. Contents 1.Relational Databases and Data Models 2.SQL 3.The HR Database Schema in Oracle 4.Introducing SELECT Statement The WHERE.

Literal Character Strings

• A literal is a character, a number, or a date included in the SELECT list

• Date and character literal values must be enclosed within single quotation marks

• Each character string is output once for each row returned

SELECT LAST_NAME || SELECT LAST_NAME || ' is a '' is a ' || JOB_ID AS || JOB_ID AS "Employee Details" FROM EMPLOYEES"Employee Details" FROM EMPLOYEES

Employees

King is a AD_PRES

Kochhar is a AD_VP

De Haan is a AD_VP

Page 27: Introduction to SQL. Contents 1.Relational Databases and Data Models 2.SQL 3.The HR Database Schema in Oracle 4.Introducing SELECT Statement The WHERE.

Removing Duplicate Rows

• The default display of queries is all rows, including duplicate rows

• Eliminate duplicate rows by using the DISTINCT keyword in the SELECT clause

SELECT DEPARTMENT_IDSELECT DEPARTMENT_IDFROM EMPLOYEESFROM EMPLOYEES

DEPARTMENT_ID

90

90

60

...

SELECTSELECT DISTINCTDISTINCT DEPARTMENT_ID DEPARTMENT_IDFROM EMPLOYEESFROM EMPLOYEES

DEPARTMENT_ID

90

60

...

Page 28: Introduction to SQL. Contents 1.Relational Databases and Data Models 2.SQL 3.The HR Database Schema in Oracle 4.Introducing SELECT Statement The WHERE.

UNION and INTERSECT

• UNION combines the results from several SELECT statements

• The columns count and types should match

• INTERSECT makes logical intersection of given sets of records

SELECT FIRST_NAME AS NAMESELECT FIRST_NAME AS NAMEFROM EMPLOYEESFROM EMPLOYEESUNIONUNIONSELECT LAST_NAME AS NAME SELECT LAST_NAME AS NAME FROM EMPLOYEESFROM EMPLOYEES

NAME

Abel

Adam

Alana

Alberto

...

Page 29: Introduction to SQL. Contents 1.Relational Databases and Data Models 2.SQL 3.The HR Database Schema in Oracle 4.Introducing SELECT Statement The WHERE.

Limiting the Rows Selected

• Restrict the rows returned by using the WHERE clause:

• More examples:

SELECT LAST_NAME, SELECT LAST_NAME, DEPARTMENT_ID FROM DEPARTMENT_ID FROM EMPLOYEES EMPLOYEES WHEREWHERE DEPARTMENT_ID = 90DEPARTMENT_ID = 90

SELECT FIRST_NAME, LAST_NAME, JOB_ID FROM SELECT FIRST_NAME, LAST_NAME, JOB_ID FROM EMPLOYEES WHERE LAST_NAME = 'Whalen'EMPLOYEES WHERE LAST_NAME = 'Whalen'

LAST_NAME DEPARTMENT_ID

King 90

Kochhar 90

De Haan 90

SELECT LAST_NAME, SALARY FROM EMPLOYEESSELECT LAST_NAME, SALARY FROM EMPLOYEESWHERE SALARY <= 3000WHERE SALARY <= 3000

Page 30: Introduction to SQL. Contents 1.Relational Databases and Data Models 2.SQL 3.The HR Database Schema in Oracle 4.Introducing SELECT Statement The WHERE.

• Using BETWEEN operator to specify a range:

• Using IN / NOT IN operators to specify a set of values:

• Using LIKE operator to specify a pattern:

• Using BETWEEN operator to specify a range:

• Using IN / NOT IN operators to specify a set of values:

• Using LIKE operator to specify a pattern:

Other Comparison Conditions

SELECT LAST_NAME, SALARY FROM EMPLOYEESSELECT LAST_NAME, SALARY FROM EMPLOYEESWHERE SALARY BETWEEN 2500 AND 3000WHERE SALARY BETWEEN 2500 AND 3000

SELECT FIRST_NAME, LAST_NAME, MANAGER_ID FROM SELECT FIRST_NAME, LAST_NAME, MANAGER_ID FROM EMPLOYEES WHERE MANAGER_ID IN (100, 101, 201)EMPLOYEES WHERE MANAGER_ID IN (100, 101, 201)

SELECT FIRST_NAME FROM EMPLOYEESSELECT FIRST_NAME FROM EMPLOYEESWHERE FIRST_NAME LIKE 'S%'WHERE FIRST_NAME LIKE 'S%'

Page 31: Introduction to SQL. Contents 1.Relational Databases and Data Models 2.SQL 3.The HR Database Schema in Oracle 4.Introducing SELECT Statement The WHERE.

• Checking for NULL value:

• Note: COLUMN=NULL is always false!

• Using OR and AND operators:

• Checking for NULL value:

• Note: COLUMN=NULL is always false!

• Using OR and AND operators:

Other Comparison Conditions (2)

SELECT LAST_NAME, MANAGER_ID FROM EMPLOYEESSELECT LAST_NAME, MANAGER_ID FROM EMPLOYEESWHERE MANAGER_ID IS NULLWHERE MANAGER_ID IS NULL

SELECT LAST_NAME, JOB_ID, SALARY FROM EMPLOYEESSELECT LAST_NAME, JOB_ID, SALARY FROM EMPLOYEESWHERE SALARY >= 1000 AND JOB_ID LIKE '%MAN%'WHERE SALARY >= 1000 AND JOB_ID LIKE '%MAN%'

SELECT LAST_NAME FROM EMPLOYEESSELECT LAST_NAME FROM EMPLOYEESWHERE COMMISSION_PCT IS NOT NULLWHERE COMMISSION_PCT IS NOT NULL OR LAST_NAME LIKE '%S%'OR LAST_NAME LIKE '%S%'

Page 32: Introduction to SQL. Contents 1.Relational Databases and Data Models 2.SQL 3.The HR Database Schema in Oracle 4.Introducing SELECT Statement The WHERE.

Sorting with ORDER BY

• Sort rows with the ORDER BY clause• ASC: ascending order, default• DESC: descending order

SELECT LAST_NAME, SELECT LAST_NAME, HIRE_DATE FROM EMPLOYEES HIRE_DATE FROM EMPLOYEES ORDER BYORDER BY HIRE_DATE HIRE_DATE

LAST_NAME HIRE_DATE

King 17-JUN-87

Whalen 17-SEP-87

Kochhar 21-SEP-89

SELECT LAST_NAME, SELECT LAST_NAME, HIRE_DATE FROM EMPLOYEES HIRE_DATE FROM EMPLOYEES ORDER BYORDER BY HIRE_DATE HIRE_DATE DESCDESC

LAST_NAME HIRE_DATE

Zlotkey 29-JAN-00

Mourgos 16-NOV-99

Grant 24-MAY-99

Page 33: Introduction to SQL. Contents 1.Relational Databases and Data Models 2.SQL 3.The HR Database Schema in Oracle 4.Introducing SELECT Statement The WHERE.

SQL LanguageSelecting Data From Multiple Tables

Page 34: Introduction to SQL. Contents 1.Relational Databases and Data Models 2.SQL 3.The HR Database Schema in Oracle 4.Introducing SELECT Statement The WHERE.

Data from Multiple Tables

• Sometimes you need data from more than one table:

LAST_NAME DEPARTMENT_ID

King 90

Kochhar 90

Fay 20

DEPARTMENT_ID

DEPARTMENT_NAME

90 Executive

20 Marketing

10 Administration

LAST_NAME DEPARTMENT_NAME

King Executive

Fay Marketing

Kochhar Executive

Page 35: Introduction to SQL. Contents 1.Relational Databases and Data Models 2.SQL 3.The HR Database Schema in Oracle 4.Introducing SELECT Statement The WHERE.

Cartesian Product

• This will produce Cartesian product:

• The result:

SELECT LAST_NAME, DEPARTMENT_NAMESELECT LAST_NAME, DEPARTMENT_NAMEFROM EMPLOYEES, DEPARTMENTSFROM EMPLOYEES, DEPARTMENTS

LAST_NAME DEPARTMENT_NAME

King Executive

King Marketing

King Administration

Kochhar Executive

Kochhar Marketing

.. ..

Page 36: Introduction to SQL. Contents 1.Relational Databases and Data Models 2.SQL 3.The HR Database Schema in Oracle 4.Introducing SELECT Statement The WHERE.

Cartesian Product

• A Cartesian product is formed when:

• A join condition is omitted

• A join condition is invalid

• All rows in the first table are joined to all rows in the second table

• To avoid a Cartesian product, always include a valid join condition

Page 37: Introduction to SQL. Contents 1.Relational Databases and Data Models 2.SQL 3.The HR Database Schema in Oracle 4.Introducing SELECT Statement The WHERE.

Types of Joins

• Natural joins

• Join with USING clause

• Inner joins with ON clause

• Left, right and full outer joins

• Cross joins

Page 38: Introduction to SQL. Contents 1.Relational Databases and Data Models 2.SQL 3.The HR Database Schema in Oracle 4.Introducing SELECT Statement The WHERE.

Natural Join

• The NATURAL JOIN combines the rows from two tables that have equal values in all matched by name columns

SELECT DEPARTMENT_ID, DEPARTMENT_NAME,SELECT DEPARTMENT_ID, DEPARTMENT_NAME, LOCATION_ID, CITYLOCATION_ID, CITYFROM DEPARTMENTS FROM DEPARTMENTS NATURAL JOINNATURAL JOIN LOCATIONS LOCATIONS

DEPARTMENT_ID

DEPARTMENT_NAME LOCATION_ID CITY

60 IT 1400 Southlake

50 Shipping 1500 San Francisco

10 Administration 1700 Seattle

90 Executive 1700 Seattle

... ... ... ...

Page 39: Introduction to SQL. Contents 1.Relational Databases and Data Models 2.SQL 3.The HR Database Schema in Oracle 4.Introducing SELECT Statement The WHERE.

Join with USING Clause

• If several columns have the same names we can limit the NATURAL JOIN to only one of them by the USING clause:

SELECT E.EMPLOYEE_ID, E.LAST_NAME,SELECT E.EMPLOYEE_ID, E.LAST_NAME, D.LOCATION_ID, D.DEPARTMENT_NAMED.LOCATION_ID, D.DEPARTMENT_NAMEFROM EMPLOYEES E FROM EMPLOYEES E JOINJOIN DEPARTMENTS D DEPARTMENTS D USING USING (DEPARTMENT_ID)(DEPARTMENT_ID)

EMPLOYEE_ID LAST_NAME LOCATION_ID DEPARTMENT_NAME

102 De Haan 1700 Executive

103 Hunold 1400 IT

104 Ernst 1400 IT

... ... ... ...

Page 40: Introduction to SQL. Contents 1.Relational Databases and Data Models 2.SQL 3.The HR Database Schema in Oracle 4.Introducing SELECT Statement The WHERE.

Inner Join with ON Clause

• To specify arbitrary conditions or specify columns to join, the ON clause is used

• Such JOIN is called also INNER JOIN

SELECT E.EMPLOYEE_ID, E.LAST_NAME,SELECT E.EMPLOYEE_ID, E.LAST_NAME, E.DEPARTMENT_ID, D.DEPARTMENT_ID, D.LOCATION_IDE.DEPARTMENT_ID, D.DEPARTMENT_ID, D.LOCATION_IDFROM EMPLOYEES E FROM EMPLOYEES E JOINJOIN DEPARTMENTS D DEPARTMENTS D ONON (E.DEPARTMENT_ID = D.DEPARTMENT_ID) (E.DEPARTMENT_ID = D.DEPARTMENT_ID)

EMPLOYEE_ID LAST_NAME DEPARTMENT_ID

DEPARTMENT_ID

LOCATION_ID

200 Whalen 10 10 1700

201 Hartstein 20 20 1800

202 Fay 20 20 1800

Page 41: Introduction to SQL. Contents 1.Relational Databases and Data Models 2.SQL 3.The HR Database Schema in Oracle 4.Introducing SELECT Statement The WHERE.

INNER vs. OUTER Joins

• The join of two tables returning only matched rows is an inner join

• A join between two tables that returns the results of the inner join as well as unmatched rows from the left (or right) table is a left (or right) outer join

• A join between two tables that returns the results of an inner join as well as the results of a left and right join is a full outer join

Page 42: Introduction to SQL. Contents 1.Relational Databases and Data Models 2.SQL 3.The HR Database Schema in Oracle 4.Introducing SELECT Statement The WHERE.

INNER JOIN

SELECT E.FIRST_NAME || ' ' || E.LAST_NAME ASSELECT E.FIRST_NAME || ' ' || E.LAST_NAME AS MANAGER_NAME, D.DEPARTMENT_ID, D.DEPARTMENT_NAMEMANAGER_NAME, D.DEPARTMENT_ID, D.DEPARTMENT_NAMEFROM EMPLOYEES E FROM EMPLOYEES E INNER JOININNER JOIN DEPARTMENTS D DEPARTMENTS D ONON E.EMPLOYEE_ID=D.MANAGER_ID E.EMPLOYEE_ID=D.MANAGER_ID

MANAGER_NAME DEPARTMENT_ID DEPARTMENT_ NAME

Jennifer Whalen 10 Administration

Michael Hartstein 20 Marketing

Den Raphaely 30 Purchasing

Susan Mavris 40 Human Resources

Adam Fripp 50 Shipping

Alexander Hunold 60 IT

Hermann Baer 70 Public Relations

... ... ...

Page 43: Introduction to SQL. Contents 1.Relational Databases and Data Models 2.SQL 3.The HR Database Schema in Oracle 4.Introducing SELECT Statement The WHERE.

LEFT OUTER JOIN

SELECT E.FIRST_NAME || ' ' || E.LAST_NAME ASSELECT E.FIRST_NAME || ' ' || E.LAST_NAME AS MANAGER_NAME, D.DEPARTMENT_ID, D.DEPARTMENT_NAMEMANAGER_NAME, D.DEPARTMENT_ID, D.DEPARTMENT_NAMEFROM EMPLOYEES E FROM EMPLOYEES E LEFT OUTER JOINLEFT OUTER JOIN DEPARTMENTS D DEPARTMENTS D ONON E.EMPLOYEE_ID=D.MANAGER_ID E.EMPLOYEE_ID=D.MANAGER_ID

MANAGER_NAME DEPARTMENT_ID DEPARTMENT_ NAME

Jennifer Whalen 10 Administration

Michael Hartstein 20 Marketing

Den Raphaely 30 Purchasing

Clara Vishney (null) (null)

Jason Mallin (null) (null)

Hazel Philtanker (null) (null)

Nanette Cambrault (null) (null)

... ... ...

Page 44: Introduction to SQL. Contents 1.Relational Databases and Data Models 2.SQL 3.The HR Database Schema in Oracle 4.Introducing SELECT Statement The WHERE.

RIGHT OUTER JOIN

SELECT E.FIRST_NAME || ' ' || E.LAST_NAME ASSELECT E.FIRST_NAME || ' ' || E.LAST_NAME AS MANAGER_NAME, D.DEPARTMENT_ID, D.DEPARTMENT_NAMEMANAGER_NAME, D.DEPARTMENT_ID, D.DEPARTMENT_NAMEFROM EMPLOYEES E FROM EMPLOYEES E RIGHT OUTER JOINRIGHT OUTER JOIN DEPARTMENTS D DEPARTMENTS D ONON E.EMPLOYEE_ID=D.MANAGER_ID E.EMPLOYEE_ID=D.MANAGER_ID

MANAGER_NAME DEPARTMENT_ID DEPARTMENT_ NAME

Jennifer Whalen 10 Administration

Michael Hartstein 20 Marketing

Den Raphaely 30 Purchasing

(null) 120 Treasury

(null) 130 Corporate Tax

(null) 140 Control And Credit

(null) 150 Shareholder Services

... ... ...

Page 45: Introduction to SQL. Contents 1.Relational Databases and Data Models 2.SQL 3.The HR Database Schema in Oracle 4.Introducing SELECT Statement The WHERE.

FULL OUTER JOIN

SELECT E.FIRST_NAME || ' ' || E.LAST_NAME ASSELECT E.FIRST_NAME || ' ' || E.LAST_NAME AS MANAGER_NAME, D.DEPARTMENT_ID, D.DEPARTMENT_NAMEMANAGER_NAME, D.DEPARTMENT_ID, D.DEPARTMENT_NAMEFROM EMPLOYEES E FROM EMPLOYEES E FULL OUTER JOINFULL OUTER JOIN DEPARTMENTS D DEPARTMENTS D ONON E.EMPLOYEE_ID=D.MANAGER_ID E.EMPLOYEE_ID=D.MANAGER_ID

MANAGER_NAME DEPARTMENT_ID DEPARTMENT_ NAME

Jennifer Whalen 10 Administration

Michael Hartstein 20 Marketing

... ... ...

Clara Vishney (null) (null)

Jason Mallin (null) (null)

... ... ...

(null) 150 Shareholder Services

... ... ...

Page 46: Introduction to SQL. Contents 1.Relational Databases and Data Models 2.SQL 3.The HR Database Schema in Oracle 4.Introducing SELECT Statement The WHERE.

Three-Way Joins

• A three-way join is a join of three tables

SELECT E.EMPLOYEE_ID, CITY, DEPARTMENT_NAME SELECT E.EMPLOYEE_ID, CITY, DEPARTMENT_NAME FROM EMPLOYEES EFROM EMPLOYEES EJOINJOIN DEPARTMENTS D DEPARTMENTS D ONON D.DEPARTMENT_ID = E.DEPARTMENT_ID D.DEPARTMENT_ID = E.DEPARTMENT_IDJOINJOIN LOCATIONS L LOCATIONS L ONON D.LOCATION_ID = L.LOCATION_ID D.LOCATION_ID = L.LOCATION_ID

EMPLOYEE_ID CITY DEPARTMENT_ NAME

103 Southlake IT

104 Southlake IT

124 San Francisco Administration

... ... ...

Page 47: Introduction to SQL. Contents 1.Relational Databases and Data Models 2.SQL 3.The HR Database Schema in Oracle 4.Introducing SELECT Statement The WHERE.

Cross Join

• The CROSS JOIN clause produces the cross-product of two tables• Same as a Cartesian product• Not often used

SELECT LAST_NAME, DEPARTMENT_NAMESELECT LAST_NAME, DEPARTMENT_NAMEFROM EMPLOYEES FROM EMPLOYEES CROSS JOINCROSS JOIN DEPARTMENTS DEPARTMENTS

LAST_NAME DEPARTMENT_NAME

King Executive

King Marketing

King Administration

Kochhar Executive

.. ..

Page 48: Introduction to SQL. Contents 1.Relational Databases and Data Models 2.SQL 3.The HR Database Schema in Oracle 4.Introducing SELECT Statement The WHERE.

Additional Conditions

• You can apply additional conditions in the WHERE clause:

SELECT E.EMPLOYEE_ID, SELECT E.EMPLOYEE_ID, E.FIRST_NAME || ' ' || E.LAST_NAME AS NAME, E.FIRST_NAME || ' ' || E.LAST_NAME AS NAME, E.MANAGER_ID, E.DEPARTMENT_ID, D.DEPARTMENT_NAMEE.MANAGER_ID, E.DEPARTMENT_ID, D.DEPARTMENT_NAMEFROM EMPLOYEES E JOIN DEPARTMENTS D ONFROM EMPLOYEES E JOIN DEPARTMENTS D ON (E.DEPARTMENT_ID = D.DEPARTMENT_ID)(E.DEPARTMENT_ID = D.DEPARTMENT_ID)WHERE E.MANAGER_ID = 149WHERE E.MANAGER_ID = 149

EMPLOYEE_ID

NAME MANAGER_ID

DEPARTMENT_ID

DEPARTMENT_NAME

174 Ellen Abel 149 80 Sales

175 Alyssa Hutton 149 80 Sales

... ... ... ... ...

Page 49: Introduction to SQL. Contents 1.Relational Databases and Data Models 2.SQL 3.The HR Database Schema in Oracle 4.Introducing SELECT Statement The WHERE.

SQL Language

Nested SELECT Statements

Page 50: Introduction to SQL. Contents 1.Relational Databases and Data Models 2.SQL 3.The HR Database Schema in Oracle 4.Introducing SELECT Statement The WHERE.

Nested SELECT Statements

• SELECT statements can be nested in the where clause

• Note: Always prefer joins to nested SELECT statements (better performance)

SELECT FIRST_NAME, LAST_NAME, SALARYSELECT FIRST_NAME, LAST_NAME, SALARYFROM EMPLOYEESFROM EMPLOYEESWHERE SALARY = WHERE SALARY = (SELECT MAX(SALARY) FROM EMPLOYEES)(SELECT MAX(SALARY) FROM EMPLOYEES)

SELECT FIRST_NAME, LAST_NAME, SALARYSELECT FIRST_NAME, LAST_NAME, SALARYFROM EMPLOYEESFROM EMPLOYEESWHERE DEPARTMENT_ID IN WHERE DEPARTMENT_ID IN (SELECT DEPARTMENT_ID FROM DEPARTMENTS(SELECT DEPARTMENT_ID FROM DEPARTMENTS WHERE DEPARTMENT_NAME='Accounting')WHERE DEPARTMENT_NAME='Accounting')

Page 51: Introduction to SQL. Contents 1.Relational Databases and Data Models 2.SQL 3.The HR Database Schema in Oracle 4.Introducing SELECT Statement The WHERE.

• Using the EXISTS operator in SELECT statements

• Find all employees that have worked in the past in the department #110

• Using the EXISTS operator in SELECT statements

• Find all employees that have worked in the past in the department #110

Using the EXISTS operator

SELECT FIRST_NAME, LAST_NAME FROM EMPLOYEES ESELECT FIRST_NAME, LAST_NAME FROM EMPLOYEES EWHERE EXISTS WHERE EXISTS (SELECT EMPLOYEE_ID FROM JOB_HISTORY JH(SELECT EMPLOYEE_ID FROM JOB_HISTORY JH WHERE DEPARTMENT_ID = 110 ANDWHERE DEPARTMENT_ID = 110 AND JH.EMPLOYEE_ID=E.EMPLOYEE_ID)JH.EMPLOYEE_ID=E.EMPLOYEE_ID)

Page 52: Introduction to SQL. Contents 1.Relational Databases and Data Models 2.SQL 3.The HR Database Schema in Oracle 4.Introducing SELECT Statement The WHERE.

SQL LanguageAggregating Data

Page 53: Introduction to SQL. Contents 1.Relational Databases and Data Models 2.SQL 3.The HR Database Schema in Oracle 4.Introducing SELECT Statement The WHERE.

Group Functions

• Group functions operate on sets of rows to give one result per group

EMPLOYEE_ID SALARY

100 24000

101 17000

102 17000

103 9000

104 6000

... ...

MAX(SALARY)

24000

Page 54: Introduction to SQL. Contents 1.Relational Databases and Data Models 2.SQL 3.The HR Database Schema in Oracle 4.Introducing SELECT Statement The WHERE.

Group Functions in SQL

• COUNT(*) – count of the selected rows

• SUM(column) – sum of the values in given column from the selected rows

• AVG(column) – average of the values in given column

• MAX(column) – the maximal value in given column

• MIN(column) – the minimal value in given column

Page 55: Introduction to SQL. Contents 1.Relational Databases and Data Models 2.SQL 3.The HR Database Schema in Oracle 4.Introducing SELECT Statement The WHERE.

AVG() and SUM() Functions

• You can use AVG() and SUM() for numeric data types

SELECT AVG(SALARY), MAX(SALARY),SELECT AVG(SALARY), MAX(SALARY), MIN(SALARY), SUM(SALARY)MIN(SALARY), SUM(SALARY)FROM EMPLOYEESFROM EMPLOYEESWHERE JOB_ID LIKE '%REP%'WHERE JOB_ID LIKE '%REP%'

AVG(SALARY) MAX(SALARY) MIN(SALARY) SUM(SALARY)

8272.72 11500 6000 273000

Page 56: Introduction to SQL. Contents 1.Relational Databases and Data Models 2.SQL 3.The HR Database Schema in Oracle 4.Introducing SELECT Statement The WHERE.

MIN() and MAX() Functions

• You can use MIN() and MAX() for any data type (number, date, varchar, ...)

• Displaying the first and last employee's name in alphabetical order:

SELECT MIN(HIRE_DATE), MAX(HIRE_DATE)SELECT MIN(HIRE_DATE), MAX(HIRE_DATE)FROM EMPLOYEESFROM EMPLOYEES

MIN(HIRE_DATE) MAX(HIRE_DATE)

17-JUN-1987 29-JAN-00

SELECT MIN(LAST_NAME), MAX(LAST_NAME)SELECT MIN(LAST_NAME), MAX(LAST_NAME)FROM EMPLOYEESFROM EMPLOYEES

Page 57: Introduction to SQL. Contents 1.Relational Databases and Data Models 2.SQL 3.The HR Database Schema in Oracle 4.Introducing SELECT Statement The WHERE.

The COUNT(…) Function

• COUNT(*) returns the number of rows in the result table

• COUNT(expr) returns the number of rows with non-null values for the expr

SELECT COUNT(*) FROM EMPLOYEESSELECT COUNT(*) FROM EMPLOYEESWHERE DEPARTMENT_ID = 50WHERE DEPARTMENT_ID = 50

COUNT(*)

5

SELECT COUNT(COMMISSION_PCT)SELECT COUNT(COMMISSION_PCT)FROM EMPLOYEESFROM EMPLOYEESWHERE DEPARTMENT_ID = 80WHERE DEPARTMENT_ID = 80

COUNT(COMMISION_PCT)

3

Page 58: Introduction to SQL. Contents 1.Relational Databases and Data Models 2.SQL 3.The HR Database Schema in Oracle 4.Introducing SELECT Statement The WHERE.

Group Functions and Nulls

• Group functions ignore null values in the column

• If each null value in COMMISSION_PCT is considered as 0 and is included in the calculation, the result will be 0.0425

SELECT AVG(COMMISSION_PCT) FROM EMPLOYEESSELECT AVG(COMMISSION_PCT) FROM EMPLOYEES

AVG(COMMISSION_PCT)

.2229

Page 59: Introduction to SQL. Contents 1.Relational Databases and Data Models 2.SQL 3.The HR Database Schema in Oracle 4.Introducing SELECT Statement The WHERE.

SQL LanguageGroup Functions and theGROUP BY Statement

Page 60: Introduction to SQL. Contents 1.Relational Databases and Data Models 2.SQL 3.The HR Database Schema in Oracle 4.Introducing SELECT Statement The WHERE.

Creating Groups of Data

DEPARTMENT_ID SALARY

50 3100

50 3000

50 2600

50 2600

20 4400

20 13000

20 6000

40 6500

40 10000

110 12000

110 8300

... ...

EMPLOYEESEMPLOYEES

11300113001130011300

23400234002340023400

16500165001650016500

20300203002030020300

DEPARTMENT_ID

SUM(SALARY)

50 11300

20 23400

40 16500

110 20300

... ...

Page 61: Introduction to SQL. Contents 1.Relational Databases and Data Models 2.SQL 3.The HR Database Schema in Oracle 4.Introducing SELECT Statement The WHERE.

The GROUP BY Statement

• We can divide rows in a table into smaller groups by using the GROUP BY clause

• The syntax:

• The <group_by_expression> is a list of columns

SELECT <SELECT <columns>columns>, <, <group_function(column)>group_function(column)>FROM <FROM <table>table>[WHERE <[WHERE <condition>condition>]][GROUP BY[GROUP BY <<group_by_expression>group_by_expression>]][ORDER BY[ORDER BY <<columnscolumns>>

Page 62: Introduction to SQL. Contents 1.Relational Databases and Data Models 2.SQL 3.The HR Database Schema in Oracle 4.Introducing SELECT Statement The WHERE.

The GROUP BY Statement

• Example of grouping data:

• The GROUP BY column does not have to be in the SELECT list

SELECT DEPARTMENT_ID, SUM(SALARY)SELECT DEPARTMENT_ID, SUM(SALARY)FROM EMPLOYEESFROM EMPLOYEESGROUP BY DEPARTMENT_IDGROUP BY DEPARTMENT_ID

DEPARTMENT_ID SUM(SALARY)

100 51600

30 24900

(null) 7000

... ...

Page 63: Introduction to SQL. Contents 1.Relational Databases and Data Models 2.SQL 3.The HR Database Schema in Oracle 4.Introducing SELECT Statement The WHERE.

Grouping by Several Columns

DEPARTMENT_ID

JOB_ID SALARY

20 AD_ASST 4400

20 MK_MAN 13000

20 MK_MAN 12000

30 PU_CLERK 2500

30 PU_CLERK 2500

30 PU_CLERK 2500

30 PU_MAN 11000

30 PU_MAN 11500

30 PU_MAN 10000

30 PU_MAN 11000

... ... ...

4400440044004400

25000250002500025000

7500750075007500

DPT_ID JOB_ID SUM(SALARY)

20 AD_ASST 4400

20 MK_MAN 25000

30 PU_CLERK 7500

30 PU_MAN 43500

... ... ...43500435004350043500

EMPLOYEESEMPLOYEESEMPLOYEESEMPLOYEES

EMPLOYEESEMPLOYEESEMPLOYEESEMPLOYEES

Page 64: Introduction to SQL. Contents 1.Relational Databases and Data Models 2.SQL 3.The HR Database Schema in Oracle 4.Introducing SELECT Statement The WHERE.

Grouping by Several Columns – Example

• Example of grouping data by several columns:

SELECT DEPARTMENT_ID, JOB_ID,SELECT DEPARTMENT_ID, JOB_ID, COUNT(EMPLOYEE_ID), SUM(SALARY)COUNT(EMPLOYEE_ID), SUM(SALARY)FROM EMPLOYEESFROM EMPLOYEESGROUP BY DEPARTMENT_ID, JOB_IDGROUP BY DEPARTMENT_ID, JOB_IDORDER BY SUM(SALARY) DESCORDER BY SUM(SALARY) DESC

DEPARTMENT_ID JOB_ID COUNT(EMPLOYEE_ID)

SUM(SALARY)

80 SA_REP 29 243500

50 SH_CLERK 20 64300

80 SA_MAN 5 61000

... ... ... ...

Page 65: Introduction to SQL. Contents 1.Relational Databases and Data Models 2.SQL 3.The HR Database Schema in Oracle 4.Introducing SELECT Statement The WHERE.

Illegal Queries

• This SELECT statement is illegal

• Can not combine columns with groups functions unless when using GROUP BY

• This SELECT statement is also illegal

• Can not use WHERE for group functions

SELECT DEPARTMENT_ID, COUNT(LAST_NAME)SELECT DEPARTMENT_ID, COUNT(LAST_NAME)FROM EMPLOYEESFROM EMPLOYEES

SELECT DEPARTMENT_ID, AVG(SALARY)SELECT DEPARTMENT_ID, AVG(SALARY)FROM EMPLOYEESFROM EMPLOYEESWHERE AVG(SALARY) > 8000WHERE AVG(SALARY) > 8000GROUP BY DEPARTMENT_ID;GROUP BY DEPARTMENT_ID;

Page 66: Introduction to SQL. Contents 1.Relational Databases and Data Models 2.SQL 3.The HR Database Schema in Oracle 4.Introducing SELECT Statement The WHERE.

Using GROUP BY with HAVING Clause

• HAVING works like WHERE but is used for the grouping functions

SELECT DEPARTMENT_ID,SELECT DEPARTMENT_ID, COUNT(EMPLOYEE_ID), COUNT(EMPLOYEE_ID), AVGAVG(SALARY)(SALARY)FROM EMPLOYEESFROM EMPLOYEESGROUP BY DEPARTMENT_IDGROUP BY DEPARTMENT_IDHAVING COUNT(EMPLOYEE_ID) BETWEEN 3 AND 6HAVING COUNT(EMPLOYEE_ID) BETWEEN 3 AND 6

DEPARTMENT_ID COUNT(EMPLOYEE_ID) AVG(SALARY)

100 6 8600

30 6 4150

90 3 19333.33

60 5 5760

Page 67: Introduction to SQL. Contents 1.Relational Databases and Data Models 2.SQL 3.The HR Database Schema in Oracle 4.Introducing SELECT Statement The WHERE.

Using Grouping Functions and Table Joins

• We can apply grouping function from joined tables

SELECT COUNT(*) AS EMPS, DEPARTMENT_NAMESELECT COUNT(*) AS EMPS, DEPARTMENT_NAMEFROM EMPLOYEES E JOIN DEPARTMENTS DFROM EMPLOYEES E JOIN DEPARTMENTS D ON E.DEPARTMENT_ID=D.DEPARTMENT_IDON E.DEPARTMENT_ID=D.DEPARTMENT_IDWHEREWHERE HIRE_DATE BETWEEN '1991-1-1' AND '1997-12-31'HIRE_DATE BETWEEN '1991-1-1' AND '1997-12-31'GROUP BY DEPARTMENT_NAMEGROUP BY DEPARTMENT_NAMEHAVING COUNT(*) > 5HAVING COUNT(*) > 5ORDER BY EMPS DESCORDER BY EMPS DESC

EMPS DEPARTMENT_NAME

19 Shipping

15 Sales

Page 68: Introduction to SQL. Contents 1.Relational Databases and Data Models 2.SQL 3.The HR Database Schema in Oracle 4.Introducing SELECT Statement The WHERE.

Oracle Data TypesOverview

Page 69: Introduction to SQL. Contents 1.Relational Databases and Data Models 2.SQL 3.The HR Database Schema in Oracle 4.Introducing SELECT Statement The WHERE.

Oracle Data Types

• NUMBER – integer number (up to 38 digits)

• NUMBER(p, s) – integer/real number of given precision p and scale s

• NUMBER(10, 2) – fixed point real number

• VARCHAR2(size) – string of variable length up to given size (locale specific)

• VARCHAR2(50) – string of length up to 50

• NVARCHAR2(size) – Unicode string of variable length up to given size

Page 70: Introduction to SQL. Contents 1.Relational Databases and Data Models 2.SQL 3.The HR Database Schema in Oracle 4.Introducing SELECT Statement The WHERE.

Oracle Data Types (2)

• DATE – date between Jan 1, 4712 BC and Dec 31, 9999 AD

• TIMESTAMP – date and time (year, month, day, hour, minute, and seconds)

• Precision can be defined

• BLOB – binary large data object, RAW data (up to 128 TB)

• Can contain photos, videos, etc.

• CLOB, NCLOB – character large data object (up to 128 TB)

Page 71: Introduction to SQL. Contents 1.Relational Databases and Data Models 2.SQL 3.The HR Database Schema in Oracle 4.Introducing SELECT Statement The WHERE.

SQL LanguageData Definition Language (DDL)

Page 72: Introduction to SQL. Contents 1.Relational Databases and Data Models 2.SQL 3.The HR Database Schema in Oracle 4.Introducing SELECT Statement The WHERE.

Data Definition Language

• Types of commands

• Defining / editing objects

• CREATE

• ALTER

• DROP

Page 73: Introduction to SQL. Contents 1.Relational Databases and Data Models 2.SQL 3.The HR Database Schema in Oracle 4.Introducing SELECT Statement The WHERE.

Creating Objects

• CREATE / CREATE OR REPLACE commands• CREATE TABLE <name> (<fields definitions>)

• CREATE SEQUENCE <name>

• CREATE VIEW <name> AS <select>

CREATE TABLE PERSONS (CREATE TABLE PERSONS ( PERSON_ID INTEGER NOT NULL,PERSON_ID INTEGER NOT NULL, NAME NVARCHAR2(50) NOT NULL,NAME NVARCHAR2(50) NOT NULL, CONSTRAINT PERSON_PK PRIMARY KEY(PERSON_ID)CONSTRAINT PERSON_PK PRIMARY KEY(PERSON_ID)))

CREATE OR REPLACE VIEW PERSONS_TOP_10 ASCREATE OR REPLACE VIEW PERSONS_TOP_10 ASSELECT NAME FROM PERSONS WHERE ROWNUM <= 10SELECT NAME FROM PERSONS WHERE ROWNUM <= 10

Page 74: Introduction to SQL. Contents 1.Relational Databases and Data Models 2.SQL 3.The HR Database Schema in Oracle 4.Introducing SELECT Statement The WHERE.

Modifying Objects

• ALTER command• ALTER TABLE <name> <command>

• ALTER

-- Add a foreign key constraint TOWN --> COUNTIRY-- Add a foreign key constraint TOWN --> COUNTIRYALTER TABLE TOWNALTER TABLE TOWN ADD CONSTRAINT TOWN_COUNTRY_FKADD CONSTRAINT TOWN_COUNTRY_FK FOREIGN KEY (COUNTRY_ID)FOREIGN KEY (COUNTRY_ID) REFERENCES COUNTRY(ID) ENABLEREFERENCES COUNTRY(ID) ENABLE

-- Add column COMMENT to the table PERSON-- Add column COMMENT to the table PERSONALTER TABLE PERSONS ADD ("COMMENT" VARCHAR2(800))ALTER TABLE PERSONS ADD ("COMMENT" VARCHAR2(800))

-- Remove column COMMENT from the table PERSON-- Remove column COMMENT from the table PERSONALTER TABLE PERSONS DROP COLUMN "COMMENT"ALTER TABLE PERSONS DROP COLUMN "COMMENT"

Page 75: Introduction to SQL. Contents 1.Relational Databases and Data Models 2.SQL 3.The HR Database Schema in Oracle 4.Introducing SELECT Statement The WHERE.

Deleting Objects

• DROP command• DROP TABLE <name>

• DROP SEQUENCE <name>

• DROP TRIGGER <name>

• DROP INDEX <name>

DROP SEQUENCE SEQ_PERSONDROP SEQUENCE SEQ_PERSON

DROP CONSTRAINT TRG_PERSON_INSERTDROP CONSTRAINT TRG_PERSON_INSERT

DROP TABLE PERSONSDROP TABLE PERSONS

Page 76: Introduction to SQL. Contents 1.Relational Databases and Data Models 2.SQL 3.The HR Database Schema in Oracle 4.Introducing SELECT Statement The WHERE.

Creating TablesBest Practices

Page 77: Introduction to SQL. Contents 1.Relational Databases and Data Models 2.SQL 3.The HR Database Schema in Oracle 4.Introducing SELECT Statement The WHERE.

Creating Tables in Oracle

• Creating new table:

• Define the table name

• Define the columns and their types

• Define the table primary key

• Define a sequence for populating the primary key

• Define a trigger for automatically populate the primary key on insertion

• Define foreign/keys and constraints

Page 78: Introduction to SQL. Contents 1.Relational Databases and Data Models 2.SQL 3.The HR Database Schema in Oracle 4.Introducing SELECT Statement The WHERE.

Creating Tables in Oracle – Example

CREATE TABLE PERSONS( PERSON_ID NUMBER NOT NULL, NAME VARCHAR2(100) NOT NULL, CONSTRAINT PERSONS_PK PRIMARY KEY(PERSON_ID));

CREATE SEQUENCE SEQ_PERSONS;

CREATE TRIGGER TRG_PERSONS_INSERTBEFORE INSERT ON PERSONS FOR EACH ROW BEGIN SELECT SEQ_PERSONS.nextval INTO :new.PERSON_ID FROM dual; END;

Page 79: Introduction to SQL. Contents 1.Relational Databases and Data Models 2.SQL 3.The HR Database Schema in Oracle 4.Introducing SELECT Statement The WHERE.

SQL LanguageInserting Data in the Tables

Page 80: Introduction to SQL. Contents 1.Relational Databases and Data Models 2.SQL 3.The HR Database Schema in Oracle 4.Introducing SELECT Statement The WHERE.

Inserting Data

• INSERT command• INSERT INTO <table> VALUES (<values>)

• INSERT INTO <table>(<columns>) VALUES (<values>)

• INSERT INTO <table> SELECT <values>

INSERT INTO COUNTRYINSERT INTO COUNTRYVALUES ('1', 'Bulgaria', 'Sofia')VALUES ('1', 'Bulgaria', 'Sofia')

INSERT INTO COUNTRY(NAME, CAPITAL)INSERT INTO COUNTRY(NAME, CAPITAL)VALUES ('Bulgaria', 'Sofia')VALUES ('Bulgaria', 'Sofia')

INSERT INTO COUNTRY(COUNTRY_ID, NAME, CAPITAL)INSERT INTO COUNTRY(COUNTRY_ID, NAME, CAPITAL)SELECT NULL, COUNTRY, CAPITAL FROM CAPITALSSELECT NULL, COUNTRY, CAPITAL FROM CAPITALS

Page 81: Introduction to SQL. Contents 1.Relational Databases and Data Models 2.SQL 3.The HR Database Schema in Oracle 4.Introducing SELECT Statement The WHERE.

SQL LanguageUpdating Data in the Tables

Page 82: Introduction to SQL. Contents 1.Relational Databases and Data Models 2.SQL 3.The HR Database Schema in Oracle 4.Introducing SELECT Statement The WHERE.

Updating Data

• UPDATE command• UPDATE <table> SET <column=expression> WHERE <condition>

• Note: Don't forget the WHERE clause!

UPDATE PERSONSUPDATE PERSONSSET NAME = 'Updated Name'SET NAME = 'Updated Name'WHERE PERSON_ID = 1WHERE PERSON_ID = 1

UPDATE EMPLOYEESUPDATE EMPLOYEESSET SALARY = SALARY * 1.10SET SALARY = SALARY * 1.10WHERE DEPARTMENT_ID = 3WHERE DEPARTMENT_ID = 3

Page 83: Introduction to SQL. Contents 1.Relational Databases and Data Models 2.SQL 3.The HR Database Schema in Oracle 4.Introducing SELECT Statement The WHERE.

Updating Joined Tables

• Updating joined tables is done by nested SELECT

UPDATEUPDATE (SELECT SALARY (SELECT SALARY FROM EMPLOYEES E INNER JOIN DEPARTMENTS D FROM EMPLOYEES E INNER JOIN DEPARTMENTS D ON E.DEPARTMENT_ID = D.DEPARTMENT_IDON E.DEPARTMENT_ID = D.DEPARTMENT_ID WHERE D.NAME = 'Accounting')WHERE D.NAME = 'Accounting')SET SALARY = SALARY * 1.10SET SALARY = SALARY * 1.10

Page 84: Introduction to SQL. Contents 1.Relational Databases and Data Models 2.SQL 3.The HR Database Schema in Oracle 4.Introducing SELECT Statement The WHERE.

SQL LanguageDeleting Data from the Tables

Page 85: Introduction to SQL. Contents 1.Relational Databases and Data Models 2.SQL 3.The HR Database Schema in Oracle 4.Introducing SELECT Statement The WHERE.

Deleting Data

• Deleting rows from a table• DELETE FROM <table> WHERE <condition>

• Note: Don’t forget the WHERE clause!

• Delete all rows from a table at once• TRUNCATE TABLE <table>

DELETE FROM PERSONS WHERE PERSON_ID = 1DELETE FROM PERSONS WHERE PERSON_ID = 1

DELETE FROM PERSONS WHERE NAME LIKE 'S%'DELETE FROM PERSONS WHERE NAME LIKE 'S%'

TRUNCATE TABLE PERSONSTRUNCATE TABLE PERSONS

Page 86: Introduction to SQL. Contents 1.Relational Databases and Data Models 2.SQL 3.The HR Database Schema in Oracle 4.Introducing SELECT Statement The WHERE.

Problems

1. What is SQL? What is DML? What is DDL? Recite the most important SQL commands.

2. What is PL/SQL?

3. Start Oracle SQL Developer and connect to the database. Use the HR user. Examine the major tables in the HR schema.

4. Write a SQL query to find all information about all department.

5. Write a SQL query to find all department names.

6. Write a SQL query to find the salary of each employee by month, by day and hour. Consider that one month has 20 workdays and each workday has 8 work hours.

Page 87: Introduction to SQL. Contents 1.Relational Databases and Data Models 2.SQL 3.The HR Database Schema in Oracle 4.Introducing SELECT Statement The WHERE.

Problems (2)

7. Write a SQL query to find the email addresses of each employee. Consider that the mail domain is mail.somecompany.com. Emails should look like "[email protected]". The produced column should be names "Full Email Address".

8. Write a SQL query to find all different salaries that are paid to the employees.

9. Write a SQL query to find all information about the employees whose position is "AC_MGR" (Accounting Manager).

10. Write a SQL query to find the names of all employees whose first name starts with "Sa".

Page 88: Introduction to SQL. Contents 1.Relational Databases and Data Models 2.SQL 3.The HR Database Schema in Oracle 4.Introducing SELECT Statement The WHERE.

Problems (3)

11. Write a SQL query to find the names of all employees whose last name contains the character sequence "ei".

12. Write a SQL query to find the names of all employees whose salary is in the range [3000...5000].

13. Write a SQL query to find the names of all employees whose salary is 2500, 4000 or 5000.

14. Write a SQL query to find all locations that has no state or post code defined.

15. Write a SQL query to find all employees that are paid more than 10000. Order them in decreasing order by salary.

Page 89: Introduction to SQL. Contents 1.Relational Databases and Data Models 2.SQL 3.The HR Database Schema in Oracle 4.Introducing SELECT Statement The WHERE.

Problems (4)

16. Write a SQL query to find to top 5 best paid employees.

17. Write a SQL query to find all departments and the town of their location. Use natural join.

18. Write a SQL query to find all departments and the town of their location. Use join with USING clause.

19. Write a SQL query to find all departments and the town of their location. Use inner join with ON clause.

20. Write a SQL query to find all the locations and the departments for each location along with the locations that do not have department. User right outer join. Rewrite the query to use left outer join.

Page 90: Introduction to SQL. Contents 1.Relational Databases and Data Models 2.SQL 3.The HR Database Schema in Oracle 4.Introducing SELECT Statement The WHERE.

Problems (5)

21. Write a SQL query to find the manager of each department.

22. Write a SQL query to find the location of each department manager.

23. Write a SQL query to find the names of all employees from the departments "Sales" and "Finance" whose hire year is between 1995 and 2000.

24. Write a SQL query to find the names and salaries of the employees that take the minimal salary in the company. Use nested SELECT statement.

25. Write a SQL query to find the names and salaries of the employees that take a salary that is up to 10% higher than the minimal salary for the company.

Page 91: Introduction to SQL. Contents 1.Relational Databases and Data Models 2.SQL 3.The HR Database Schema in Oracle 4.Introducing SELECT Statement The WHERE.

Problems (6)

26. Write a SQL query to find the average salary in the "Sales" department.

27. Write a SQL query to find the number of employees in the "Sales" department.

28. Write a SQL query to find the number of all locations where the company has an office.

29. Write a SQL query to find the number of all departments that has manager.

30. Write a SQL query to find the number of all departments that has no manager.

31. Write a SQL query to find all departments and the average salary for each of them.

Page 92: Introduction to SQL. Contents 1.Relational Databases and Data Models 2.SQL 3.The HR Database Schema in Oracle 4.Introducing SELECT Statement The WHERE.

Problems (7)

32. Write a SQL query to find the count of all employees in each department and for each manager.

33. Write a SQL query to find all managers that have exactly 5 employees. Display their names and the name and location of their department.

34. Write a SQL query to find all departments along with their managers. For departments that do not have manager display "(no manager)".

35. Write a SQL query to find the names of all employees whose last name is exactly 5 characters long.

36. Write a SQL query to print the current date and time in the format "day.month.year hour:minutes:seconds".

Page 93: Introduction to SQL. Contents 1.Relational Databases and Data Models 2.SQL 3.The HR Database Schema in Oracle 4.Introducing SELECT Statement The WHERE.

Problems (8)

37. Write a SQL statement to create a table USERS. Users should have username, password, full name and last login time. Choose appropriate data types for the fields of the table. Define a primary key column with a primary key constraint. Define a sequence for populating the primary key. Define a trigger to update the primary key column value before inserting a record.

38. Write a SQL statement to create a view that displays the users from the USERS table that have been in the system today. Test if the view works correctly.

Page 94: Introduction to SQL. Contents 1.Relational Databases and Data Models 2.SQL 3.The HR Database Schema in Oracle 4.Introducing SELECT Statement The WHERE.

Problems (9)

39. Write a SQL statement to create a table GROUPS. Groups should have unique name (use unique constraint). Define primary key and a sequence and a trigger for populating it.

40. Write a SQL statement to add a column GROUP_ID to the table USERS. Fill some data in this new column and as well in the GROUPS table. Write a SQL statement to add a foreign key constraint between tables USERS and GROUPS.

41. Write SQL statements to insert several records in the USERS and GROUPS tables.

Page 95: Introduction to SQL. Contents 1.Relational Databases and Data Models 2.SQL 3.The HR Database Schema in Oracle 4.Introducing SELECT Statement The WHERE.

Problems (10)

42. Write SQL statements to insert in the USER table the names of all employees from the EMPLOYEES table. Combine the first and last names as a full name. For user name use the email column from EMPLOYEES. Use blank password.

43. Write a SQL statement that changes the password to NULL for all USERS that have not been in the system since 10.03.2006.

44. Write a SQL statement that deletes all users without passwords (NULL or empty password).

Page 96: Introduction to SQL. Contents 1.Relational Databases and Data Models 2.SQL 3.The HR Database Schema in Oracle 4.Introducing SELECT Statement The WHERE.

Homework

1. Write a SQL query to display the average employee salary by country.

2. Write a SQL query to display the average employee salary by region.

3. Write a SQL query to display the country of each employee along with his name and department city.

4. Write a SQL query to display the country where maximal number of employees work.

5. Write a SQL query to display the number of managers for each region and each country.

6. Define table WORKHOURS to store work reports for each employee (date, task, hours, comments). Don't forget to define automatically populated primary key (primary key constraint + sequence + trigger).

Page 97: Introduction to SQL. Contents 1.Relational Databases and Data Models 2.SQL 3.The HR Database Schema in Oracle 4.Introducing SELECT Statement The WHERE.

Homework (2)

7. Define foreign key between the tables WORKHOURS and EMPLOYEE. Add additional column in the employee table if needed.

8. Write several SQL statements to fill some data in the WORKHOURS table.

9. Write a SQL query to find all the average work hours per week for each country.

10. Write a SQL query to find all the departments where some employee worked overtime (over 8 hours/day) during the last week.

11. Write a SQL query to find all employees that have worked 3 or more days overtime in the last week. Display their name, location department and country.


Recommended