Database Systems

97
1 Creating and Maintaining Database Objects Database Systems

description

Database Systems. Creating and Maintaining Database Objects. SQL Scripts. Script: text file that contains a sequence of SQL commands Running a script: SQL> START path_to_script_file; Path cannot contain any blank spaces. Inserting a Value Into Every Field in a Record. Syntax: - PowerPoint PPT Presentation

Transcript of Database Systems

Page 1: Database Systems

1

Creating and MaintainingDatabase Objects

Database Systems

Page 2: Database Systems

2

Script: text file that contains a sequence of SQL commands

Running a script:SQL> START path_to_script_file;

Path cannot contain any blank spaces

SQL Scripts

Page 3: Database Systems

3

Syntax:INSERT INTO tablename VALUES

(column1_value, column2_value, …);

You must insert a value or a NULL placeholder for every field

Fields must be entered in the order they appear in the table when you issue the DESC command

Inserting a Value Into EveryField in a Record

Page 4: Database Systems

4

Inserting a Value Into EveryField in a Record

• Example:

Page 5: Database Systems

5

Command to insert values for selected record fields:

INSERT INTO tablename

(column1_name, column2_name, …)

VALUES

(column1_value, column2_value, …);

Inserting Selected Table Fields

Page 6: Database Systems

6

Example:

Inserting Selected Table Fields

Page 7: Database Systems

7

Date values must be converted from characters to dates using the TO_DATE function and a format mask

Example:

Inserting Date Values

Page 8: Database Systems

8

Must be enclosed in single quotes Is case-sensitive To insert a string with a single

quote, type the single quote twice Example:'Mike''s Motorcycle Shop'

Inserting Text Data

Page 9: Database Systems

9

Transaction Logical unit of work consisting of one or

more SQL DML commands INSERT, UPDATE, DELETE

All transaction commands must succeed or none can succeed

Transaction results are not visible to other users until they are “committed” to the database

Until a transaction is committed, it can easily be “rolled back” (undone)

Transactions

Page 10: Database Systems

10

A transaction starts when you type one or more commands in SQL*Plus

A transaction ends when you issue either the COMMIT or ROLLBACK command

SQL>COMMIT;

SQL>ROLLBACK;

Transactions

Page 11: Database Systems

11

Committing and Rolling Back Data

• COMMIT• Makes transaction command changes

permanent in the database and visible to other users

• ROLLBACK• Rolls back transaction command

changes and restores database to its state before the transaction

Page 12: Database Systems

12

Used to mark individual sections of a transaction

You can roll back a transaction to a savepoint

Savepoints

Page 13: Database Systems

13

Syntax:UPDATE tablename

SET column1 = new_value,

column2 = new_value, …

WHERE search_condition;

Records can be updated in only one table at a time

Can update multiple records if they all match the search condition

Updating Records

Page 14: Database Systems

14

Format:WHERE fieldname operator expression

