54
LECTURE9: DATA MANIPULATION IN SQL Ref. Chapter5 from “Database Systems: A Practical Approach to Design, Implementation and Management.” Thomas Connolly, Carolyn Begg. IS220 : Database Fundamentals

LECTURE9: DATA MANIPULATION IN SQL · Notice the WHERE clause in the SQL UPDATE statement! The WHERE clause specifies which record or records that should be updated. If you omit the

  • Upload
    dangdat

  • View
    222

  • Download
    0

Embed Size (px)

Citation preview

LECTURE9:DATA MANIPULATION IN SQL

Ref. Chapter5from

“Database Systems: A Practical Approach to Design, Implementation and Management.”Thomas Connolly, Carolyn Begg.

I S 220 : D at ab as e Fu n d am en t a l s

The Process of Database Design2

Conceptual Design (ERD)

Logical Design(Relational

Model)Physical Design

Create schema (DDL)

Load Data(DML)

Tables in the Examples

Customer(custNo, custName, custSt, custCity, age)Product(prodNo, prodName, prodDes, price)Orders(ordNo, ordDate, custNo, prodNo, quantity)

WherecustName, custSt, custCity, prodName, prodDes are stringsordDate is dateOthers are numbers

3

Sample Data in Customer Table4

custNo custName custSt custCity age

1 C1 Olaya St Jeddah 20

2 C2 Mains St Riyadh 30

3 C3 Mains Rd Riyadh 25

4 C4 Mains Rd Dammam

5 C5 Mains Rd Riyadh

Sample Data in Product Table5

prodNo prodName prodDes price100 P0 Food 100

101 P1 healthy Food 100

102 P2 200

103 P3 self_raising flour,80%wheat

300

104 P4 network 80x 300

Sample Data in Orders Table6

ordNo ordDate custNo prodNo quantity

1 01-jan-2003 1 100 2

2 02-jan-2003 1 101 1

3 01-jan-2003 2 102 1

4 01-jan-2003 3 100 2

5 03-jan-2003 1 101 1

6 06-mar-2003 2 100 10

7

Data Manipulation Language (DML)

Data Manipulation Language (DML)

¨ DML is used to retrieve and modify data in the tables

¨ Four basic statements¤ Insert Into¤ Select¤ Update¤ Delete From

Lecture8

8

Insert Statement

¨ The INSERT statement adds one or more new rows of data to a database table.

¨ Syntax

¨ Note:¤ value list must correspond to column list¤ If column list is omitted, then a value for every attribute is required and must

match exactly the default order in which they appear in the table (as shown in a DESCRIBE statement),

¤ The data types must be correct

9

INSERT INTO table_name (column1,column2,column3,...)VALUES (value1,value2,value3,...);

INSERT INTO table_nameVALUES (value1,value2,value3,...);

Insert Statement Example

¨ Example: for table Customer

Insert into Customer(custNo, custName) values (6, 'John'); Output: 1 row inserted

Insert into Customer values (7, 'David ', 'St1','City1', 20);Output: 1 row inserted

10

Inserting Rows With Null Values

¨ Suppose that EMAIL column is defined as a NOT NULL column.¨ An implicit attempt to add values to the table as shown would

generate an error.

¨

¨ An implicit insert will automatically insert a null value in columns that allow nulls.

11

Inserting Special Values

¨ Special values such as SYSDATE can be entered in the VALUES list of an INSERT statement.

¨ SYSDATE will put the current date and time in a column.

ExampleINSERT INTO employees

(employee_id, first_name, last_name, email, phone_number, hire_date, job_id, salary)

VALUES

