Lab # 3 Data Manipulation Language (DML) Eng. Alaa O Shama

21
The Islamic University of Gaza Faculty of Engineering Department of Computer Engineering ECOM 4113: Database Lab Lab # 3 Data Manipulation Language (DML) Eng. Alaa O Shama October, 2015

Transcript of Lab # 3 Data Manipulation Language (DML) Eng. Alaa O Shama

Page 1: Lab # 3 Data Manipulation Language (DML) Eng. Alaa O Shama

The Islamic University of Gaza

Faculty of Engineering

Department of Computer Engineering

ECOM 4113: Database Lab

Lab # 3

Data Manipulation Language (DML)

Eng. Alaa O Shama

October, 2015

Page 2: Lab # 3 Data Manipulation Language (DML) Eng. Alaa O Shama

Objective

To be familiar with SQL Language especially with Data Manipulation Language

(DML).

In this lab, we will use the well-known HR sample schema (which included in

Oracle XE).

INSERT INTO

INSERT INTO statement used to insert new rows in a table in database.

INSERT INTO Basic Syntax

INSERT INTO table-name (Col.s List) VALUES (value-list);

You can also insert new rows without specifying column names, by typing:

“INSERT INTO table-name VALUES (value-list)”.

In this case, you MUST order values in the same order of its corresponding

columns.

Note: use “DESC[ribe] table-name” statement to see the columns order in table

definition.

Page 3: Lab # 3 Data Manipulation Language (DML) Eng. Alaa O Shama

DELETE

DELETE statement is the opposite of INSERT statement. It is used to delete rows

from a table according to a specified condition.

The syntax of SQL DELETE statement is:

Delete From Syntax

Delete from table-name

where condition;

It also can be used to delete all rows from a table by not specifying any

conditions.

If you want to empty a table, you just have to issue this command:

“DELETE FROM table-name”.

You should be aware when using this form.

Page 4: Lab # 3 Data Manipulation Language (DML) Eng. Alaa O Shama

UPDATE

UPDATE statement is used to modify existing rows values in a table.

The syntax of SQL UPDATE statement is:

Update Statement Syntax

UPDATE table-name SET column_name_1 = new_value1 , column_name_2 = new_value2 -- etc WHERE condition;

SELECT

The most commonly used SQL command is SELECT statement.

SQL SELECT statement is used to query or retrieve data from a table in the

database. A query may retrieve information from specified columns or from all of

the columns in the table.

To create a simple SQL SELECT Statement, you must specify the column(s) name

and the table name. The whole query is called SQL SELECT Statement.

SELECT Syntax

SELECT Attribute List

FROM Table List

[ WHERE condition ] [ GROUP BY grouping attributes

[ HAVING <group selection condition> ] ]

[ ORDER BY Columns || aliases || columns numbers ]

Page 5: Lab # 3 Data Manipulation Language (DML) Eng. Alaa O Shama

Attribute List:

It is a list of the attributes we want to retrieve. It can be:

* It is a fast alternative to all columns names.

Q1: Retrieve all the employees.

Specific Column(s).

Q2: Retrieve the first name, last name, phone and salary for each Employee.

Page 6: Lab # 3 Data Manipulation Language (DML) Eng. Alaa O Shama

Arithmetic Expressions

Create expressions with number and date data by using arithmetic operators.

Q3: Retrieve the Salary+300 for each employee.

Null Values

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

It is NOT the same as a zero or a blank space.

The result of any arithmetic expressions containing a null value is a

Null value.

Use NVL function, which converts a Null value into an actual specified value.

Q4: Retrieve the total salary for each employee.

Page 7: Lab # 3 Data Manipulation Language (DML) Eng. Alaa O Shama

Concatenation Operator

Links columns or character strings to other columns.

Is represented by two vertical bars (||).

Creates a resultant column that is a character expression.

Q5: Retrieve the full name of each employee.

DISTINCT COLUMN

In a table, some of the columns may contain duplicate values. If you want to list only the different (distinct) values in a table.

The DISTINCT keyword can be used to return only distinct (different) values.

