




















Study with the several resources on Docsity
Earn points by helping other students or get them with a premium plan
This page cannot be seen from the preview
Don't miss anything!





















Advanced SQL: SQL Data Types and Schemas, Integrity Constraints, Authorization, Embedded SQL, Dynamic SQL, Functions and Procedural Constructs, Recursive Queries, Advanced SQL Features. Relational Database Design: Features of Good Relational Design, Atomic Domains and First Normal Form, Functional-Dependency Theory, Decomposition using Functional Dependencies.
Built-in Data Types in SQL date: Dates, containing a (4 digit) year, month and date o Example: date ‘2005- 7 - 27’ time: Time of day, in hours, minutes and seconds. o Example: time ‘09:00:30’ time ‘09:00:30.75’ timestamp : date plus time of day o Example: timestamp ‘2005- 7 - 27 09:00:30.75’ interval: period of time o Example: interval ‘1’ day o Subtracting a date/time/timestamp value from another gives an interval value o Interval values can be added to date/time/timestamp values Can extract values of individual fields from date/time/timestamp Example: extract ( year from r.starttime) Can cast string types to date/time/timestamp Example: cast <string-valued-expression> as date Example: cast <string-valued-expression> as time User-Defined Types create type construct in SQL creates user-defined type create type Dollars as numeric (12,2) final Usage: create table department ( dept_name varchar (20), building varchar (15), budget Dollars ); create domain construct in SQL-92 creates user-defined domain types create domain person_name char (20) not null Types and domains are similar. Domains can have constraints, such as not null , specified on them. create domain degree_level varchar (10) constraint degree_level_test check ( value in (’Bachelors’, ’Masters’, ’Doctorate’)); Domain Constraints Domain constraints are the most elementary form of integrity constraint. They test values inserted in the database, and test queries to ensure that the comparisons make sense. New domains can be created from existing data types Example: create domain Dollars numeric (12, 2) create domain Pounds numeric (12,2) We cannot assign or compare a value of type Dollars to a value of type pounds. o However, we can convert type as below (cast r. A as Pounds )
Large-Object Types Large objects (photos, videos, CAD files, etc.) are stored as a large object : o 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) o clob : character large object -- object is a large collection of character data o When a query returns a large object, a pointer is returned rather than the large object itself. Index Creation create table student ( ID varchar (5), name varchar (20) not null , dept_name varchar (20), tot_cred numeric (3,0) default 0, primary key ( ID )) create index studentID_index on student ( ID ) Indices are data structures used to speed up access to records with specified values for index attributes ◦ Ex: select * from student where ID = ‘12345’ can be executed by using the index to find the required record, without looking at all records of student Create Table Extensions
Schemas, Catalogs, and Environments
The check clause check ( P ) , where P is a predicate Example: ensure that semester is one of fall, winter, spring or summer: create table section ( course_id varchar (8), sec_id varchar (8), semester varchar (6), year numeric (4,0), building varchar (15), room_number varchar (7), time slot id varchar (4), primary key ( course_id , sec_id , semester , year ), check ( semester in (’Fall’, ’Winter’, ’Spring’, ’Summer’)) ); The check clause in SQL-92 permits domains to be restricted: o Use check clause to ensure that an hourly_wage domain allows only values greater than a specified value. create domain hourly_wage numeric(5,2) constraint value_test check ( value > = 4.00) o The domain has a constraint that ensures that the hourly_wage is greater than 4. o The clause constraint value_test is optional; useful to indicate which constraint an update violated. Default Values
Referential Integrity It Ensures that a value that appears in one relation for a given set of attributes also appears for a certain set of attributes in another relation. -- Example: If “Biology” is a department name appearing in one of the tuples in the instructor relation, then there exists a tuple in the department relation for “Biology”. Let A be a set of attributes. Let R and S be two relations that contain attributes A and where A is the primary key of S. A is said to be a foreign key of R if for any values of A appearing in R these values also appear in S. Primary and candidate keys and foreign keys can be specified as part of the SQL create table statement: The primary key clause lists attributes that comprise the primary key. The unique key clause lists attributes that comprise a candidate key. The foreign key clause lists the attributes that comprise the foreign key and the name of the relation referenced by the foreign key. By default, a foreign key references the primary key attributes of the referenced table.
Or
Cascading Actions in Referential Integrity
Integrity Constraint Violation During Transactions Ex: create table person ( ID char (10), name char (40), mother char (10), father char (10), primary key ID, foreign key father references person, foreign key mother references person )
Granting a privilege on a view does not imply granting any privileges on the underlying relations. The grantor of the privilege must already hold the privilege on the specified item (or be the database administrator). Privileges in SQL select: allows read access to relation,or the ability to query using the view o Example: grant users U 1, U 2, and U 3 select authorization on the branch relation: grant select on department to U 1 , U 2 , U 3 insert : the ability to insert tuples update : the ability to update using the SQL update statement delete : the ability to delete tuples. all privileges : used as a short form for all the allowable privileges
Revoking Authorization in SQL: The revoke statement is used to revoke authorization. revoke
All privileges that depend on the privilege being revoked are also revoked. <privilege-list> may be all to revoke all privileges the revokee may hold. If the same privilege was granted twice to the same user by different grantees, the user may retain the privilege after the revocation. Roles create role instructor; grant instructor to Amit; Privileges can be granted to roles: o grant select on takes to instructor ; Roles can be granted to users, as well as to other roles o create role teaching_assistant o grant teaching_assistant to instructor ; Instructor inherits all privileges of teaching_assistant Chain of roles o create role dean ; o grant instructor to dean ; o grant dean to Satoshi; Authorization on Views create view geo_instructor as ( select * from instructor where dept_name = ’Geology’); grant select on geo_instructor to geo_staff Suppose that a geo_staff member issues ◦ select * from geo_instructor ; What if ◦ geo_staff does not have permissions on instructor? ◦ creator of view did not have some permissions on instructor?
Other Authorization Features references privilege to create foreign key ◦ grant reference ( dept_name ) on department to Mariano; transfer of privileges ◦ grant select on department to Amit with grant option ;
Authorization-grant graph ( U 1 ,U 2 ,... ,U 5 are users and DBA refers to the database administrator). Revoking of Privileges
◦ revoke select on department from Amit, Satoshi cascade ; ◦ revoke select on department from Amit, Satoshi restrict ;
Accessing SQL from a Programming Language
from student where tot_cred > :credit_amount END_EXEC The open statement causes the query to be evaluated EXEC SQL open c END_EXEC The fetch statement causes the values of one tuple in the query result to be placed on host language variables. EXEC SQL fetch c into :si , :sn END_EXEC Repeated calls to fetch get successive tuples in the query result A variable called SQLSTATE in the SQL communication area (SQLCA) gets set to ‘02000’ to indicate no more data is available The close statement causes the database system to delete the temporary relation that holds the result of the query. EXEC SQL close c END_EXEC These details vary with language. For example, the Java embedding defines Java iterators to step through result tuples. SQLJ, the Java embedding of SQL, provides a variation, where Java iterators are used in place of cursors. SQLJ associates the results of a query with an iterator, and the next() method of the Java iterator interface can be used to step through the result tuples, just as the preceding examples use fetch on the cursor. Embedded SQL expressions for database modification ( update , insert , and delete ) do not return a result. Thus, they are somewhat simpler to express. A database modification request takes the form EXEC SQL < any valid update, insert, or delete > END-EXEC Embedded SQL allows a host-language program to access the database, but it provides no assistance in presenting results to the user or in generating reports. Dynamic SQL Allows programs to construct and submit SQL queries at run time. -- Example of the use of dynamic SQL from within a C program. **char *** sqlprog = “ update instrucotor set sal = sal * 1. where ID = ?” EXEC SQL prepare dynprog from :sqlprog; char ins [10] = “ 201 101”; EXEC SQL execute dynprog using :instructor; The dynamic SQL program contains a ?, which is a place holder for a value that is provided when the SQL program is executed. ODBC and JDBC API (application-program interface) for a program to interact with a database server Application makes calls to Connect with the database server Send SQL commands to the database server Fetch tuples of result one-by-one into program variables ODBC (Open Database Connectivity) works with C, C++, C#, and Visual Basic JDBC (Java Database Connectivity) works with Java ODBC: Open DataBase Connectivity(ODBC) is a standard for application program to communicate with a database server. It is an Application Program Interface (API) to open a connection with a database, send queries and updates, get back results. Applications such as GUI, spreadsheets, etc. can use ODBC
Each database system supporting ODBC provides a "driver" library that must be linked with the client program. When client program makes an ODBC API call, the code in the library communicates with the server to carry out the requested action, and fetch results. ODBC program first allocates an SQL environment, then a database connection handle. Opens database connection using SQLConnect(). Parameters for SQLConnect: o connection handle, o the server to which to connect o the user identifier, o password Must also specify types of arguments: o SQL_NTS denotes previous argument is a null-terminated string. Good programming requires checking results of every function call for errors; JDBC: JDBC is a Java API for communicating with database systems supporting SQL. It supports a variety of features for querying and updating data, and for retrieving query results JDBC also supports metadata retrieval, such as querying about relations present in the database and the names and types of relation attributes Model for communicating with the database: o Open a connection o Create a “statement” object o Execute queries using the Statement object to send queries and fetch results o Exception mechanism to handle errors Procedural Extensions and Stored Procedures SQL provides a module language that permits definition of procedures in SQL, with if-then-else statements, for and while loops, etc. Stored Procedures Can store procedures in the database then execute them using the call statement permit external applications to operate on the database without knowing about internal details Functions and Procedures: SQL:1999 supports functions and procedures. Functions/procedures can be written in SQL itself, or in an external programming language --Functions are particularly useful with specialized data types such as images and geometric objects Example: functions to check if polygons overlap, or to compare images for similarity -- Some database systems support table-valued functions , which can return a relation as a result SQL:1999 also supports a rich set of imperative constructs, including Loops, if-then-else, assignment constructs. Many databases have proprietary procedural extensions to SQL that differ from SQL: SQL Functions: Define a function that, given the name of a department, returns the count of the number of instructors in that department. create function dept_count (dept_name varchar (20)) returns integer begin declare d_count integer; select count (* ) into d_count from instructor where instructor.dept_name = dept_name return d_count; end Find the department name and budget of all departments with more than 12 instructors. select dept_name, budget from department where dept_count (dept_name ) > 1
Recursion in SQL: SQL:1999 permits recursive view definition Example: find which courses are a prerequisite, whether directly or indirectly, for a specific course with recursive rec_prereq(course_id, prereq_id) as ( select course_id, prereq_id from prereq union select rec_prereq.course_id , prereq.prereq_id, from rec_rereq, prereq where rec_prereq.prereq_id = prereq.course_id )
This example view, rec_prereq, is called the transitive closure of the prereq relation The Power of Recursion Recursive views make it possible to write queries, such as transitive closure queries, that cannot be written without recursion or iteration. Intuition: Without recursion, a non-recursive non-iterative program can perform only a fixed number of joins of prereq with itself o This can give only a fixed number of levels of prereq o Given a fixed non-recursive query, we can construct a database with a greater number of levels of prerequisites on which the query will not work o Alternative: write a procedure to iterate as many times as required Computing transitive closure using iteration, adding successive tuples to rec_prereq o The next we show a prereq relation o Each step of the iterative process constructs an extended version of rec_prereq from its recursive definition. o The final result is called the fixed point of the recursive view definition. Recursive views are required to be monotonic. That is, if we add tuples to prereq the view rec_prereq contains all of the tuples it contained before, plus possibly more Example of Fixed-Point Computation _Recursive queries should not use any of the following constructs as they make the query nonmonotonic.
More on Sub Queries: --SQL:2003 allows subqueries to occur anywhere a value is required provided the subquery returns only one value. This applies to updates as well --SQL:2003 allows subqueries in the from clause to access attributes of other relations in the from clause using the lateral construct: select name , salary , avg_salary from instructor I1 , lateral ( select avg ( salary ) as avg_salary from instructor I where I2. dept_name = I1. dept_name ); When sub queries are written in either select or where clause we can access the attributes of outer query but when the sub query is written in from clause we cannot access. So to facilitate this we use lateral clause.
o employee1 ( ID , name ) o employee2 ( name , street, city, salary ) The next slide shows how we lose information -- we cannot reconstruct the original employee relation -- and so, this is a lossy decomposition. A Lossy Decomposition: It is Loss of information via a bad decomposition. Our decomposition is unable to represent certain important facts of University employees. So we need to avoid this, and it is said to be lossy decomposition and on the other hand if we are able to get by original data then it is called as a lossless decomposition. Example of Lossless join decomposition Decomposition of R = (A, B, C) into R 1 = (A, B) R 2 = (B, C) Functional Dependencies Constraints on the set of legal relations. Require that the value for a certain set of attributes determines uniquely the value for another set of attributes. A functional dependency is a generalization of the notion of a key. Definition: Functional dependency is a relationship that exists when one attribute uniquely determines another attribute. It is a relationship between attributes of a table dependent on each other. It helps in preventing data redundancy and gets to know about bad designs. Functional dependencies are constraints on the set of legal relations. Syntax: A - > B Ex: Account no - > Balance for account table.
Let R be a relation schema and let R and R, then the functional dependency holds on R if and only if for any legal relations r(R), whenever any two tuples t1 and t2 of r agree on the attributes of , they also agree on the attributes of . That is, t1[] = t2 [] t1[ ] = t2 [ ] Example: Consider r (A ,B ) with the following instance of r. A B 1 4 1 5 3 7 On this instance, A B does NOT hold, but B A does hold. K is a superkey for relation schema R if and only if K R K is a candidate key for R if and only if o K R , and o for no K, R Functional dependencies allow us to express constraints that cannot be expressed using superkeys. Consider the schema: inst_dept (ID, name, salary, dept_name, building, budget ). We expect these functional dependencies to hold:
Use of Functional Dependencies: We use functional dependencies to: test relations to see if they are legal under a given set of functional dependencies. -- If a relation r is legal under a set F of functional dependencies, we say that r satisfies F. specify constraints on the set of legal relations -- We say that F holds on R if all legal relations on R satisfy the set of functional dependencies F. Note: A specific instance of a relation schema may satisfy a functional dependency even if the functional dependency does not hold on all legal instances. For example, a specific instance of instructor may, by chance, satisfy name ID. Closure of a Set of Functional Dependencies Given a set F of functional dependencies, there are certain other functional dependencies that are logically implied by F. For example: If A B and B C , then we can infer that A C The set of all functional dependencies logically implied by F is the closure of F. We denote the closure of F by F +. F+ is a superset of F. Partial Dependency: If proper subset of candidate key determines non-prime attribute, it is called partial dependency. Transitive Dependency: When an indirect relationship causes functional dependency it is called Transitive Dependency. If P - > Q and Q - > R is true, then P-> R is a transitive dependency. Trivial Dependency: If a functional dependency (FD) X → Y holds, where Y is a subset of X, then it is called a trivial FD. Trivial FDs always hold. Non-Trivial Dependency: If an FD X → Y holds, where Y is not a subset of X, then it is called a non-trivial FD.
Domain is atomic if its elements are considered to be indivisible units Examples of non-atomic domains: Set of names, composite attributes Identification numbers like CS101 that can be broken up into parts A relational schema R is in first normal form if the domains of all attributes of R are atomic. Non-atomic values complicate storage and encourage redundant storage of data.
Third Normal Form(3NF): A relation schema R is in third normal form (3NF) if for all:
( NOTE : each attribute may be in a different candidate key) If a relation is in BCNF it is in 3NF (since in BCNF one of the first two conditions above must hold). And, Third condition is a minimal relaxation of BCNF to ensure dependency preservation. Boyce-Codd Normal Form(BCNF): A relation schema R is in BCNF with respect to a set F of functional dependencies if for all functional dependencies in F + of the form
2. is a superkey for R Example schema not in BCNF: instr_dept ( ID, name, salary, dept_name, building, budget ) because dept_name building, budget holds on instr_dept, but dept_name is not a super key Decomposing a Schema into BCNF
We decompose R into:
In our example, = dept_name = building, budget and inst_dept is replaced by ( U ) = ( dept_name, building, budget ) ( R - ( - ) ) = ( ID, name, salary, dept_name ) BCNF and Dependency Preservation Constraints, including functional dependencies, are costly to check in practice unless they pertain to only one relation. If it is sufficient to test only those dependencies on each individual relation of a decomposition in order to ensure that all functional dependencies hold, then that decomposition is dependency preserving. Because it is not always possible to achieve both BCNF and dependency preservation, we consider a weaker normal form, known as third normal form. How good is BCNF? There are database schemas in BCNF that do not seem to be sufficiently normalized Ex:1 Consider a relation inst_info (ID, child_name, phone) where an instructor may have more than one phone and can have multiple children There are no non-trivial functional dependencies and therefore the relation is in BCNF Insertion anomalies – i.e., if we add a phone 981- 992 - 3443 to 99999, we need to add two tuples (99999, David, 981 - 992 - 3443) (99999, William, 981- 992 - 3443)