(304,’Fahad',’Khaled’, 't_user', 4159982010, SYSDATE, 'ST_CLERK',2500);

12

Simple SELECT Queries

¨ The SELECT is one of the most important, if not the most important,keyword in SQL

¨ You use SELECT to retrieve information from the database.

¨ Syntax

13

SELECT expression_listFROM table_list

[WHERE condition][ORDER BY expression_list];

Simple SELECT Queries

Expression in SELECT statement :

Condition in WHERE statement:¨ an expression that can be evaluated to TRUE or

FALSE. ¨ Only rows satisfying the condition will be chosen.¨ Condition can be simple comparison or compound

expression

14

Expression Example

column names SELECT prodNo

arithmetic operators for numbers: +, -, *, / SELECT Price+10

Constant SELECT 'The first name is', fnameFROM customer

Listing All Data in a Table

¨ If WHERE clause is omitted, all rows will be listed.

Example: List all data in the customer tableSELECT custNo, custName, custSt, custCity, age

FROM customer;

OR (use * for all columns)

SELECT * FROM CUSTOMER;

15

custNo custName custSt custCity age

1 C1 Olaya St Jeddah 20

2 C2 Mains St Riyadh 30

3 C3 Mains Rd Riyadh 25

4 C4 Mains Rd Dammam

5 C5 Mains Rd Riyadh

Using Arithmetic Operators

¨ The example shown uses the addition operator to calculate a salary increase of 300 for all employees and displays a new SALARY + 300 column in the output.

SELECT last_name, salary, salary + 300FROM employees;

¨ Note that this example does not create new columns in the tables or change the actual data values.

¨ The results of the calculations will appear only in the output

16

Simple Queries : Use of DISTINCT

¨ Use Distinct in the select statement to remove duplicate values

¨ Syntax

17

SELECT DISTINCT column_name,column_nameFROM table_name;

Use of DISTINCT Example

Example: List all customer cities.

SELECT custCity FROM customer;

¨ A city will be repeated if there are more than one customer in that city. To eliminate the duplicates, use:

SELECT DISTINCT custCity FROM customer;

18

custCity

Jeddah

Riyadh

Dammam

custCity

Jeddah

Riyadh

Riyadh

Dammam

Riyadh

WHERE Clause¨ When retrieving data from the database, you may

need to limit the rows of data that are displayed.¨ You can accomplish this using the WHERE clause.¨ A WHERE clause contains a condition that must be

met, and it directly follows the FROM clause in a SQL statement.

• Syntax

19

SELECT expression_listFROM table_list

[WHERE condition][ORDER BY expression_list];

Conditions in the WHERE Clause

WHERE clause consists of five basic search conditions:

¨ Comparison: Compare the value of one expression to the value of another expression (= , <, >, <=, >=, <>).

¨ Range: Test whether the value of an expression falls within a specified range of values (BETWEEN/ NOT BETWEEN).

¨ Set membership: Test whether the value of an expression equals one of a set of values (IN/ NOT IN).

¨ Pattern match: Test whether a string matches a specified pattern (LIKE/ NOT LIKE).

¨ NULL: Test whether a column has null value (IS NULL/ IS NOT NULL).

Note: Basic comparisons can be compounded by AND, OR, NOT¤ Eg, prodNo=100 and ordDate='01-jan-2003'

20

Simple Queries : Comparison search condition

Comparison operators: = , < , > , <= , >= , <>

Example 1: List all products (by prodNo and price) which are priced more than 100.

Select prodNo, priceFrom Product

Where price >100;

Example 2: What is the name of the customer whose custNo is 1?

Select custNameFrom customer

Where custNo=1;

21

prodNo price102 200

103 300

104 300

custName

C1

Simple Queries : Compound comparison search condition

¨ Compound comparison operators: AND , OR , NOT , ( )

¨ Order of evaluation:¤ Expression is evaluated left to right¤ Between brackets¤ NOT¤ AND¤ OR

22

Examples

Example 1: Find all orders of product 100 before 02/01/03.SELECT *

FROM ordersWHERE prodNo = 100 AND ordDate <'02-jan-2003';

Example 2: Find all products priced less than 200 or greater than 300

SELECT * FROM product

WHERE price < 200 OR price >300;

23

ordNo ordDate custNo prodNo quantity

1 01-jan-2003 1 100 2

4 01-jan-2003 3 100 2

prodNo prodName prodDes price

100 P0 Food 100

101 P1 healthy food 100

More Examples

Example: Find the customer with name C1 and live in Riyadh or Jeddah

SELECT *

FROM customers

WHERE custName ='C1‘ AND (custCity='Jeddah' ORcustCity='Riyadh');

24

custNo custName custSt custCity age

1 C1 Olaya St Jeddah 20

Simple Queries : BETWEEN / NOT BETWEEN

¨ The BETWEEN operator is used to select values within a range.

¨ The NOT BETWEEN checks if a value is outside a range.

¨ Syntax:

25

SELECT column_name(s)FROM table_name

WHERE column_name BETWEEN |NOT BETWEEN value1 AND value2;

BETWEEN Example

Example: List products priced between 200 and 300.

SELECT * FROM product

WHERE price >=200 and price <=300;

or equivalently

SELECT * FROM product

WHERE price between 200 and 300;

26

prodNo prodName prodDes price

102 P2 200

103 P3 self_raisingflour,80%wheat

300

104 P4 network 80x 300

Simple Queries : IN / NOT IN

¨ IN tests whether a data value matches one of a list values.

¨ NOT IN checks for data values that do not lie in a specific list of values

¨ Syntax

27

SELECT column_name(s)FROM table_name

WHERE column_name IN| NOT IN (value1,value2,...);

IN Example

Example: List all customers living in Riyadh, or Dammam, or Jeddah.

SELECT *FROM Customer

WHERE custCity = 'Jeddah' OR custCity = 'Riyadh' ORcustCity = 'Dammam';

or equivalently

SELECT *FROM Customer

WHERE custCity IN (‘Jeddah', ‘Riyadh', ‘Dammam');

28

custNo custName custSt custCity age

1 C1 Olaya St Jeddah 20

2 C2 Mains St Riyadh 30

3 C3 Mains Rd Riyadh 25

4 C4 Mains Rd Dammam

5 C5 Mains Rd Riyadh

Simple Queries : LIKE / NOT LOKE

¨ LIKE is used to search for a specified pattern in a column.¨ NOT LIKE allows you to select records that does NOT match

the pattern.

¨ Syntax

¨ SQL has special pattern matching symbol¤ % represents any sequence of zero or more characters¤ _ represents any single character

29

SELECT column_name(s)FROM table_name

WHERE column_name LIKE | NOT LIKE ‘pattern’;

LIKE Example

Example: List all products whose description contain the string 'Food'.

SELECT * FROM productWHERE prodDes LIKE '%Food%';

30

prodNo prodName prodDes price

100 P0 Food 100

101 P1 healthy Food 100

More Examples of LIKE | NOT LIKE

LIKE 'H_' : any string beginning with H and exactly 2 characters long

NOT LIKE 'H%': any string not beginning with H

LIKE '%y': any string ending with 'y'

31

Simple Queries : IS NULL and IS NOT NULL

¨ It is not possible to test for NULL values with comparisonoperators, such as =, <, or <>.

¨ To test for null values in a query, use IS NULL or IS NOTNULL in the WHERE clause.

¨ Comparisons between a NULL and any other value, returnunknown and the result will not be included in the finalresults

¨ Syntax

32

SELECT column_name(s)FROM table_name

WHERE column_name IS NULL | IS NOT NULL ;

IS NULL and IS NOT NULL Examples

Example: List all products with a product description.

SELECT * FROM productWHERE prodDes IS NOT NULL;

Similarly, to list products without description, useSELECT * FROM productWHERE prodDes IS NULL;

33

prodNo prodName prodDes price

100 P0 Food 100

101 P1 healthy Food 100

103 P3 self_raisingflour,80%wheat

300

104 P4 network 80x 300

prodNo prodName prodDes price

102 P2 200

Simple Queries : Ordering of Rows

¨ Rows can be put in ascending or descending order of some columns. To do this, use ORDER BY

¨ Syntax

¨ Default order (ie, if desc is not used) is ascending

34

SELECT column_name,column_nameFROM table_name

WHERE ConditionORDER BY column_name,column_name ASC|DESC ;

Ordering of Rows Example

¨ Example: list all products in descending order of price

SELECT * FROM productORDER BY price desc;

¨ Can also order by several attributes, eg.ORDER BY price desc, prodName;

35

prodNo prodName prodDes price

103 P3 self_raisingflour,80%wheat

300

104 P4 network 80x 300

102 P2 200

100 P0 Food 100

101 P1 healthy Food 100

Ordering of Rows Example

SELECT * FROM IndividualORDER BY FirstName, LastName ;

36

Operators Summary 37

Operator Function

= equal to

< less than

> greater than

<= less than equal to

>= greater than equal to

<> not equal to

LIKE % used as wildcard. eg. LIKE ‘%PRE%’

IN test for in an enumerated list.

BETWEEN used to select values within a range

Update Statement

¨ The UPDATE statement is used to update records in a table

¨ Syntax

Notice the WHERE clause in the SQL UPDATE statement!The WHERE clause specifies which record or records that should be updated. If you omit the WHERE clause, all records will be updated!

38

UPDATE table_nameSET column1=value1, column2=value2,...

WHERE some_column=some_value ;

Update Statement Example

¨ Example : Customer C1 has changed his city to Riyadh.

UPDATE CustomerSET custCity=‘Riyadh‘ , custSt='12 Mains Rd'

WHERE CustName=C1';Output: 1 row updatedSelect * From Customer ;

39

custNo custName custSt custCity age

1 C1 12 Main Rd Riyadh 20

2 C2 Mains St Riyadh 30

3 C3 Mains Rd Riyadh 25

4 C4 Mains Rd Dammam

5 C5 Mains Rd Riyadh

Update Statement Example

Be careful when updating records. If we had omitted the WHERE clause, in the example before, like this:

UPDATE CustomerSET custCity=‘Riyadh‘ , custSt='12 Mains Rd' ;

Output: 5 rows updated

Select * From Customer ;

40

custNo custName custSt custCity age

1 C1 12 Main Rd Riyadh 20

2 C2 12 Main Rd Riyadh 30

3 C3 12 Main Rd Riyadh 25

4 C4 12 Main Rd Riyadh

5 C5 12 Main Rd Riyadh

Delete Statement

¨ The DELETE statement is used to delete records in a table.

¨ Syntax

Notice the WHERE clause in the SQL DELETE statement!The WHERE clause specifies which record or records that should be deleted. If you omit the WHERE clause, all records will be deleted!

DELETE does not delete the table itself, only rows in the table.

41

DELETE FROM table_nameWHERE some_column=some_value;

Delete Statement Example

¨ Example : Delete Customer C1

DELETE FROM CustomerWHERE CustName=‘C1';

Output: 1 row deletedSelect * From Customer ;

42

custNo custName custSt custCity age

2 C2 Mains St Riyadh 30

3 C3 Mains Rd Riyadh 25

4 C4 Mains Rd Dammam

5 C5 Mains Rd Riyadh

Delete Statement Example

¨ Example : Delete all Customers

DELETE FROM Customer;

Output: 5 row deletedSelect * From Customer ;

43

custNo custName custSt custCity age

Using A Subquery To Copy Rows

¨ To select all rows from the EMPLOYEES table and insert them into the SALES_REPS table, the statement would be written as shown:

INSERT INTO sales_repsSELECT *FROM employees;

¨ this will work only if both tables have the same number of columns with matching data types, and they are in the same order.

44

Update and Delete with a value from a Subquery

¨ Updating a column with a value from a subqueryUPDATE copy_employees

SET salary = (SELECT salary

FROM employees

WHERE employee_id= 205)

WHERE employee_id= 202;

¨ Deleting rows with a value from a subqueryDELETE FROM copy_employees

WHERE department_id=(SELECT department_id

FROM departments

WHERE department_name= 'Shipping');

5 row(s) deleted

45

Truncate Statement

¨ TRUNCATE deletes all data in a table and frees storage space for the table rows ( deletes data faster but you cannot rollback)

¨ Syntax

TRUNCATE get rid of the data but not the table itself (DROP)

46

Truncate table table_name;

Truncate Example

¨ Example : Delete all Products

TRUNCATE TABLE product;

47

prodNo prodName prodDes price

48

Truncate vs Delete

Delete Truncate

To remove rows from a table To remove all rows from a table

WHERE Clause can be used , if no where clause is specified all

rows will be removed

We cant use WHERE clause

DML command DDL command

You can rollback You can’t rollback

Extra Example49

Employee No. First Name Last Name Dept Number SalaryE1 Mandy Smith D1 50000E2 Daniel Hodges D2 45000E3 Shaskia Ramanthan D2 58000

Dept Number Dept Name Location Mail NumberD1 Computer Science Bundoora 39D2 Information Science Bendigo 30D3 Physics Bundoora 37D4 Chemistry Bendigo 35

50

1)Basic SQL SELECT QueriesSELECT firstName, lastNameFROM Employee WHERE employeeNo = ‘E1’;

51

2)Compound Comparison

SELECT deptNumberFROM EMPLOYEEWHERE lastName = ‘Smith’OR lastName = ‘Hodges’;

SQL Queries Example

52

SELECT DISTINCT deptNumber

FROM EMPLOYEE;

3)Duplicate Removal

4)Set Membership Search ( IN)

SELECT deptNumber, mailNumberFROM DEPARTMENTWHERE deptName IN ( ‘Computer Science’, ‘Physics’);

SQL Queries Example

5)Pattern Match Search ( LIKE)

SELECT employeeNo, deptNumberFROM EMPLOYEEWHERE firstName LIKE ‘%an%’;

53

SELECT employeeNo , lastNameFROM EMPLOYEEORDER BY lastName;

6)Sorting Output from Queries

SQL Queries Example

54