Page 8: Lab # 3 Data Manipulation Language (DML) Eng. Alaa O Shama

Q6: Retrieve the location id of all departments.

A Column Alias

Renames a column heading.

Useful with calculations and concatenation.

Immediately follows the column name (There can also be the optional

AS keyword between the column name and alias).

Requires double quotation marks if it contains spaces or special

characters or if it is case sensitive.

Page 9: Lab # 3 Data Manipulation Language (DML) Eng. Alaa O Shama

function ( [DISTINCT] column || * )

Aggregate (Group) Functions in SQL

Aggregate functions operate on sets of rows to give one result per group. These sets may comprise the entire table or the table split into groups.

Group Functions:

COUNT.

SUM.

MAX.

MIN.

AVG.

STDDEV.

VARIANCE.

Notes:

All group function ignore NULL values. To substitute a value for null value,

use the NVL function.

The data types for the functions argument may be CHAR, VARCHAR2,

NUMBER, or DATE.

The AVG, SUM, VARIANCE, and STDDEV functions can be used only with

numeric data types.

Page 10: Lab # 3 Data Manipulation Language (DML) Eng. Alaa O Shama

Ig Ignore

NULL

v

a

l

u

e

s

DISTINCT makes the function consider only non-duplicate values; ALL makes

it consider every value, including duplicates. The default is ALL and therefore

does not need to be specified.

COUNT(*) returns the number of rows in a table that satisfy the criteria of

the SELECT statement, including duplicate rows and rows containing null

values in any of the columns.

Q7: Retrieve the sum of the salaries of all employees, the maximum salary,

the minimum salary, and the average salary.

Q8: Retrieve the total number of employees in the company.

Q9: Retrieve the number of employees who can earn a commission.

Ignore NULL

values but count

duplicate values.

Page 11: Lab # 3 Data Manipulation Language (DML) Eng. Alaa O Shama

Q10: Count the number of distinct salary values in the database.

Q11: Retrieve the average of the Commissions of the employees.

avg ignores NULL values, so the

result is the average of the

commissions of the employees

who earn commission not of All

employees.

Replace NULL values

with 0,so the result is the

average of commissions

of all employees.

Restricting Data

In most cases, we query the database to get some specific data from a table

not the whole table; therefore, we need a technique to restrict the data

retrieved by SELECT statement.

Restricting the rows that are returned by a query can be done by using the

optional [WHERE clause].

Page 12: Lab # 3 Data Manipulation Language (DML) Eng. Alaa O Shama

Notes:

Comparison operators:

When you deal with character strings or date values, you must enclosed

them by single quotation marks (' ').

Character values are case-sensitive, and date values are format-sensitive.

The default date format is DD/MM/YY.

Q12: Retrieve all employees who are working in department 30.

Operator Meaning

= Equal to

> Greater than

>= Greater than or equal to

< Less than

<= Less than or equal to

<> Not equal to

BETWEEN ... AND ... Between two values (inclusive)

LIKE Match a character pattern: %: any number of any characters. _: one character.

IS NULL Is a null value

IN(set) Match any of a list of values

ANY(set) Compare to any value in a set

ALL(set) Compare to all values in a set

Page 13: Lab # 3 Data Manipulation Language (DML) Eng. Alaa O Shama

Q13: Retrieve all employees whose first name is “David”.

Q14: Retrieve all employees who are hired on 7/6/2002.

Q15: Retrieve all employees whose first name starts with “A”.

Page 14: Lab # 3 Data Manipulation Language (DML) Eng. Alaa O Shama

Q16: Retrieve all employees whose first name starts with “A” and the third letter is “e”.

Q17: Retrieve the names of all employees whose salary between 5000 and 6000.

Page 15: Lab # 3 Data Manipulation Language (DML) Eng. Alaa O Shama

Q18: Retrieve all employees who are working in departments: 60, 90, or 100.

Q19: Retrieve all employees who are working in departments 100 AND their salary is

greater than ALL employees in department 60.

