Docsity

SQL Data Types and Schemas, Lecture notes of Database Management Systems (DBMS)

Toggle sidebar
bg1
UNIT III
ADVANCED SQL
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.
SQL Data Types and Schemas
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)
pf3
pf4
pf5
pf8
pf9
pfa
pfd
pfe
pff
pf12
pf13
pf14
pf15
pf16
pf17
pf18
pf19
pf1a
pf1b
pf1c

Partial preview of the text

Download SQL Data Types and Schemas and more Lecture notes Database Management Systems (DBMS) in PDF only on Docsity!

UNIT III

ADVANCED SQL

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.

SQL Data Types and Schemas

Built-in Data Types in SQLdate: 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 Creationcreate 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

Applications often require creation of tables that have the same schema as an existing table. SQL provides a

create table like extension to support this task:

create table temp instructor like instructor ;

The above statement creates a new table temp instructor that has the same schema as instructor

For example the following statement creates a table t1 containing the results of a query.

create table t1 as

( select *

from instructor

where dept_name = ’Music’);

By default, the names and data types of the columns are inferred from the query result. Names can be

explicitly given to the columns by listing the column names after the relation name.

Schemas, Catalogs, and Environments

Early file systems were flat; that is, all files were stored in a single directory. Current file systems, of course,

have a directory (or, synonymously, folder) structure, with files stored within subdirectories. To name a file

uniquely, we must specify the full path name of the file, for example, /users/avi/db-book/chapter3.tex.

Like early file systems, early database systems also had a single name space for all relations. Users had to

coordinate to make sure they did not try to use the same name for different relations. Contemporary database

systems provide a three-level hierarchy for naming relations. The top level of the hierarchy consists of

catalogs , each of which can contain schemas. SQL objects such as relations and views are contained within

a schema.

In order to perform any actions on a database, a user (or a program) must first connect to the database. The

user must provide the user name and usually, a password for verifying the identity of the user. Each user has

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

SQL allows a default value to be specified for an attribute as illustrated by the following create table

statement:

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 ));

The default value of the tot cred attribute is declared to be 0. As a result, when a tuple is inserted into the

student relation, if no value is provided for the tot cred attribute, its value is set to 0. The following insert

statement illustrates how an insertion can omit the value for the tot cred attribute.

insert into student ( ID , name , dept_name ) values (’12789’, ’Newman’, ’Comp. Sci.’);

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.

Example : dept_name varchar (20) references department

Or

create table classroom ( building varchar (15), room number varchar (7), capacity numeric (4,0),

primary key ( building , room number ))

create table department

( dept_name varchar (20), building varchar (15), budget numeric (12,2) check ( budget > 0),

primary key ( dept_name ))

create table course

( course id varchar (8), title varchar (50), dept_name varchar (20), credits numeric (2,0) check ( credits > 0),

primary key ( course id ),

foreign key ( dept_name ) references department )

create table instructor

( ID varchar (5), name varchar (20), not null dept_name varchar (20),

salary numeric (8,2), check ( salary > 29000),

primary key ( ID ),

foreign key ( dept_name ) references department )

create table section

