Download presentation
Presentation is loading. Please wait.
1
Database Systems
2
Major Content & Grade Introduction * The Relational Model *** SQL ****
Transaction Management *** Database Design (E-R) *** Database Design (Normalization) ***
3
Unit 3 SQL 3.1 Introduction 3.2 Setting Up the Database 3.3 Queries
3.4 View 3.5 Data manipulation 3.6 Security
4
About SQL SQL is of the ability to implementing database in a computerized environment. The SQL is an non-procedural language. Power of SQL: Data definition (DDL) ( Include Other database object definition ) Interactive Data manipulation (DML) Embedded SQL and dynamic SQL(数据库应用课讲) Integrity Authorization (Security) Transaction Control
5
History of SQL IBM Sequel (Specifying QUeries As Relational Expression, 1972) language developed as part of System R project at the IBM San Jose Research Lab SEQUEL (Structured English QUEry Language,1974) Renamed SQL (Structured Query Language, 1976) ANSI and ISO standard SQL: SQL-86, SQL-89 (SQL1) SQL-92 (SQL2) SQL:1999 (SQL3) SQL:2003 Commercial systems offer most, if not all, SQL-92 features, plus varying feature sets from later standards and special proprietary features.
6
Unit 3 SQL 3.1 Introduction 3.2 Setting Up the Database 3.3 Queries
3.4 View 3.5 Data manipulation 3.6 Security
7
Data Definition Language
Data Definition Language (DDL) provide the abilities to setting up a database. DDL allows the specification of not only a set of relations but also information about each relation, including: The schema for each relation. The domain of values associated with each attribute. Integrity constraints The set of indices to be maintained for each relations. Security and authorization information for each relation. The physical storage structure of each relation on disk.
8
Domain Types in SQL char(n): Fixed length character string, with user-specified length n. varchar(n): Variable length character strings, with user-specified maximum length n. int: Integer (a finite subset of the integers that is machine-dependent). smallint: Small integer (a machine-dependent subset of the integer domain type). numeric(p,d): Fixed point number, with user-specified precision of p digits, with n digits to the right of decimal point.
9
Domain Types in SQL real, double precision: Floating point and double-precision floating point numbers, with machine-dependent precision. float(n): Floating point number, with user-specified precision of at least n digits. date: Dates, containing a (4 digit) year, month and date Example: date ‘ ’ time: Time of day, in hours, minutes and seconds. Example: time ‘09:00:30’ time ‘09:00:30.75’ timestamp: date plus time of day Example: timestamp ‘ :00:30.75’
10
Domain Types in SQL blob: binary large object -- object is a large collection of uninterpreted binary data (whose interpretation is left to an application outside of the database system). clob: character large object -- object is a large collection of character data. User-defined domain: Example: create domain money numeric(12, 2)
11
Creating DataBase Creating the Banking database: Database Schema:
branch (branch_name, branch_city, assets) customer (customer_name, customer_street, customer_city) depositor (customer_name, account_number) account (account_number, branch_name, balance) borrower (customer_name, loan_number) loan (loan_number, branch_name, amount) Creating database Banking steps: 1) CREATE DATABASE Banking … (syntax lie on DBMS) 2) Creating referenced tables(被参照关系) 3) Creating referencing tables 4) Creating other object of database
12
Creating Tables Syntax
An SQL relation is defined using the create table command: CREATE TABLE <table-name> ( [ [ <column-name1 data_type> [<column_constraint>] , [ ...n ] ] [ <table_constraint> ], ] );
13
Creating Tables Creating Tables in the Banking database:
//Creating table customer in SQL CREATE TABLE customer ( customer_name char(20), customer_street char(30) NOT NULL, customer_city char(30) ) ;
14
Integrity Constraints in Tables
Integrity constraints ENSURE that changes made to the database by authorized DO NOT result in a loss of data consistency. PRIMARY KEY Constrants (Entity integrity) FROEIGE KEY Constrants (Referential integrity) [NOT] NULL Constrants UNIQUE Constrants DEFAULT Constrants CHECK Constrants Assertion Constrants Syntax CONSTRAINT <constraint_name> <constraint>
15
Integrity Constraints in Tables
Create table with constraints CREATE TABLE account ( account_number char(10), branch_name char(30) NOT NULL, balance numeric(12.2), PRIMARY KEY (account_number), FOREIGN KEY (branch_name) REFERENCES branch(branch_name), CONSTRAINT chk_balance CHECK (balance >= 0 ) ) ; The referenced table must be an existing relation! Integrity constraints can be added to an existing relation, if the relation does not satisfies the constraint, reject! Constraint name make it easy to drop.
16
Drop and Alter Table The drop table command deletes all information about the dropped relation from the database. Syntax: DROP TABLE <table_name>; Example: DROP TABLE customer The alter table command is used to add attributes or constraints to an existing relation. Syntax: ALTER TABLE < table_name > ADD|DROP|ALTER …; Examples: ALTER TABLE customer ADD customer_id CHAR(10); ALTER TABLE customer DROP customer_city; ALTER TABLE account ALTER balance numeric(10.2);
17
More about create tables
After create table statement executed, the definition will been stored in Data Dictionary as metadata. A foreign key specification is accepted only if it references an existing table. There are more complex integrity Constraints will be introduced later. Only after tables been created, data can be entered into the table in database. Integrity Constraints are important part of table to avoid invalid data into database.
18
课后阅读 3.1, 3.2 4.1, 4.2
19
Database Systems
20
Unit 3 SQL 3.1 Introduction 3.2 Setting Up the Database 3.3 Queries
3.4 View 3.5 Data manipulation 3.6 Security
21
Basic Query Structure SQL is based on set and relational operations with certain modifications and enhancements A typical SQL query has the form: SELECT A1, A2, ..., An FROM r1, r2, ..., rm WHERE P ; Ai represents an attribute Ri represents a relation P is a predicate This query is equivalent to the relational algebra expression: The result of an SQL query is a relation.
22
The SELECT Clause The SELECT clause list the attributes desired in the result of a query corresponds to the projection operation of the relational algebra Example: find the names of all branches in the loan relation: SELECT branch_name FROM loan ; In the relational algebra, the query would be: branch_name (loan) NOTE: SQL names are case insensitive (i.e., you may use upper- or lower-case letters.)
23
The SELECT Clause SQL allows duplicates in relations as well as in query results. To force the elimination of duplicates, insert the keyword DISTINCT after select. Example: Find the names of all branches in the loan relations, and remove duplicates SELECT DISTINCT branch_name FROM loan ; The keyword all specifies that duplicates not be removed. SELECT ALL branch_name FROM loan ;
24
The SELECT Clause An asterisk(*) in the select clause denotes “all attributes” SELECT * FROM loan ; The SELECT clause can contain arithmetic expressions involving the operation, +, –, , and /, and operating on constants or attributes of tuples. The query: SELECT loan_number, branch_name, amount FROM loan ; would return a relation that is the same as the loan relation, except that the value of the attribute amount is multiplied by 100.
25
The WHERE Clause The WHERE clause specifies conditions that the result must satisfy. Corresponds to the selection predicate of the relational algebra. Example: Find all loan number at the Perryridge branch with loan amounts greater than $ SELECT loan_number FROM loan WHERE branch_name=‘ Perryridge’ AND amount>1200; Comparison results can be combined using the logical connectives AND, OR, and NOT.
26
The WHERE Clause SQL includes a BETWEEN comparison operator
Example: Find the loan number of those loans with loan amounts between $90,000 and $100,000 (that is, $90,000 and $100,000) SELECT loan_number FROM loan WHERE amount BETWEEN AND ;
27
The FROM Clause The FROM clause lists the relations involved in the query Corresponds to the Cartesian product operation of the relational algebra. Example: Find the Cartesian product borrower × loan SELECT FROM borrower, loan ; Example: Find the name, loan number and loan amount of all customers having a loan at the Perryridge branch SELECT customer_name, borrower.loan_number, amount FROM borrower, loan WHERE borrower.loan_number = loan.loan_number AND branch_name = ‘Perryridge’ ;
28
The RENAME Operation The SQL allows renaming relations and attributes using the AS clause: old-name AS new-name Example: Find the name, loan number and loan amount of all customers; rename the column name loan_number as loan_id. SELECT customer_name, borrower.loan_number AS loan_id, amount FROM borrower, loan WHERE borrower.loan_number = loan.loan_number ;
29
The RENAME Operation Relation variables are defined in the FROM clause via the use of the as clause. Example: Find the customer names, loan number and loan amount for all customers having a loan from the bank. SELECT customer_name, B.loan_number, amount FROM borrower AS B, loan AS L WHERE B.loan_number = L.loan_number ;
30
Branch_ name city assets Brighton Brooklyn Downtown Mianus Horseneck 400000 North Town Rye … …… branch The RENAME Operation Example: Find the names of all branches that have assets greater than at least one (some) branch located in Brooklyn. B1.bn B1.bc B1.a B2.bn B2.bc B2.a Brighton Brooklyn Downtown Mianus Horseneck 400000 North Town Rye … ……. …… πB1.branch_name(B1.assets>B2.assets ( B1)( branch) × B2.branch_cith=‘Brooklyn’(B2( branch)) ) )
31
Branch_ name city assets Brighton Brooklyn Downtown Mianus Horseneck 400000 North Town Rye … …… branch The RENAME Operation Example: Find the names of all branches that have assets greater than at least one (some) branch located in Brooklyn. SELECT DISTINCT B1.branch_name FROM branch AS B1, branch AS B2 WHERE B1.assets > B2.assets AND B2.branch_city = ‘ Brooklyn’ ; πB1.branch_name(B1.assets>B2.assets B2.branch_cith=‘Brooklyn’( B1)( branch) × B2( branch) ) )
32
String Operations SQL includes a string-matching operator for comparisons on character strings. The operator “LIKE” uses patterns that are described using two special characters: percent (%). The % character matches any substring. underscore (_). The _ character matches any character. Example: Find the names of all customers whose street includes the substring “Main”. SELECT customer_name FROM customer WHERE customer_street LIKE ‘%Main%’ ; Example: Match the name “Main%” LIKE ‘Main\%’ escape ‘\’
33
The ORDER BY Clause The ORDER BY Clause Ordering the Display of Tuples
Example: List in alphabetic order the names of all customers having a loan in Perryridge branch SELECT DISTINCT customer_name FROM borrower, loan WHERE borrower loan_number = loan.loan_number AND branch_name = ‘Perryridge’ ORDER BY customer_name ; We may specify DESC for descending order or ASC for ascending order, for each attribute; ascending order is the default. Example: ORDER BY customer_name DESC
34
Set Operations The set operations union, intersect, and except operate on relations and correspond to the relational algebra operations Each of the above operations automatically eliminates duplicates; to retain all duplicates use the corresponding multiset versions union all, intersect all and except all. Set operations may NOT been implemented in some DBMS.
35
Set Operations Examples:
Find all customers who have a loan, an account, or both: (SELECT customer_name FROM depositor) UNION (SELECT customer_name FROM borrower) ; Find all customers who have both a loan and an account. (SELECT customer_name FROM depositor) INTERSECT (SELECT customer_name FROM borrower) ; Find all customers who have an account but no loan. (SELECT customer_name FROM depositor) EXCEPT (SELECT customer_name FROM borrower) ;
36
Database Systems
37
Unit 3 SQL 3.1 Introduction 3.2 Setting Up the Database 3.3 Queries
3.4 View 3.5 Data manipulation 3.6 Security
38
Aggregate Functions(集函数)
These functions operate on the multiset of values of a column of a relation, and return a value avg([DISTINCT | ALL] <column_name>): average value min([DISTINCT | ALL] <column_name>): minimum value max([DISTINCT| ALL] <column_name>): maximum value sum([DISTINCT | ALL] <column_name>): sum of values count([DISTINCT | ALL] <column_name>) count([DISTINCT | ALL] *) : number of values
39
Aggregate Functions Examples:
Find the average account balance at the Perryridge branch. SELECT avg (balance) FROM account WHERE branch_name = ‘Perryridge’ ; Find the number of tuples in the customer relation. SELECT count (*) FROM customer ; Find the number of depositors in the bank. SELECT count (DISTINCT customer_name) FROM depositor ;
40
The GROUP BY Clause The GROUP BY Clause division records in the middle result into different part(group) according attribute or attributes given by the GROUP BY Clause. Tuples with the same value on all attributes in the GROUP BY Clause are placed in one group. After the tuples was grouped, Aggregate Functions will act on the group, NOT the whole tuples.
41
The GROUP BY Clause Example: Find the number of depositors for each branch. SELECT branch_name, count (customer_name) FROM depositor, account WHERE depositor.account_number = account.account_number GROUP BY branch_name ; (DISTINCT customer_name) Note: Attributes in SELECT clause outside of aggregate functions must appear in GROUP BY list.
42
The HAVING Clause The HAVING Clause is used to choose the specific groups according the given predicate following the HAVING Clause. The HAVING Clause is usually after the GROUP BY Clause. Example: Find the names of all branches where the average account balance is more than $1,200. SELECT branch_name, avg (balance) FROM account GROUP BY branch_name HAVING avg (balance) > 1200 ;
43
Executing Orders of Query Clauses
SELECT [ALL | DISTINCT ] [*] | [<object_exp1>[, <object_exp1> ]… ] FROM <table_name1>[, <table_name2 > ] … [ WHERE <condition_exp> ] [ GROUP BY <column_names> ] [ HAVING <condition_exp> ] [ ORDER BY <column_name1> [ ASC | DESC ] [<column_name2> [ ASC | DESC ] …]] ; ④ ① ② ③ ⑤
44
Null Values It is possible for tuples to have a null value, denoted by null, for some of their attributes null signifies an unknown value or that a value does not exist. The predicate IS NULL can be used to check for null values. Example: Find all loan number which appear in the loan relation with null values for amount. SELECT loan_number FROM loan WHERE amount IS NULL ; The result of any arithmetic expression with null involving null is null Example: 5 + null returns null Any comparison with null returns unknown Example: 5 < null or null <> null or null = null
45
Null Values Three-valued logic using the truth value unknown:
OR: (unknown OR true) = true, (unknown OR false) = unknown (unknown OR unknown) = unknown AND: (true AND unknown) = unknown, (false AND unknown) = false, (unknown AND unknown) = unknown NOT: (NOT unknown) = unknown “P is unknown” evaluates to true if predicate P evaluates to unknown Result of WHERE clause predicate is treated as false if it evaluates to unknown
46
Null Values Aggregate functions simply ignore nulls
Total all loan amounts SELECT sum (amount ) FROM loan ; Above statement ignores null amounts Result is null if there is no non-null amount All aggregate operations except count(*) ignore tuples with null values on the aggregated attributes.
47
Nested Subqueries SQL provides a mechanism for the nesting of subqueries. A subquery is a SELECT-FROM-WHERE expression that is nested within another query. Nested Query indicates that SQL is a structured language. SELECT [ALL | DISTINCT ] [*] | [<object_exp1>[, <object_exp1> ]… ] FROM <table_name1>[, <table_name2 > ] … [ WHERE <condition_exp> ] [ GROUP BY <column_names> ] [ HAVING <condition_exp> ] [ ORDER BY <column_name1> [ ASC | DESC ] [<column_name2> [ ASC | DESC ] …]] ;
48
The IN predicate Find all customers who have both an account and a loan at the bank. SELECT DISTINCT customer_name FROM borrower WHERE customer_name IN ( SELECT customer_name FROM depositor ) ; Find all customers who have a loan at the bank but do not have an account at the bank SELECT DISTINCT customer_name FROM borrower WHERE customer_name NOT IN ( SELECT customer_name FROM depositor ) ;
49
The IN predicate Find all customers who have both an account and a loan at the Perryridge branch. A1 (IN predicate) SELECT DISTINCT customer_name FROM borrower, loan WHERE borrower.loan_number = loan.loan_number AND branch_name = ‘Perryridge’ AND (branch_name, customer_name ) IN ( SELECT branch_name, customer_name FROM depositor, account WHERE depositor.account_number = account.account_number ) ;
50
The IN predicate Find all customers who have both an account and a loan at the Perryridge branch. account_ number branch_ name balance A-101 Downtown 500 A-215 Mianus 700 A-102 Perryridge 400 A-305 Round Hill 350 A-201 Brighton 900 A-222 Redwood A-217 750 account loan_ number branch_ name amount L-11 Round Hill 900 L-14 Downtown 1500 L-15 Perryridge L-16 1300 L-17 1000 L-23 Redwood 2000 L-93 Mianus 500 loan πdepositor.customer_name( depositor.customer_name = borrower.customer_name account.branch_name = ‘Perryridge’ loan.branch_name = ‘Perryridge’ ( ) (depositor account) × (borrower loan)
51
The IN predicate Find all customers who have both an account and a loan at the Perryridge branch. A2 (Algebra expression) SELECT DISTINCT depositor.customer_name FROM depositor , account, borrower, loan WHERE depositor.account_number = account.account_number AND borrower.loan_number = loan.loan_number AND depositor.customer_name = borrower.customer_name AND account.branch_name = ‘Perryridge’ AND loan.branch_name = ‘Perryridge’ ; πdepositor.customer_name( depositor.customer_name = borrower.customer_name account.branch_name = ‘Perryridge’ loan.branch_name = ‘Perryridge’ ( ) (depositor account) × (borrower loan)
52
Set Comparison >some ( > any ), including >=, <, <=, = … >all, including >=, <, <=, = … Example: Find all branches that have greater assets than some branch located in Brooklyn. Branch_ name city assets Brighton Brooklyn Downtown Mianus Horseneck 400000 North Town Rye … …… branch SELECT branch_name FROM branch WHERE assets > some ( SELECT assets FROM branch WHERE branch_city = ‘Brooklyn’)
53
Set Comparison Find the names of all branches that have greater assets than all branches located in Brooklyn. Branch_ name city assets Brighton Brooklyn Downtown Mianus Horseneck 400000 North Town Rye … …… branch SELECT branch_name FROM branch WHERE assets > all ( SELECT assets FROM branch WHERE branch_city = ‘Brooklyn’)
54
Set Comparison Find the branch that has the highest average balance.
account_ number branch_ name balance A-101 Downtown 500 A-215 Mianus 700 A-102 Perryridge 400 A-305 Round Hill 350 A-201 Brighton 900 A-222 Redwood A-217 750 account SELECT branch_name FROM account GROUP BY branch_name HAVING avg(balance) = max ( SELECT avg(balance) FROM account GROUP BY branch_name) ; 原因:集函数不能作用于查询外部!
55
Set Comparison Find the branch that has the highest average balance.
account_ number branch_ name balance A-101 Downtown 500 A-215 Mianus 700 A-102 Perryridge 400 A-305 Round Hill 350 A-201 Brighton 900 A-222 Redwood A-217 750 account SELECT branch_name FROM account GROUP BY branch_name HAVING avg(balance) = ( SELECT avg(balance) FROM account GROUP BY branch_name) ; max(avg(balance)) 原因:集函数不能复合!
56
Set Comparison Find the branch that has the highest average balance.
account_ number branch_ name balance A-101 Downtown 500 A-215 Mianus 700 A-102 Perryridge 400 A-305 Round Hill 350 A-201 Brighton 900 A-222 Redwood A-217 750 account SELECT branch_name FROM account GROUP BY branch_name HAVING avg(balance) >= ALL ( SELECT avg(balance) FROM account GROUP BY branch_name) ;
57
Test for Empty Relations
The exists construct returns the value true if the argument subquery is nonempty. Example: Find the customers name who have at least one deposit of a balance greater than $700. {t | u( depositor(u) v( account(v) u[account_number ] = v[account_number] v[balance ] > ‘700’ ) t[customer_name] = u[customer_name ] ) } SELECT DISTINCT customer_name FROM depositor WHERE EXISTS ( SELECT * FROM account WHERE depositor.account = account.account AND balance > 700 ) ;
58
Test for Empty Relations
Find all customers who have an account at all branches located in Brooklyn. {t | u ( depositor(u) v (branch(v) v[branch_city] = ‘Brooklyn’ w( account(w) w[account_number] = u[account_number] w[branch_name] = v[branch_name]) ) t[customer_name] = u[customer_name] ) } 等价转换 {t | u ( depositor(u) v (branch(v) v[branch_city] = ‘Brooklyn’ w( account(w) w[account_number] = u[account_number] w[branch_name] = v[branch_name]) ) t[customer_name] = u [customer_name] ) }
59
Test for Empty Relations
SELECT DISTINCT customer_name FROM depositor AS D WHERE NOT EXISTS ( SELECT * FROM branch AS B WHERE branch_city = ‘Brooklyn’ AND SELECT * FROM account WHERE account_number = D.account_number AND branch_name = B. branch_name)); {t | u ( depositor(u) v (branch(v) v[branch_city] = ‘Brooklyn’ w( account(w) w[account_number] = u[account_number] w[branch_name] = v[branch_name]) ) t[customer_name] = u [customer_name] ) }
60
Queries Find the largest account balance. A1 (Algebra expression)
number Branch_ name balance A-101 Downtown 500 A-215 Mianus 700 A-102 Perryridge 400 … …… account Queries Find the largest account balance. A1 (Algebra expression) πbalance(account) – πA1.balance (A1.balance < A2.balance (A1(account) × A2(account) ) ) SELECT DISTINCT balance FROM account EXCEPT SELECT A1.balance FROM account AS A1, account AS A2 WHERE A1.balance < A2.balance ;
61
Queries Find the largest account balance. A2 (Aggregate Functions)
number Branch_ name balance A-101 Downtown 500 A-215 Mianus 700 A-102 Perryridge 400 … …… account Queries Find the largest account balance. A2 (Aggregate Functions) SELECT max(balance) FROM account
62
Queries Find the largest account balance. A3 (Set Comparison)
number Branch_ name balance A-101 Downtown 500 A-215 Mianus 700 A-102 Perryridge 400 … …… account Queries Find the largest account balance. A3 (Set Comparison) SELECT DISTINCT balance FROM account WHERE balance >= ALL ( SELECT balance FROM account );
63
Queries Find the largest account balance. A4 (EXISTS predicate)
number Branch_ name balance A-101 Downtown 500 A-215 Mianus 700 A-102 Perryridge 400 … …… account Queries Find the largest account balance. A4 (EXISTS predicate) {t | u ( account(u) v( account(v) u[balance] v[balance]) t[balance] = u[balance] ) } SELECT DISTINCT A1.balance FROM account A1 WHERE NOT EXISTS ( SELECT * FROM account A2 WHERE A1.balance < A2.balance);
64
Test for Absence of Duplicate Tuples
The unique construct tests whether a subquery has any duplicate tuples in its result. Example: Find all customers who have at most one account at the Perryridge branch. SELECT DISTINCT D1.customer_name FROM depositor AS D1 WHERE UNIQUE ( SELECT D2.customer_name FROM account AS A, depositor AS D2 WHERE A.account_number = D2.account_number AND D1.customer_name = D2.customer_name AND A.branch_name = ‘ Perryridge’ ) ;
65
Test for Absence of Duplicate Tuples
Find all customers who have at least two accounts at the Perryridge branch. A1 (using UNIQUE) SELECT DISTINCT D1.customer_name FROM depositor AS D1 WHERE NOT UNIQUE ( SELECT D2.customer_name FROM account AS A, depositor AS D2 WHERE A.account_number = D2.account_number AND D1.customer_name = D2.customer_name AND A.branch_name = ‘ Perryridge’ ) ;
66
Test for Absence of Duplicate Tuples
Find all customers who have at least two accounts at the Perryridge branch. A2 (using GROUP BY) SELECT customer_name FROM depositor AS D, account AS A WHERE D.account_number = A.account_number AND A.branch_name = ‘Perryridge’ GROUP BY customer_name HAVING count(*) > 2 ;
67
Derived Relations SQL allows a subquery expression to be used in the FROM clause Example: Find the average account balance of those branches where the average account balance is greater than $1200. SELECT branch_name, avg_balance FROM (SELECT branch_name, avg (balance) FROM account GROUP BY branch_name ) AS branch_avg ( branch_name, avg_balance ) WHERE avg_balance > 1200
68
With Clause The with clause provides a way of defining a temporary view whose definition is available only to the query in which the with clause occurs. Find all accounts with the maximum balance WITH max_balance (value) as SELECT max (balance) FROM account SELECT account_number FROM account, max_balance WHERE account.balance = max_balance.value
69
With Clause Find all branches where the total account deposit is greater than the average of the total account deposits at all branches. WITH branch_total (branch_name, value) AS SELECT branch_name, sum (balance) FROM account GROUP BY branch_name WITH branch_total_avg (value) AS SELECT avg (value) FROM branch_total SELECT branch_name FROM branch_total, branch_total_avg WHERE branch_total.value >= branch_total_avg.value
70
Homework 3 3.2 3.9 注:尽可能用多种方法实现查询!
71
Database Systems
72
Unit 3 SQL 3.1 Introduction 3.2 Setting Up the Database 3.3 Queries
3.4 View 3.5 Data manipulation 3.6 Security
73
Views In some cases, it is not desirable for all users to see the entire logical model (that is, all the actual relations stored in the database.) Consider a person who needs to know a customer’s loan number but has no need to see the loan amount. This person should see a relation described, in SQL, by (select customer_name, loan_number from borrower, loan where borrower.loan_number = loan.loan_number ); A view provides a mechanism to hide certain data from the view of certain users. Any relation that is not of the conceptual model but is made visible to a user as a “virtual relation” is called a view.
74
Create Views A view is defined using the create view statement which has the form: CREATE VIEW v AS < query expression> ; where <query expression> is any legal SQL expression. The view name is represented by v.
75
Create Views Once a view is defined, the view name can be used to refer to the virtual relation that the view generates. When a view is created, the definition of the view is placed in the database, but no data is retrieved or stored. A view is a window on the data of the base tables, thus queries on views are immediately responsive to changes in the underlying base table data.
76
Create Views A view consisting of branches and their customers
branch (branch_name, branch_city, assets) customer (customer_name, customer_street, customer_city) depositor (customer_name, account_number) account (account_number, branch_name, balance) borrower (customer_name, loan_number) loan (loan_number, branch_name, amount)
77
Create Views A view consisting of branches and their customers
CREATE VIEW all_customer AS (SELECT branch_name, customer_name FROM depositor, account WHERE depositor.account_number = account.account_number ) UNION (SELECT branch_name, customer_name FROM borrower, loan WHERE borrower.loan_number = loan.loan_number ); Find all customers of the Perryridge branch. SELECT customer_name FROM all_customer WHERE branch_name = ‘Perryridge’ ;
78
Create Views If the optional column name list is not specified, then the columns of the new view table will inherit(继承) names of single columns in the target list of the Subquery statements. However, names must be provided when any view columns represent expressions in the target list. Example: create a view for each branch the sum of the amounts of all the loans at the branch. CREATE VIEW branch_total_loan(branch_name, total_loan) AS SELECT branch_name, sum(amount) FROM loan GROUP BY branch_name ;
79
Create Views One view may be used in the expression defining another view A view relation v1 is said to depend directly on a view relation v2 , if v2 is used in the expression defining v1 A view relation v1 is said to depend on view relation v2 , if either v1 depends directly to v2 or there is a path of dependencies from v1 to v2 A view relation v is said to be recursive if it depends on itself.(不要求掌握)
80
Drop Views Syntax: DROP VIEW viewname {CASCADE|RESTRICT};
81
Views & ANSI/SPARC architecture
View is the external level of the DBMS architecture.
82
ANSI/SPARC architecture
成绩单 学号:xxxxx 姓名:xxx 性别:x 离散数据 75 数据库系统 81 …… 外模式(External Schema,也称子模式或用户模式) ——数据库用户使用的局部数据的逻辑结构和特征的描述 模式(Logical Schema, Schema,也称逻辑模式) ——数据库中全体数据的逻辑结构和特征(型)的描述 Sno Sname Ssex Sage Sdept Cno Cname Cpno Ccredit Sno Cno Grade 内模式(Physical Schema,也称存储模式) ——数据物理结构和存储方式的描述
83
ANSI/SPARC architecture
CREATE VIEW scores AS (SELECT sno, sname,ssex,cname,grade FROM S, C, SC WHERE S.sno = SC.sno AND SC.cno = C.cno ; ANSI/SPARC architecture 成绩单 学号:xxxxx 姓名:xxx 性别:x 离散数据 75 数据库系统 81 …… NOTE: A view create the External Schema and also the map from External Schema to Logical Schema. S C Sno Sname Ssex Sage Sdept Cno Cname Cpno Ccredit SC Sno Cno Grade
84
ANSI/SPARC architecture
CREATE VIEW scores AS (SELECT sno, sname,ssex,cname,grade FROM S, C, SC WHERE S.sno = SC.sno AND SC.cno = C.cno ; ANSI/SPARC architecture 成绩单 学号:xxxxx 姓名:xxx 性别:x 离散数据 75 数据库系统 81 …… External/Conceptual mapping Sno Sname Ssex Sage Sdept Cno Cname Cpno Ccredit ……………… …… ………………… Sno Cno Grade Conceptual/Internal mapping MAPPING
85
Data Independence Two type data independence Logical data independence
the immunity of the external schemas to changes in the conceptual schema. related to External/Conceptual mapping Physical data independence the immunity of the conceptual schema to changes in the internal schema. related to Conceptual/Internal mapping
86
The value of views Views provide a way to make complex, commonly issued queries easier to compose.(简化查询) Views allow obsolete tables, and programs that reference them, to survive reorganization. (数据库重组) Views add a security aspect to allow different users to see the same data in different ways. (不同角度看待同一数据)
87
Unit 3 SQL 3.1 Introduction 3.2 Setting Up the Database 3.3 Queries
3.4 View 3.5 Data manipulation 3.6 Security
88
Insertion Syntax To insert ONE tuple or a query result into a table.
INSERT INTO table_name [(col_name1 {, col_name2…})] VALUES (expr1| NULL {, expr2|NULL…}) | Subquery ; Add a new tuple to account . INSERT INTO account VALUES ( ‘A-9732’, ‘Perryridge’,1200 ) ; or INSERT INTO account (branch_name, balance, account_number) VALUES ( ‘Perryridge’, 1200, ‘A-9732’) ;
89
Insertion Present a new $200 savings account as a gift to all loan customers of the Perryridge branch, for each loan they have. Let the loan number serve as the account number for the new savings account. branch (branch_name, branch_city, assets) customer (customer_name, customer_street, customer_city) depositor (customer_name, account_number) account (account_number, branch_name, balance) borrower (customer_name, loan_number) loan (loan_number, branch_name, amount)
90
Insertion Present a new $200 savings account as a gift to all loan customers of the Perryridge branch, for each loan they have. Let the loan number serve as the account number for the new savings account. INSERT INTO account SELECT loan_number, branch_name, FROM loan WHERE branch_name = ‘Perryridge’ ; INSERT INTO depositor SELECT customer_name, loan_number FROM loan, borrower WHERE branch_name = ‘ Perryridge’ AND loan. loan_number = borrower. loan_number ; The two SQL statements must be ONE transaction.
91
Updates To change a value in a tuple in current table without changing all values in the tuple. Syntax UPDATE table_name SET col_name1 = {expr | NULL| (Subquery1)} {, col_name2= {expr|NULL| (Subquery2)…}} [WHERE search_condition];
92
Updates Increase all accounts with balances over $10,000 by 6%, all other accounts receive 5%. Write two update statements: UPDATE account SET balance = balance WHERE balance > ; UPDATE account SET balance = balance WHERE balance <= ; The order is important Also should be a transaction
93
Updates Same query as before: Increase all accounts with balances over $10,000 by 6%, all other accounts receive 5%. UPDATE account SET balance = CASE WHEN balance <= THEN balance * ELSE balance * END ;
94
Deletion To delete the tuple(s) in the current table. Syntax
Delete all account tuples at the Perryridge branch. DELETE FROM account WHERE branch_name = ‘Perryridge’ ; Delete all accounts at every branch located in the city ‘Needham’. DELETE FROM account WHERE branch_name IN ( SELECT branch_name FROM branch WHERE branch_city = ‘Needham’ ) ; DELETE FROM table_name [WHERE search_conditon];
95
Deletion Delete the record of all accounts with balances below the average at the bank. DELETE FROM account WHERE balance < (SELECT avg (balance ) FROM account ); Problem: as we delete tuples from deposit, the average balance changes Solution used in SQL: 1. First, compute avg balance and find all tuples to delete 2. Next, delete all tuples found above (without recomputing avg or retesting the tuples)
96
Update of a view A modification to a view must be translated to a modification to the actual relations in the logical model of the database. Example: Create a view of all loan data in the loan relation, hiding the amount attribute: CREATE VIEW branch_loan AS SELECT branch_name, loan_number FROM loan ; Add a new tuple to branch_loan : INSERT INTO branch_loan VALUES (‘Perryridge’, ‘L-307’) ; This insertion must be represented by the insertion of the tuple (‘L-307’, ‘Perryridge’, null ) into the loan relation
97
Update of a view Suppose a view downtown_account is defined as follow:
CREATE VIEW downtown_account AS SELECT account_number, branch_name, balance FROM account WHERE branch_name = ‘Downtown’ ; Then the tuple (‘A-999’, ‘Perryridge’, 100) can be inserted into the downtown_account view, in fact, the tuple is inserted into the TABLE account, but this is not what we want. This problem can be solved at the defination of view: CREATE VIEW v AS < query expression> [WITH CHECK OPTION]; The clause WITH CHECK OPTION add the view’s WHERE conditions to the modifications of view.
98
Update of a view Redefine the view downtown_account as follow:
CREATE VIEW downtown_account AS SELECT account_number, branch_name, balance FROM account WHERE branch_name = ‘Downtown’ WITH CHECK OPTION ; INSERT INTO downtown_account(account_number, balance) VALUES (‘A-999’, 100); will insert the tuple (‘A-999’, ‘downtown’, 100) into TABLE account, and insert the tuple (‘A-999’, ‘Perryridge’, 100) to the view downtown_account will be rejected by the DBMS. Updates and Deletes are similarly rejected if the new value does not satisfy the WHERE clause condition.
99
Update of a view A view is either updatable or read-only. Insert, Update, and Delete operations are permitted for updatable view and not permitted for read-only views. To be an updatable view, the following conditions must be all satisfied: The FROM clause has only one database relation. The SELECT clause contains only attribute names of the relation, and does not have any expressions, aggregates, or DISTINCT specification. Any attribute not listed in the SELECT clause can be set to NULL. The query does not have a GROUP BY or HAVING clause.
100
Joined Relations Join operations take two relations and return as a result another relation. These additional operations are typically used as subquery expressions in the from clause Join condition – defines which tuples in the two relations match, and what attributes are present in the result of the join. Join type – defines how tuples in each relation that do not match any tuple in the other relation (based on the join condition) are treated.
101
Joined Relations borrower loan NATURAL INNER JOIN borrower loan_number
branch_name amount L-170 Downtown 3000 L-230 Redwood 4000 L-260 Perryridge 1700 loan customer_name loan_number Jones L-170 Smith L-230 Hayes L-155 borrower loan INNER JOIN borrower ON loan.loan_number = borrower.loan_number loan NATURAL INNER JOIN borrower loan_number branch_Name amount customer_name L-170 Downtown 3000 Jones L-230 Redwood 4000 Smith
102
Joined Relations borrower
loan_number branch_name amount L-170 Downtown 3000 L-230 Redwood 4000 L-260 Perryridge 1700 loan customer_name loan_number Jones L-170 Smith L-230 Hayes L-155 borrower loan LEFT OUTER JOIN borrower on loan.loan_number = borrower.loan_number
103
Joined Relations loan natural right outer join borrower borrower
loan_number branch_name amount L-170 Downtown 3000 L-230 Redwood 4000 L-260 Perryridge 1700 loan customer_name loan_number Jones L-170 Smith L-230 Hayes L-155 borrower loan natural right outer join borrower
104
Joined Relations loan full outer join borrower using (loan_number)
branch_name amount L-170 Downtown 3000 L-230 Redwood 4000 L-260 Perryridge 1700 loan customer_name loan_number Jones L-170 Smith L-230 Hayes L-155 borrower loan full outer join borrower using (loan_number)
105
Joined Relations Find all customers who have either an account or a loan (but not both) at the bank. SELECT customer_name FROM (depositor natural full outer join borrower ) WHERE account_number IS NULL OR loan_number IS NULL;
106
Database File (ch11) The database is stored as a collection of files. Each file is a sequence of records A database file is partitioned into fixed-length storage units called blocks. Blocks are units of both storage allocation and data transfer. Database system seeks to minimize the number of block transfers between the disk and memory. We can reduce the number of disk accesses by keeping as many blocks as possible in main memory. Buffer – portion of main memory available to store copies of disk blocks.
107
Index of Table (ch12) Records may be stored in the Sequential File Organization(顺序文件) ordered by a search-key. Example: the account relation storage ordered by branch_name: To find the records By a given branch_name value? -- binary search(二分查找) By a given balance value? --Linear search(线性查找) NOT a good idea!
108
Index of Table An index file consists of records (called index entries) of the form: search-key pointer Search Key - attribute or set of attributes used to look up records in a file. Search Key is ordered or hashed. Indexing mechanisms used to speed up access to desired data.
109
Index of Table Types of index
Primary index: in a sequentially ordered file, the index whose search key specifies the sequential order of the file. Also called clustering index The search key of a primary index is usually but not necessarily the primary key. Secondary index: an index whose search key specifies an order different from the sequential order of the file. Also called non-clustering index. Unique index: an index was the accepted way in some database systems to guarantee a uniqueness constraint for a candidate key.
110
Index of Table SQL DDL about index:
CREATE [UNIQUE | CLUSTER] INDEX <index_name> ON < table_name > ( <column_name1> [ASC | DESC] [<column_name2 > [ASC | DESC] ]…) ; E.g.: CREATE INDEX b-index ON branch(branch_name) DROP INDEX < index_name > ;
111
Homework 4 3.15 3.19
Similar presentations
© 2025 SlidePlayer.com Inc.
All rights reserved.