To solve this query, Firstly, we want to know the salaries of department 60.

Then, find the employees in department 100 with their salary > all the values

were retrieved from previous query.

Page 16: Lab # 3 Data Manipulation Language (DML) Eng. Alaa O Shama

The previous solution is not wrong. However, it is not a practical solution since

you apply it with many steps and each step needs a human to do them (cannot

applied by machine since the retrieve values are dynamic and can be changed

in any time). A better solution is to embed the first query in the second query

in “All’s condition parentheses”, which is called: inner query:

Q20: Retrieve the first name, last name of all employees that don’t have

manager.

Grouping

You can use the GROUP BY clause to divide the rows in a table into groups. You can

then use the group functions to return summary information for each group.

Notes:

Using a WHERE clause, you can exclude rows before dividing them into groups.

You cannot use a column alias in the GROUP BY clause.

Page 17: Lab # 3 Data Manipulation Language (DML) Eng. Alaa O Shama

When using the GROUP BY clause, make sure that all columns in the

SELECT list that are not group functions are included in the GROUP BY clause.

Q21: For each department, retrieve the department number, the number of employees in the department, and their average salary.

Q22: For each job, retrieve its department id and the sum of the salary of the employees.

Restricting Group Results

You cannot use group functions in the WHERE clause. HAVING clause is used

to specify the groups that are to be displayed, thus further restricting the

groups on the basis of aggregate information.

HAVING provides a condition on the groups which necessarily involve an aggregate function.

Page 18: Lab # 3 Data Manipulation Language (DML) Eng. Alaa O Shama

Illegal Query

SELECT DEPARTMENT_ID, AVG(SALARY)

FROM EMPLOYEES

WHERE AVG(SALARY) > 8000

GROUP BY DEPARTMENT_ID;

Instead, use condition in HAVING clause.

Legal Query

SELECT DEPARTMENT_ID, AVG(SALARY)

FROM EMPLOYEES

GROUP BY DEPARTMENT_ID

Having AVG(SALARY) > 8000;

Query Results Sorting

ORDER BY clause allows you to order the tuples in the result of a query.

Notes:

In ORDER BY clause you can use column name, column alias, column number, aggregate function or mathematical expression.

The default order is in ascending order of values.

To reverse the ordering, use “DESC” keyword.

Page 19: Lab # 3 Data Manipulation Language (DML) Eng. Alaa O Shama

Q23: Retrieve all employees sorted by their first name.

Q24: Retrieve all employees’ records sorted by their hire date, such that the

newest employee should come first and the old one come last.

Q25: Retrieve all employees sorted by their total salary.

Total salary = salary + salary * commission_pct.

Page 20: Lab # 3 Data Manipulation Language (DML) Eng. Alaa O Shama

Q26: Retrieve all employees sorted by their total salary in descending order, if

there are two employees have the same total salary, then sort them by first

name in ascending order, then by their last name.

Page 21: Lab # 3 Data Manipulation Language (DML) Eng. Alaa O Shama

Exercises:

1. Write SQL statement to insert a new record into JOBS table with the following

information:

JOB_ID = C_ENG

JOB_TITLE = Computer Engineer

MIN_SALARY = 20000 MAX_SALARY = 50000

2. Retrieve all employees who aren’t working in any department.

3. Change salary of employee 115 to 8000 if the existing salary is less than 6000.

4. Write SQL statement to retrieve the last name and salary for all employees

whose salary is not in the range 5000 through 12000.

5. Retreive the first name and join date of the employees who joined between

2002 and 2005.Sort data in ascending oreder of first names .

6. Retreive average salary of employees in each department who have

commission percentage.

7. Display departments in which more than five employees have commission

percentage.

8. Show the resulting salaries if every employee working on department 100 is

given a 15 percent raise.

9. Write SQL statement to retrieve the first names of all employees who have both

an “a” and an “e” in their first name.

10. Write SQL statement to delete all employees who are not working in any

departments, and all employees who are working in department 80, but their

TOTAL salary is less than 7000.

Note: total salary = salary + salary * commission_pct