( course id varchar (8), sec id varchar (8),

semester varchar (6), check ( semester in (’Fall’, ’Winter’, ’Spring’, ’Summer’),

year numeric (4,0), check ( year > 1759 and year < 2100)

building varchar (15), room number varchar (7), time slot id varchar (4),

primary key ( course id , sec id , semester , year ),

foreign key ( course id ) references course ,

foreign key ( building , room number ) references classroom )

When a referential-integrity constraint is violated, the normal procedure is to reject the action that caused the

violation (that is, the transaction performing the update action is rolled back). However, a foreign key clause

can specify that if a delete or update action on the referenced relation violates the constraint, then, instead of

rejecting the action, the system must take steps to change the tuple in the referencing relation to restore the

constraint. Consider this definition of an integrity constraint on the relation course :

Cascading Actions in Referential Integrity

create table course

(... foreign key ( dept_name ) references department

on delete cascade

on update cascade ,... );

Because of the clause on delete cascade associated with the foreign-key declaration, if a delete of a tuple in

department results in this referential-integrity constraint being violated, the system does not reject the delete.

Instead, the delete “cascades” to the course relation, deleting the tuple that refers to department that was

deleted. Similarly, the system does not reject an update to a field referenced by the constraint if it violates the

constraint; instead, system updates the field dept_name in the referencing tuples in course to the new value

as well.

SQL also allows the foreign key clause to specify actions other than cascade , if the constraint is violated: The

referencing field (here, dept_name ) can be set to null (by using set null in place of cascade ), or to the default

value for the domain (by using set default ).

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 SQLselect: 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

This grant statement gives users Amit and Satoshi update authorization on the budget attribute of the

department relation:

grant update ( budget ) on department to Amit , Satoshi ;

The user name public refers to all current and future users of the system. Thus, privileges granted to public

are implicitly granted to all current and future users.

Revoking Authorization in SQL: The revoke statement is used to revoke authorization. revoke on from

Example: revoke select on department from Amit , Satoshi ;

revoke update (budget) on department from Amit , Satoshi ;

 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. Rolescreate 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 Viewscreate 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 Featuresreferences 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 ;

The passing of a specific authorization from one user to another can be represented by an authorization

graph. The nodes of this graph are the users. Consider the graph for update authorization on teaches. The

graph includes an edge Ui → Uj if user Ui grants update authorization on teaches to Uj. The root of the graph is

the database administrator.

Authorization-grant graph ( U 1 ,U 2 ,... ,U 5 are users and DBA refers to the database administrator). Revoking of Privileges

Revocation of a privilege from a user/role may cause other users/roles also to lose that privilege. This

behavior is called cascading revocation. In most database systems, cascading is the default behavior.

However, the revoke statement may specify restrict in order to prevent cascading revocation:

◦ revoke select on department from Amit, Satoshi cascade ; ◦ revoke select on department from Amit, Satoshi restrict ;

The following revoke statement revokes only the grant option, rather thanthe actual select privilege:

 revoke grant option for select on department from Amit;

Cascading revocation is inappropriate in many situations. Suppose Satoshi has the role of dean , grants

instructor to Amit, and later the role dean is revoked from Satoshi (perhaps because Satoshi leaves the

university); Amit continues to be employed on the faculty, and should retain the instructor role.

To deal with the above situation, SQL permits a privilege to be granted by a role rather than by a user. SQL

has a notion of the current role associated with a session. By default, the current role associated with a

session is null (except in some special cases). The current role associated with a session can be set by

executing set role role name. The specified role must have been granted to the user; else the set role

statement fails. To grant a privilege with the grantor set to the current role associated with a session, we can

add the clause:

granted by current role to the grant statement, provided the current role is not null.

Accessing SQL from a Programming Language

SQL provides a powerful declarative query language. Writing queries in SQL is usually much easier than

coding the same queries in a general-purpose programming language. However, a database programmer

must have access to a general-purpose programming language for at least two reasons:

1. Not all queries can be expressed in SQL, since SQL does not provide the full expressive power of a

general-purpose language. That is, there exist queries that can be expressed in a language such as

C, Java, or Cobol that cannot be expressed in SQL. To write such queries, we can embed SQL within a

more powerful 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; endFind 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 )

select ∗ from rec_prereq;

This example view, rec_prereq, is called the transitive closure of the prereq relation The Power of RecursionRecursive 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 requiredComputing 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.

  1. Aggregation on the recursive view
  2. Not exists on a subquery that uses the recursive view
  3. Set difference (except) whose right hand side uses the recursive view._ Advanced SQL Features Create table extensions: In SQL 1999 to Create a table with the same schema as an existing table: create table temp_ins like instructor it requires 2 steps 1) creation and 2) store data. In SQL 2003 we have a provision that combines both the steps into one: Create table ti as < sql query> with data

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, AB does NOT hold, but BA does hold.  K is a superkey for relation schema R if and only if KRK is a candidate key for R if and only if o KR , 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:

dept_name  building and

ID  building

but would not expect the following to hold: dept_name  salary

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 nameID. 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 AB and BC , then we can infer that AC 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.

  • We assume all relations are in first normal form Second normal form (2NF): A database is in second normal form if it satisfies the following conditions:  It is in first normal form  All non-prime attributes are fully functional dependent on the primary key An attribute that is not part of any candidate key is known as non-prime attribute. A table that is in 1st normal form and contains only a single key as the primary key is automatically in 2nd normal form. Example : Suppose a school wants to store the data of teachers and the subjects they teach. They create a table that looks like this: Since a teacher can teach more than one subjects, the table can have multiple rows for a same teacher. teacher_id subject teacher_age 111 Maths 38 111 Physics 38 222 Biology 38 333 Physics 40 333 Chemistry 40 Candidate Keys : {teacher_id, subject} Non prime attribute : teacher_age The table is in 1 NF because each attribute has atomic values. However, it is not in 2NF because non prime attribute teacher_age is dependent on teacher_id alone which is a proper subset of candidate key. This violates the rule for 2NF as the rule says “ no non-prime attribute is dependent on the proper subset of any candidate key of the table”. To make the table complies with 2NF we can break it in two tables like this: teacher_details table: teacher_id teacher_age 111 38 222 38 333 40 teacher_subject table: teacher_id subject 111 Maths 111 Physics 222 Biology 333 Physics 333 Chemistry Now the tables comply with Second normal form (2NF).

Third Normal Form(3NF): A relation schema R is in third normal form (3NF) if for all:

   in F + with at least one of the following holds:

1.    is trivial (i.e.,   )

  1.  is a superkey for R

3. Each attribute A in  –  is contained in a candidate key for R.

( 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

where   R and   R , at least one of the following holds:

1.    is trivial (i.e.,   )

2.  is a superkey for R Example schema not in BCNF: instr_dept ( ID, name, salary, dept_name, building, budget ) because dept_namebuilding, budget holds on instr_dept, but dept_name is not a super key Decomposing a Schema into BCNF

Suppose we have a schema R and a non-trivial dependency    causes a violation of BCNF.

We decompose R into:

  1. ( U  )

2. ( R - (  -  ) )

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)