Operators Equal (=) Greater than, Less than (>, <) Greater than or Equal to (>=) Less than or Equal to (<=) Not equal (< >, !=, ^= LIKE BETWEEN IN NOT IN

Search Conditions

Page 15: Database Systems

15

WHERE s_name = ‘Sarah’

WHERE s_age > 18

WHERE s_class <> ‘SR’

Text in single quotes is case sensitive

Search Condition Examples

Page 16: Database Systems

16

Syntax:DELETE FROM tablenameWHERE search_condition;

Deletes multiple records if search condition specifies multiple records

If search condition is omitted, all table records are deleted

You can’t delete a record if it contains a primary key value that is referenced as a foreign key

Deleting Records

Page 17: Database Systems

17

Truncating Tables

• Removes all table data without saving any rollback information• Advantage: fast way to delete table

data• Disadvantage: can’t be undone

• Syntax:TRUNCATE TABLE tablename;

Page 18: Database Systems

18

Sequential list of numbers that is automatically generated by the database

Used to generate values for surrogate keys

Sequences

Page 19: Database Systems

19

Syntax:CREATE SEQUENCE sequence_name

[optional parameters];

Example:CREATE SEQUENCE f_id_sequence

START WITH 200;

Creating Sequences

Page 20: Database Systems

20

Viewing Sequence Information

• Query the SEQUENCE Data Dictionary View:

Page 21: Database Systems

21

Pseudocolumns

• Acts like a column in a database query

• Actually a command that returns a specific values

• Used to retrieve:• Current system date • Name of the current database user• Next value in a sequence

Page 22: Database Systems

22

Pseudocolumn Examples

PseudocolumnName

Output

CURRVAL Most recently retrieved sequence value

NEXTVAL Next value in a sequence

SYSDATE Current system date from database server

USER Username of current user

Page 23: Database Systems

23

Retrieving the current system date:SELECT SYSDATEFROM DUAL;

• Retrieving the name of the current user:

SELECT USERFROM DUAL;

DUAL is a system table that is used with pseudocolumns

Using Pseudocolumns

Page 24: Database Systems

24

Accessing the next value in a sequence:

sequence_name.NEXTVAL

Inserting a new record using a sequence:

INSERT INTO my_faculty VALUES

(f_id_sequence.nextval, ‘Professor Jones’);

Using PseudocolumnsWith Sequences

Page 25: Database Systems

25

• Permissions that you can grant to other users to allow them to access or modify your database objects

• Granting object privileges:GRANT privilege1, privilege2, …ON object_nameTO user1, user 2, …;

• Revoking object privileges:REVOKE privilege1, privilege2, …ON object_nameFROM user1, user 2, …;

Object Privileges

Page 26: Database Systems

26

Examples of Object Privileges

Object Type Privilege Description

Table, Sequence

ALTER Allows user to change object’s structure using the ALTER command

Table, Sequence

DROP Allows user to drop object

Table, Sequence

SELECT Allows user to view object

Table INSERT, UPDATE, DELETE

Allows user to insert, update, delete table data

Any database object

ALL Allows user to perform any operation on object

Page 27: Database Systems

27

Granting and Revoking Object Privileges

Page 28: Database Systems

28

Syntax:

SELECT column1, column2, …

FROM tablename

WHERE search_condition;

Retrieving Data From a Single Table

Page 29: Database Systems

29

To retrieve every column in a table:SELECT * FROM …

To retrieve every record in a table, omit the search conditionSELECT column1, column2, …

FROM tablename;

Retrieving Data From a Single Table

Page 30: Database Systems

30

Qualifying Table Names

• If you retrieve data from a table that is owned by another user, you must qualify the table name by prefacing it with the owner’s name

Page 31: Database Systems

31

Sometimes queries retrieve duplicate records

To suppress duplicate outputs, use the DISTINCT qualifier:SELECT DISTINCT column1, column2, …

FROM ...

Suppressing Duplicate Records

Page 32: Database Systems

32

Combining search conditions AND: both conditions must be true OR: either condition can be true

Combining AND and OR in a single operation AND comparisons are evaluated first Always use parentheses to force

conditions to be evaluated in the correct order

Using Multiple Search Conditions

Page 33: Database Systems

33

NULL: not defined Use IS NULL search condition

SELECT s_name, s_class

FROM my_students

WHERE s_class IS NULL;

Searching for NULL Records

Page 34: Database Systems

34

Use IS NOT NULL operator

SELECT s_name, s_age

FROM my_students

WHERE s_class IS NOT NULL;

Searching for NOT NULL Records

Page 35: Database Systems

35

Using the IN and NOT IN Operators

• IN retrieves all values where the search column value matches a set of values

SELECT *

FROM enrollment

WHERE grade IN (‘A’, ‘B’);

Page 36: Database Systems

36

Using the IN and NOT IN Operators

• NOT IN retrieves all values where the search column value matches a set of values

SELECT *

FROM enrollment

WHERE grade NOT IN (‘A’, ‘B’);

Page 37: Database Systems

37

Using the LIKE Operator

• Performs inexact searches by matching part of a character string

WHERE fieldname LIKE character_string;

Page 38: Database Systems

38

Using the LIKE Operator

• Character string must be in single quotes and use wildcard characters• % represents multiple wildcard characters• _ represents a single wildcard character• Wildcard characters can be placed at

beginning or end of string

• Examples:WHERE s_class LIKE ‘_R’;WHERE s_name LIKE ‘J%’;

Page 39: Database Systems

39

Use the ORDER BY clause Specify sort key, which is

column by which output is sorted

SELECT s_name, s_age

FROM my_students

ORDER BY s_age;

Sorting Query Output

Page 40: Database Systems

40

Default sort order Numerical: ascending Character: A - Z Date: oldest - newest To force the sort order: use ASC or

DESC Example

SELECT s_name, s_ageFROM my_studentsORDER BY s_age DESC;

Sorting Query Data

Page 41: Database Systems

41

Arithmetic operations on retrieved data Addition (+) Subtraction (-) Multiplication (*) Division (/)

Example:SELECT inv_id, qoh*price

FROM inventory;

Using Calculations in Queries

Page 42: Database Systems

42

ABS - absolute value CEIL – rounds a number up to the next integer FLOOR – rounds a number down to the

previous integer MOD – returns the remainder of a number and

a divisor POWER - raises a number to an exponent ROUND - rounds a number SQRT – returns the square root of a value TRUNC - truncates a number to the nearest

whole number

Single-RowNumber Functions

Page 43: Database Systems

43

Example:SELECT s_name,

TRUNC((SYSDATE - s_dob)/365)

FROM my_students;

Using Single-RowNumber Functions

Page 44: Database Systems

44

CONCAT – joins 2 character strings INITCAP – returns a string with the initial letter only

uppercase LENGTH – returns the length of a string LPAD, RPAD – returns a string with a specific number

of characters added on the left or right side LTRIM, RTRIM – returns a string with all instances of a

specific character trimmed from the left or right side REPLACE – replaces all instances of a character with

another character UPPER/LOWER – returns a string in all upper/lower

case letters

Single-RowCharacter Functions

Page 45: Database Systems

45

Example:SELECT UPPER(s_name)

FROM my_students;

Using Single-RowCharacter Functions

Page 46: Database Systems

46

To find a date that is a specific number of days before or after a known date, add or subtract the number from the known date

Example:SELECT order_date + 30 FROM cust_order;

Date Arithmetic

Page 47: Database Systems

47

To find the number of days between two known dates, subtract the later date from the earlier date

Example:SELECT SYSDATE – s_dobFROM my_students;

Date Arithmetic

Page 48: Database Systems

48

ADD_MONTHS returns a date that is a specific

number of months after a given date

Example:SELECT ADD_MONTHS(SYSDATE, 6)

FROM dual;

Date Functions

Page 49: Database Systems

49

LAST_DATE Returns the date that is the last

day of the month specified in the current date

Example:SELECT LAST_DATE(order_date) FROM cust_orderWHERE order_id = 1057;

Date Functions

Page 50: Database Systems

50

MONTHS_BETWEEN Returns the number of months

between two input dates

Example:SELECT MONTHS_BETWEEN(order_date, SYSDATE)

FROM cust_orderWHERE order_id = 1057;

Date Functions

Page 51: Database Systems

51

Used to perform an operation on a field from a group of retrieved records AVG (average of all retrieved values) COUNT (number of records retrieved) MAX (maximum value retrieved) MIN (minimum value retrieved) SUM (sum of all retrieved values)

Group Functions

Page 52: Database Systems

52

SELECT AVG (s_age) FROM my_students;

SELECT MAX (s_age) FROM my_students;

SELECT MIN (s_age) FROM my_students;

SELECT SUM (s_age) FROM my_students;

Group Function Examples

Page 53: Database Systems

53

GROUP BY must be used if some columns in the SELECT clause are used in a group function and some are not

Group all fields that are not included in the group function

Example:SELECT s_class, AVG(s_age)

FROM my_students

GROUP BY s_class;

Using the GROUP BY Clause

Page 54: Database Systems

54

Creating Alternate Column Headings in SQL*Plus

• Syntax:SELECT column1 “heading1”, column2 “heading2”, …

• Example:SELECT (SYSDATE – s_dob) “Student Age”

FROM my_students;

Page 55: Database Systems

55

Creating a Column Alias

• Column alias: alternate column name that can be referenced in the ORDER BY and GROUP BY clauses

• Syntax:SELECT column1 AS alias1 …

Example:SELECT (SYSDATE – s_dob) AS age_alias

ORDER BY age_alias

Page 56: Database Systems

56

Dynamic SQL Queries

• Queries that allow users to specify search conditions at runtime

• Approaches• Substitution Values• Runtime Variables

Page 57: Database Systems

57

Using Substitution Values

• Created when search expression is prefaced with an ampersand (&)

• System then prompts user for value

Page 58: Database Systems

58

Using Runtime Variables

• Runtime variable: variable defined in SQL*Plus environment• Syntax:

DEFINE variable_name = variable_value;

• You can then substitute the variable name for a query search condition value

Page 59: Database Systems

59

Using Runtime Variables

• Example:

Page 60: Database Systems

60

Formatting Data Using theTO_CHAR Function

• Used to display NUMBER and DATE values using a specific format mask

• Syntax:TO_CHAR(fieldname, ‘format_mask’);

Page 61: Database Systems

61

Join Queries

• Retrieve data from multiple tables by joining tables using foreign key references

• Join query types:• Inner (equality)• Outer• Self• Inequality

Page 62: Database Systems

62

Inner Joins

• One record is retrieved for each matching row

Page 63: Database Systems

63

Syntax:SELECT column1, column2, …

FROM table1, table2

WHERE table1.join_column =

table2.join_column

You must include a join condition for every link between 2 tables

Inner Joins

Join condition

Page 64: Database Systems

64

Example:SELECT s_name, f_nameFROM student, facultyWHERE student.f_id = faculty.f_id;

If you have N tables in the FROM clause, you must have (N - 1) join conditions

Inner Joins

Page 65: Database Systems

65

Qualifying Field Names

• If a field in the SELECT clause exists in multiple tables in the FROM clause, you must qualify the field name by prefacing it with either table’s name

Page 66: Database Systems

66

1. Identify all of the tables involved in the query, and label:

Display fields Join fields Search fields

2. Write the query List all display fields in the SELECT clause List all table names in the FROM clause List all join condition links in the WHERE

clause List all search fields in the WHERE clause

Process for DesigningComplex Inner Join Queries

Page 67: Database Systems

67

Outer Joins

• Limitation of inner joins: some records may be omitted if corresponding records don’t exist in one of the tables

• Example: retrieve records for all students, along with their corresponding ENROLLMENT information

Page 68: Database Systems

68

Outer Joins

Student 105 (Michael Connoly) does not have any ENROLLMENT records

Page 69: Database Systems

69

Outer Joins

• No records retrieved for Michael:

Page 70: Database Systems

70

Outer Joins

To include records in first (inner) table, even when they do not have matching records in second (outer) table, place outer join marker (+) beside outer table name in join clause

Page 71: Database Systems

71

Outer JoinsOuter join marker

Page 72: Database Systems

72

Self Joins

• Used to join a table to itself when the table has a hierarchical relationship

Page 73: Database Systems

73

Self Joins

• To create a self-join, you need to create a table alias, which gives an alternate name to the table so you can create a join condition

• Syntax to create table alias in FROM clause:

FROM table1 alias1, table2 alias2

Page 74: Database Systems

74

Self Joins P_ID PROJECT_NAME CLIENT_ID MGR_ID PARENT_P_ID

1 Hardware Support Intranet 2 105

2 Hardware Support Interface 2 103 1

3 Hardware Support Database 2 102 1

4 Teller Support System 4 105

5 Internet Advertising 6 105

6 Network Design 6 104 5

7 Exploration Database 5 102

PARENT_PROJECT

P_ID PROJECT_NAME CLIENT_ID MGR_ID PARENT_P_ID

1 Hardware Support Intranet 2 105

2 Hardware Support Interface 2 103 1

3 Hardware Support Database 2 102 1

4 Teller Support System 4 105

5 Internet Advertising 6 105

6 Network Design 6 104 5

7 Exploration Database 5 102

PROJECT

P_ID PROJECT_NAME CLIENT_ID MGR_ID PARENT_P_ID

1 Hardware Support Intranet 2 105

2 Hardware Support Interface 2 103 1

3 Hardware Support Database 2 102 1

4 Teller Support System 4 105

5 Internet Advertising 6 105

6 Network Design 6 104 5

7 Exploration Database 5 102

SUB_PROJECT

Page 75: Database Systems

75

Self Join Example

Page 76: Database Systems

76

Inequality Joins

• Join created by placing making join condition satisfy an inequality condition

Page 77: Database Systems

77

Inequality Joins

Page 78: Database Systems

78

Nested Queries

• Created when a sub-query is nested within a main query• Main query: first query listed in

SELECT command• Sub-query: retrieves one or more

values that specify the main query’s search condition

Page 79: Database Systems

79

Nested Query WhereSub-query Returns a Single Value

• Syntax:SELECT column1, column2, …

FROM table1, table2, …

WHERE join conditions

AND search_column1 = (SELECT column1

FROM table1, table2, …

WHERE search and

join conditions)

Sub-querythat returnsone value

Page 80: Database Systems

80

Nested Query WhereSub-query Returns Multiple Values

• Syntax:SELECT column1, column2, …

FROM table1, table2, …

WHERE join conditions

AND search_column1 IN (SELECT column1

FROM table1, table2, …

WHERE search and

join conditions)

Sub-querythat returnsmultiple values

Page 81: Database Systems

81

• Performs set operations on outputs of two unrelated queries

• Both queries must have:• same number of display fields• corresponding display fields must have

same data type

Using Set Operators in Queries

Page 82: Database Systems

82

• UNION: combines results, suppresses duplicate rows

• UNION ALL: combines results, displays duplicates

• INTERSECT: finds matching rows• MINUS: returns the difference

between returned record sets

Query Set Operators

Page 83: Database Systems

83

Selecting Records For Update

• In a normal SELECT command, the retrieved records are not locked, and are available for other users to view, updated, and delete

• Sometimes, you need to select records, and then immediately update them based on the retrieved values• Airline seat reservations• Inventory items for sale

Page 84: Database Systems

84

Selecting Records For Update

• Syntax:SELECT column1, column2, …

FROM table1, table2, …

WHERE search and join conditions

FOR UPDATE OF column1, column2, …

NOWAIT;

Page 85: Database Systems

85

Selecting Records For Update

• All retrieved records are locked until you issue a COMMIT command• Fields listed in FOR UPDATE clause are

for documentation purposes only

• NOWAIT clause is optional• Makes it so when another user tries to

retrieved locked record, their system doesn’t just “hang”

Page 86: Database Systems

86

• Logical table based on a query• Does not physically exist in the

database• Presents data in a different format

from underlying tables• Uses:

• Security• Simplifying complex queries

Database Views

Page 87: Database Systems

87

• Creating a view:CREATE VIEW view_name AS

SQL_command;

• Views can be queried just like tables:SELECT *

FROM view_name;

Database Views

Page 88: Database Systems

88

Simple Views

• Based on SQL query that retrieves data from only one table

• View can support all table operations:• INSERT• UPDATE• DELETE

Page 89: Database Systems

89

Complex Views

• Based on query that retrieves data from multiple tables

• Can only be used to support SELECT operations• No table operations supported

Page 90: Database Systems

90

Indexes

• Index: Separate table is maintained that shows index keys and physical locations of corresponding records• In Oracle, ROWID is

translated to physical location of row on disk

• Improves response time of searches and joins

SLName ROWID

Brown 13387289

Jones 13879872

Smith 58925789

Helgeson 29875018

Page 91: Database Systems

91

Using Indexes

• Create table index AFTER table is populated with data• Indexes make INSERT, UPDATE, and DELETE

operations slower because index must also be maintained

Page 92: Database Systems

92

Indexing Strategies

• A table can have indexes on multiple fields• Create indexes based on fields used for search or join

operations• Typically, indexes only speed retrievals when <15% of the

table records are involved

• Each additional index adds processing overhead for INSERT, UPDATE, and DELETE operations

• In Oracle, primary keys are automatically indexed

Page 93: Database Systems

93

Creating Indexes

• Syntax:CREATE INDEX index_name

ON tablename(index_field);

Page 94: Database Systems

94

Synonyms

• Alternate name for a table• Allows you to not have to preface

table with owner’s username when you are querying a table that belongs to another user

Page 95: Database Systems

95

Public Synonyms

• Can only be created by a DBA• Syntax:CREATE PUBLIC SYNONYM synonym_name

FOR owner_name.tablename;

• All users with privileges to use table can then use synonym instead of owner_name.tablename

Page 96: Database Systems

96

Private Synonyms

• You can create private synonyms for any tables that you have privileges to use

• Only you can use the synonym• Syntax:CREATE SYNONYM synonym_name

FOR table_name.table_name;

Page 97: Database Systems

End of Lecture