Chapter 3
Structured Query Language:
Creating and manipulating data
• In chapter 1, we looked at how databases are
used in various business applications
• In chapter 2, we see how databases are
helpful in decision making
• In this chapter, we learn how to create, load
data and extract information from a database
• This is accomplish using Structured Query
Language (SQL)
The HR Entity Relationship Diagram
DEPARTMENTS LOCATIONS
HR department_id location_id
department_name street_address
manager_id postal_code
location_id city
state_province
country_id
JOB_HISTORY
employee_id
start_date
end_date EMPLOYEES
job_id employee_id
department_id first_name
last_name COUNTRIES
email country_id
phone_number country_name
hire_date region_id
job_id
salary
commission_pct
manager_id
JOBS department_id
job_id
job_title
min_salary
max_salary REGIONS
region_id
region_name
Note:
Please create the HR database to facilitate your learning for Tutorials 3-5.
Execute the Create_HR.txt and In_HR.txt script.
SELECT Statement
• Used for queries on single or multiple tables
• Clauses of the SELECT statement:
– SELECT
• List the columns (and expressions) that should be returned from the query
– FROM
• Indicate the table(s) or view(s) from which data will be obtained
– WHERE
• Indicate the conditions under which a row will be included in the result
– GROUP BY
• Indicate categorization of results
– HAVING
• Indicate the conditions under which a category (group) will be included
– ORDER BY
• Sorts the result according to specified criteria
53
Summary
• In this lesson, you should have learned how to:
– Write and execute SELECT statement that:
• Uses arithmetic and concatenation operators
• Uses literal character strings
• Eliminate duplicate rows
• Use the WHERE clause to restrict rows of output:
– Use the comparison conditions
– Use the BETWEEN, IN, LIKE, and NULL operators
– Apply the logical AND, OR, and NOT operators
• Use the ORDER BY clause to sort rows of output
SELECT *|{[DISTINCT] column|expression [alias],...}
FROM table
[WHERE condition(s)]
[ORDER BY {column, expr, alias} [ASC|DESC]] ;
Displaying Data
from Multiple Tables
SQL provides join conditions that enable
information to be queried from separate
tables and combined in one report.
Summary
• In this lesson, you should have learned how
to:
– Write SELECT statement to access data from
more than one table using equijoins and non-
equijoins
– Use a self-join to join a table to itself
– Generate a Cartesian product )cross join) of all
rows from two or more tables
Reporting Aggregated Data
Using the Group Functions
Types of Group Functions
• In SQL, the following group functions can operate on a
whole table or on a specific grouping of rows.
• Each function returns ONE result
– AVG
– COUNT
– MAX
Group
– MIN functions
– SUM
– Group functions:
• Types and syntax
• Use AVG, SUM, MIN, MAX, COUNT
• Use DISTINCT keyword within group functions
• NULL values in a group function
–Grouping rows:
• GROUP BY clause
• HAVING clause
–Nesting group functions
Manipulating Data
– Adding new rows in a table
• INSERT statement
– Changing data in a table
• UPDATE statement
– Removing rows from a table:
• DELETE statement
Data Manipulation Language
– A DML statement is executed when you:
• Add new rows to a table
• Modify existing rows in a table
• Remove existing rows from a table
– A transaction consists of a collection of DML
statements that form a logical unit of work.
Adding a New Row to a Table
New
DEPARTMENTS row
Insert new row
into the
DEPARTMENTS table.
INSERT Statement Syntax
– Add new rows to a table by using the INSERT statement:
INSERT INTO table [(column [, column...])]
VALUES (value [, value...]);
– With this syntax, only one row is inserted at a time.
Inserting New Rows
– Insert a new row containing values for each column.
– List values in the default order of the columns in the
table.
– Optionally,
INSERT list the columns in the INSERT clause.
INTO departments(department_id,
department_name, manager_id, location_id)
VALUES (70, 'Public Relations’ , 100, 1700);
– Enclose character and date values within single quotation
marks.
Inserting Rows with Null Values
– Implicit method: Omit the column from the
column list.
INSERT INTO departments (department_id,
department_name)
VALUES (30, 'Purchasing');
– Explicit method: Specify the NULL keyword in the
VALUES clause.
INSERT INTO departments
VALUES (100, 'Finance', NULL, NULL);
Inserting Special Values
• The SYSDATE function records the current date and time.
INSERT INTO employees (employee_id,
first_name, last_name,
email, phone_number,
hire_date, job_id, salary,
commission_pct, manager_id,
department_id)
VALUES (113,
'Louis', 'Popp',
'LPOPP', '515.124.4567',
SYSDATE, 'AC_ACCOUNT', 6900,
NULL, 205, 110);
Inserting Specific Date and Time Values
– AddINTO
INSERT a new employee.
employees
VALUES (114,
'Den', 'Raphealy',
'DRAPHEAL', '515.127.4561',
TO_DATE('FEB 3, 1999', 'MON DD,
YYYY'),
'SA_REP', 11000, 0.2, 100, 60);
Copying Rows
from Another Table
– Write your INSERT statement with a subquery:
INSERT INTO sales_reps(id, name, salary, commission_pct)
SELECT employee_id, last_name, salary, commission_pct
FROM employees
WHERE job_id LIKE '%REP%';
– Do not use the VALUES clause.
– Match the number of columns in the INSERT
clause to those in the subquery.
– Inserts all the rows returned by the subquery in the
table, sales_reps.
Changing Data in a Table
EMPLOYEES
Update rows in the EMPLOYEES table:
UPDATE Statement Syntax
– Modify existing values in a table with the UPDATE
statement:
UPDATE table
SET column = value [, column = value,
...]
[WHERE condition];
– Update more than one row at a time (if required).
Updating Rows in a Table
– Values for a specific row or rows are modified if
you specify the WHERE clause:
UPDATE employees
SET department_id = 50
WHERE employee_id = 113;
– Values for all the rows in the table are modified if
you omit the WHERE clause:
UPDATE copy_emp
SET department_id = 110;
– Specify SET column_name= NULL to update a
column value to NULL.
Updating Two Columns with a
Subquery
• Update employee 113’s job and salary to match those of
employee 205.
UPDATE employees
SET job_id = (SELECT job_id
FROM employees
WHERE employee_id = 205),
salary = (SELECT salary
FROM employees
WHERE employee_id = 205)
WHERE employee_id = 113;
Updating Rows Based
on Another Table
• Use the subqueries in the UPDATE statements to update
row values in a table based on values from another table:
UPDATE copy_emp
SET department_id = (SELECT department_id
FROM employees
WHERE employee_id =
100)
WHERE job_id = (SELECT job_id
FROM employees
WHERE employee_id =
200);
Removing a Row from a Table
DEPARTMENTS
Delete a row from the DEPARTMENTS table:
DELETE Statement
• You can remove existing rows from a table by using the
DELETE statement:
DELETE [FROM] table
[WHERE condition];
Deleting Rows from a Table
– Specific rows are deleted if you specify the
WHERE
DELETE FROMclause:
departments
WHERE department_name = ‘Finance';
– All rows in the table are deleted if you omit the
WHERE clause:
DELETE FROM copy_emp;
Deleting Rows Based
on Another Table
• Use the subqueries in the DELETE statements to remove
rows from a table based on values from another table:
DELETE FROM employees
WHERE department_id =
(SELECT department_id
FROM departments
WHERE department_name
LIKE '%Public%');
Remove employees from departments that has the word ‘Public’ in their name
Summary
• In this lesson, you should have learned how to use the
following statements:
Function Description
INSERT Adds a new row to the table
UPDATE Modifies existing rows in the table
DELETE Removes existing rows from the table