DBMS Module - 2
DBMS Module - 2
Module-2
RELATIONAL MODEL
Q1) Define the following terms as they apply to the relational model of data: domain,
attribute, n-tuple, relation schema, relation state, degree of a relation, relational database
schema, and relational database state.
Domains: A domain D is set of atomic values, atomic means each value in the domain is individual.
A common method for specifying a domain is to specify a data type from which the data values
forming the domain are drawn and also we should specify a name for the domain. Some examples
of domains are.
* Branch_names: The set of names of bank branches of character type.
* Account_Number: The set of 3 digit account numbers.
* Customer_Name: The set of names of persons having account in the bank.
* Balance: The set of values of amount in the account.
These are the logical definitions of domains.
The relational model represents the database as a collection of relations (tables) each of which
is assigned a unique name. Informally each relation resembles a table, where the table consists of
rows and columns. Each row in the table represents a collection of related data values. These values
can be interpreted as facts describing the real world entity. In relational model terminology, a row
is called a tuple and a column header is called an attribute and the table is called a relation. The
data type describing the types of values that can appear in each column is represented by a domain
of possible values.
Relation Schema: A relation schema R, denoted by R(A1,A2,.An), is made up of a relation name R
and a list of attributes A1, A2,….An. Each attribute Ai is the name of role played by some domain D
in the relation schema R.D is called the domain of Ai and is denoted by dom (Ai). A relation schema
is used to describe a relation; R is called name of this relation.
Degree of a Relation: The degree (or arity) of a relation is the number of attributes present in the
relation schema. An example for relation schema for a relation of degree 7 is STUDENT (Name,
Ssn, HomePhone, Address, OfficePhone, Age, GPA), here STUDENT is the name of the relation
which has 7 attributes. The below figure shows an example of STUDENT relation.
A relation (or relation state) r of the relation schema R (A1, A2, ... , An), also denoted by r(R), is
a set of n-tuples. r = {t1, t2, ..., tm}. Each n-tuple t is an ordered list of n values t =<v1, v2,
...,vn>, where each value vi, 1 ≤ i≤ n, is an element of dom (Ai) or is a special NULL value. The
ith value in tuple t, which corresponds to the attribute Ai, is referred to as t[Ai] or [Link].
A relational database schema S is a set of relation schemas S = {R1, R2, ... , Rm} and a set of integrity
constraints IC. A relational database state DB of S is a set of relation states DB= {r1, r2, ... , rm} such
that each ri is a state of Ri and such that the ri relation states satisfy the integrity constraints specified in IC.
Figure below shows a relational database schema.
COMPANY={EMPLOYEE,DEPARTMENT,DEPT_LOCATIONS, PROJECT,WORKS_ON, DEPENDENT}.
The underlined attributes represent primary keys.
Relational database schema S is a set of relation schemas S={R1, R2, , Rm}and a set of integrity
constraints IC.
EMPLOYEE
Name SSN Bdate Address Sex Salary Dno
DEPARTMENT
Dname Dnumber
PROJECT
Pname Pnumber Dnum
WORKS_ON
ESSN PNo Hours
Age, and Gpa. Each tuple in the relation can then be interpreted as a fact or a particular instance of
the assertion. For example, the tuple in the relation asserts the fact that there is a STUDENT whose
Name is Dick Davidson, Ssn is 422-11-2320, Age is 25, and so on.
Q3) List and Explain the Relational Model Notations.
a. A relation schema R of degree n is denoted by R (A1, A2, .................. , An).
b. The letters Q, R, S denotes relation names.
c. The letters q, r, s denote relation states.
d. The letters t, u, v denote tuples.
e. In general, the name of a relation schema such as STUDENT also indicate the current set of tuples
in that relation – the current relation state – whereas STUDENT (Name, Ssn, …) refers only to
the relation schema.
f. An attribute A can be qualified with the relation name R to which it belongs by using the dot
notation R.A – for example, [Link] or [Link]. This is because the same name
may be used for two attributes in different relations. However, all attribute names in a particular
relation must be distinct.
g. An n-tuple t in a relation r( R) is denoted by t = < v1,v2,. . . . . vn>, where vi is the value
corresponding to attribute Ai. The following notation refers to component values of tuples.
i. Both t[Ai] and [Link] (and sometimes t[i]) refer to the value vi int for attribute Ai.
ii. Both t[Au, Aw,…,Az] and t.( Au, Aw,…,Az), where Au, Aw,…,Azis a list of attributes from R, refer
to the subtuple of value <vu, vw, …, vz> from t corresponding to the attributes specified in the list.
Domain Constraints: Domain constraints specify that the value of each attribute is A must be an
atomic value form the domain dom (A) for that attribute.
The data types associated with domains typically include standard numeric data types for integers
and real numbers. Characters, fixed length strings and variable length strings etc.,
Key Constraints: A relation is defined as set of tuples, and all elements of set are distinct. Hence
all the tuples in a relation must also be distinct i,e no two tuples have the same combination of values
for all their attributes.
Q5) Define the following: Superkey, Minimal Superkey, Candidate Key, Primary Key
Superkey: The subset of attributes of a relation schema R with the property that no two tuples in any
relation instance r of R will have the same combination of values for these attributes. Such setof
attributes is called superkey of the relation schema R.
A set of attributes SK of R such that no two tuples in any valid relation in stance r(R) will have the
same value for SK. That is, for any distinct tuples t1 and t2 in r(R), t1[SK]≠t2[SK]. Any such set of
attributes SK is called a superkey of the relation schema R. A superkey SK specifies a uniqueness
constraint that no two distinct tuples in any state r of R can have the same value for SK.
A key k of a relation schema R is a superkey of R with the additional property that removing any
attribute A from K leaves a set of attribute Kꞌ that is not a super key of R any more. Hence, a key
satisfies two constraints.
1. Two distinct tuples in any state of the relation cannot have identical values for (all) the
attributes in the key.
2. It is a minimal superkey – that is, a superkey from which we cannot remove any attributes
and still have the uniqueness constraint in condition 1 hold.
Minimal superkey: A superkey from which we cannot remove any attributes and still have the
uniqueness constraint hold.
For example, consider the relation with
STUDENT (Name, SSN, HomePhone, Address, Age, GPA), here the attribute set {SSN} is key
of STUDENT because no two student tuples can have same value for SSN. Any set of attributes
that include SSN – for example, {SSN, Name, Age } is a superkey however the superkey {SSN,
Dr. Salma Jabeen, ISE, DBIT
Database Management Systems/ B24IS41
Name, Age } is not a keyof STUDENT because removing Name or Age or both from the set still
leaves us with superkey. Hence a minimal superkey is a key of the relation. Here {SSN} is a
minimal superkey or key of relation STUDENT.
Candidate Key: In general a relation schema may have more than one key, i,e relation may have
more one attribute or set of attribute which can distinguish each tuple. In such cases each key is
called candidate key.
Primary Key: The candidate key whose vales are used to identify tuples in the relation is called
Primary Key. In the relation schema the attributes that form the primary key of a relation are
underlined.
Q6) Define Entity Integrity, Referential Integrity, Foreign Keys and Other Constraints.
Entity integrity constraints: The entity integrity constraints state that no primary key value can
be null. This is because the primary key value is used to identify individual tuples in the relation.
Note: Key constraints and entity integrity constraints are specified on individual relations.
Referential integrity constraint: is specified between two relations and is used to maintain
consistency among tuples of two relations.
Referential integrity constraints states that a tuple in one relation that refers to another relation
must refer to an existing tuple in that relation. For example consider,
Here the attribute DNO of EMPLOYEE gives the department number for which employee works;
hence DNO value in every EMPLOYEE tuple must match the Dnumber value of some tuples in the
DEPARTMENT relation.
Foreign Key: A set of attributes FK in relation schema R1 is a foreign key of R1 if it satisfies the
following two rules.
i. The attributes in FK have the same domain as primary key attributes PK of another relation
schema R2; i,e the attributes FK are said to reference or refer to the relation R2. In other words
a value of FK in tuple t1of R1 = the value of PK for some tuples t2 in R2 (t1[FK]= t2[PK], here
the tuple t1 references or refers to the tuple t2)
ii. A value of FK in a tuple t1 of R1 either occurs as a value of PK for some tuples t2 in R2 or is
null.
In the above example DNO is the foreign key which refers to Dnumber in DEPARTMENT relation.
Q7) Discuss the various reasons that lead to the occurrence of NULL values in relations.
OR
Write a note on NULL and three valued logic.
SQL has various rules for dealing with NULL values. NULL is used to represent a missing value, but
that it usually has one of three different interpretations. Consider the following examples to illustrate
each of the meanings of NULL.
1. Unknown value. Aperson‘s date of birth is not known, so it is represented by NULL in the
database.
2. Unavailable or withheld value. A person has a home phone but does not want it to be listed,
so it is withheld and represented as NULL in the database.
3. Not applicable attribute. An attribute LastCollegeDegree would be NULL for a person who
has no college degrees because it does not apply to that person.
It is often not possible to determine which of the meanings is intended; for example, a NULL
for the home phone of a person can have any of the three meanings. Hence, SQL does not
distinguish between the different meanings of NULL.
SQL uses a three-valued logic with values TRUE, FALSE and UNKNOWN instead of the
standard two-valued (Boolean) logic with values TRUE or FALSE.
SQL allows queries that check whether an attribute value is NULL. Rather than using = or <>
to compare an attribute value to NULL, SQL uses the comparison operators IS or IS NOT. This is
because SQL considers each NULL value as being distinct from every other NULL value, so equality
comparison is not appropriate.
Example: Retrieve the names of all employees who do not have supervisors.
SELECT Fname FROM EMPLOYEE
WHERE Super_ssn IS NULL;
Q8) Discuss the different types of update operations on relational database. Give example for
each.
The operations of relational model can be categorized in Retrieval and Updates. There are
three basic modification or update operations on relations.
[Link] 2. Delete [Link]
The Insert Operation: it is used to insert new tuples in to a relation. The insert operation provides
a list of attribute values for a new tuple t that is to be inserted into a relation R. Insert canviolate
any of the four constraints, Domain constraints, key constraint, referential integrity, entity integrity.
In such cases two options are available. The first option is to reject the insertion by specifying why
the insertion was rejected. The second option is to attempt to correct the reason for rejecting the
insertion.
Examples:
.Operation:
Insert<‘Madhu‖,‘G‘,‘Kumar‘,NULL,‘10-9-1998‘,‗Bangalore‘,25000,NULL,4>into EMPLOYEE.
Result: This insertion violates the entity integrity constraint (NULL for the primary key Ssn), So it
is rejected.
.Operation:
Insert<‘Anil‘,‘S‘,‘Kumar‘,1234,‘12-6-1998‘,‗Bangalore‘,20000,NULL,4>intoEMPLOYEE.
Result: This insertion violates the key constraint because another tuple with the same Ssn value
already exists in the EMPLOYEE relation, and so it is rejected.
.Operation:
Insert<‘Kiran‘,‘G‘,‘Shetty‘,2345,‘13-7-1998‘,‗Mysore‘,22000,NULL,5>into EMPLOYEE.
Result: This insertion violates the referential integrity constraint specified on Dno in EMPLOYEE
because no corresponding tuple exists in DEPARTMENT with Dnumber=5.
.Operation:
Insert<‘Santosh‘,‘J‘,‘Kumar‘,3456,‘6-10-1998‘,‗Bangalore‘,25000,NULL,4>into EMPLOYEE.
Result: This insertion satisfies all constraints, so it is acceptable.
The Delete Operation: It is used to delete tuples from relation. The delete operation can violate
only referential integrity, if the tuple being deleted is referenced by the foreign keys from other
tuples in the database. If the deletion operation causes violation, there are three options. The first
option is to reject the deletion. The second option is to attempt to cascade the deletion by deleting
tuples that references the tuples that is being deleted. The third option is to modify the referencing
attribute values that cause the violation.
.Operation:
Delete the WORKS_ON tuple with Essn=1234 and Pno=10.
.Operation:
Delete the EMPLOYEE tuple with Ssn=2345.
Result: This deletion will result in even worse referential integrity violations, because the tuple
involved in referenced by tuples from the EMPLOYEE, DEPARTMENT, WORKS_ON, and
DEPENDENT relations.
The Modify Operation: The Update (or Modify) operation is used to change the values of one or
more attributes in a tuple (or tuples) of some relation R. It is necessary to specify a condition on the
attributes of relation R to select the tuple (tuples) to be modified.
.Operation:
Update the salary of the EMPLOYEE tuple with Ssn=1234 to 29000.
Result: Acceptable.
.Operation:
Update the Dno of the EMPLOYEE tuple with Ssn=1234 to 1.
Result: Acceptable.
.Operation:
Update the Dno of the EMPLOYEE tuple with Ssn=1234 to 7.
Result: Unacceptable, because it violates referential integrity.
.Operation:
Update the Ssn of the EMPLOYEE tuple with Ssn=1234 to 2345.
Result: Unacceptable, because it violates primary key constraint by repeating a value that already
exists as a primary key in another tuple; it violates referential integrity constraints because there are
other relations that refer to the existing value of Ssn.
Modifying an attribute that is neither a primary key nor foreign key usually causes no problem; the
DBMS need only check to confirm the new value is of the correct data type and domain.
(condition) appears as subscript to σ. The argument relation is given in parentheses following the
σ<selection condition> (<relation name> )here the <selection condition> is made up of number of clauses
of the form
<attribute name><relational operator><constant value> or
<attribute name><relational operator><attribute name>
The relational operator may be any one of the operators {=, <, >, <=, >=, !=}
Clauses can be connected by the Boolean Operators AND, OR, NOT.
For example, select tuples for all employees who either works in department 4 and take salary
more than 25,000 or works in department 5 and take over salary more than 30,000
σ(DNO=4 AND Salary>25000) OR (DNO=5 AND Salary>30000) (EMPLOYEE)
πName, Age, Salary (σ DNO = 5 (EMPLOYEE)). Or we can explicitly show the sequence of operations,
giving a name to each intermediate relation as
DEP5_EMPS σ DNO=5(EMPLOYEE)
Note: RUS=SUR
For example, consider.
STUDENT
FN LN
Susan Yao
Ramesh Shah
Johnny Kohler
Barbara Jones
Amy Ford
Jimmy Wang
Ernest Gilbert
INSTRUCTOR
FNAME LNAME
John Smith
Ricardo Browne
Susan Yao
Francis Johnson
Ramesh Shah
INTERSECTION: The result of this operation, denoted byRNS is relation that includes all tuples
that are in common in both R and S.
Note: R ∩ S = S ∩ R
The result of STUDENT ∩ INSTRUCTOR is
FN LN
Susan Yao
Ramesh Shah
Both UNION and INTERSECTION can be treated as an-ary operations applicable to any number
of relations because both are associative operations; that is
RU(SUT) = (RUS)UT and (R N S) N T = R N (S N T)
DEFFERENCE: The result of this operation, denoted by R–S, is a relation that includes all tuples
that are in R but not in S.
Note: R– S≠S–R
The result of INSTRUCTOR–STUDENT is
FN LN
John Smith
Ricardo Browne
Francis Johnson
The INTERSECTION can be expressed in terms of union and set difference as follows:
Relation
College Department
SIT CSE
RVCE TCE
The JOIN operation denoted by ⋈ is used to combine related tuples from two relations into single
tuples. This operation is more important for any relational database with a more than a single relation.
Because allows to process relationships among relations. The general form JOIN operation on two
relations R(A1,A2, An) and S(B1,B2,…Bm) is
R⋈<Join condition>S
The result of join is a relation Q with n+m attributes Q(A1,A2,...An, B1,B2,…Bm) in that order; Q
has one tuple for each combination of tuples – one from R and one from S, whenever the combination
satisfies the join condition.
The join condition is of the form Ai$Bi, where Ai is an attribute of relation R and Bi is an attribute of
relation S and $ is one of the comparison operator {=, <, >, >=, <=, !=}.
Example:
Consider the relations EMPLOYEE(Ename, address, Dnum) and
DEPARTMENT(DeptNum, Dname, Location, Head_name).
DEPT_JOIN ← (EMPLOYEE⋈Dnum=DeptNumANDHead_name=EnameDEPARTMENT
Difference between JOIN and CARTESIAN PRODUCT: In join only the combinations of tuples
satisfying join condition appears in the result; whereas in CARTESIAN PRODUCT all combinations
of tuples are included in the result.
EQUIJOIN: The JOIN, which involves join condition with equality comparison only i,e the only
comparison operator used is = , is called an EQUIJOIN.
Example: Consider the relations
EMPLOYEE(Ename, Address, Dnum) and
DEPARTMENT (DeptNum, Dname, Location).
Then the result of this EQUIJOIN is the relation DEPT_JOIN (Ename, Address, Dnum, Deptnum,
Dname, Location)
This relation will have all the combination tuples which are having Dnum=Deptnum.
NATURAL JOIN: The result of Equijoin will have one or more pair of attributes that have identical
values in every tuple. In NATURAL JOIN this superfluous attributes are removed. Hence NATURAL
JOIN is basically an EQUIJOIN followed by removal of the superfluous (redundant) attributes.
NATURAL JOIN is denoted by *.The NATURAL JOIN requires the two join attributes to have the
same name in both the relations.
The general definition for NATURAL JOIN is Q R*(<list1>,<list2>)S
Example: DEPT_NAT EMPLOYEE * DEPARTMENT.
OUTER JOIN: It is the extension of JOIN operation. The OUTER JOIN operation is used to take the UNION
of tuples from two relations that are not UNION compatible. In normal, join operations (NATURAL or EQUI
JOIN ), only the matching tuples appear in the result, i.e the tuples without related tuples and the tuples with
null in the join attributes are eliminated. In OUTER JOIN all the tuples in relation R and in relation S or both
in the result, whether or not they have matching tuples in the other relation.
There are Three types of OUTER JOIN.
1. LEFTOUTER JOIN: The LEFTOUTER JOIN operation keeps every tuple in first or
left relation R in the result of RS; if no matching tuple is found in S, then attributes of S in
the result are filled or padded with null values. The LEFT OUTER JOIN is denoted by the
symbol
3. FULL OUTER JOIN: This operation is denoted by . FULL OUTER JOIN keeps
all the tuples in both left and right relation when no matching tuples are found, padding them
with null values as needed.
The DIVISION operation, denoted by , is useful for a special kind of query that sometimes
occurs in database applications.
The Division operator is used to find records in one relation that are associated with all
records in another relation. It is commonly used when we want to identify entities that
satisfy certain conditions across multiple related data sets.
The Division operator (R ÷ S) can be applied if:
• The attributes of S are a proper subset of the attributes of R.
• The result will include all attributes of R except those that are in S.
• It returns the tuples from R that are associated with every tuple in S.
1 X X 1
1 Y Y 2
2 X
2 Y
3 Z
Aggregate Functions: The Aggregate functions that are applied on numeric values include SUM,
AVERAGE, MAXIMUM, MINIMUM and COUNT used for counting number of tuples.
Example: For query involving aggregate functions is retrieving the average or total salary of all
employees. We can define a FUNCTION operation using the symbol (pronounced as―Script
F) to specify these types of requests as
Dnum AVERAGESalary(EMPLOYEE).
SQL
Q1)With respect to SQL explain the following with an example.
a)CREATETABLEb)ALTER TABLEc) DROPd)CREATESCHEMA
e)CREATEDOMAINcommand
a) CREATETABLECommand
CREATETABLE: The CREATE TABLE command is used to create a new relation by giving it
a name and specifying attributes and constraints. The general syntax is.
CREATETABLE<table name>(attr1 data type constraint , attr2 data type constraint , ...
attrn data type constraint);
attr1, attr2, attrn are the names of the attributes and then their data types are specified andpossibly
some constraints like the Key, entity integrity and referential integrity constraints are then
specified. For example
CREATETABLEEMPLOYEE
(NAME VARCHAR (15) NOTNULL, SSN CHAR (9) NOTNULL,BDATEDATE,
ADDRESS VARCHAR (30), SEX CHAR, SALARY DECIMAL (10,2),
DNOINTNOTNULL,PRIMARYKEY(SSN),
FOREIGNKEY(DNO)REFERENCESDEPARTMENT(DNUMBER));
Dropping an attribute(column):
WecandropanattributefromthetablebyusingDROPclausealongwithALTERTABLE command, the
general syntax is.
Herethe<attributename>iscolumnnametoberemovedfromtherelation(table).
If CASCADE option is used, then all constraints and views that reference the column are dropped
automatically from the database, along with the column.
IfRESTRICToptionisused,thenspecifiedattribute(column)isdroppedonlyifnoviewsor constraints
references the column.
WecandropanexistingdefaultclausebyusingtheALTERandDROPDEFAULTclausewith ALTER
TABLE command, the general syntax is
ALTERTABLE<tablename>ALTER<attributename>DROP DEFAULT;
Example:ALTERTABLEDEPARTMENTALTERLOCATIONDROP DEFAULT;
Settingnew default clause:
We can set new default clause using the ALTER and SET DEFAULT clause with ALTER TABLE
command. The general syntax is
ALTERTABLE<tablename>ALTER<attributename>SETDEFAULTvalue;
Herethe<attributename>isthenameofthecolumntowhich thespecifiednewvalueistobestored.
Example:ALTERTABLEEMPLOYEEALTERJOBSETDEFAULT’DAILYWAGE‘;
Droppingconstraint:
Generalsyntaxis
Example:ALTERTABLEEMPLOYEEDROPCONSTRAINTEMPFKCASCADE;
a) DROPCommand
Here if the RESTRICT option is chosen the table is dropped only if it is not referenced in any
constraints (such as by foreign key definitions in another relation).
With CASCADE option, all such constraints and views that reference the table are dropped
automatically, along with the table itself.
Note: Schema Evolution (or Schema change) commandsin SQL: Drop, Alter [Link]
commands are used to alter a schema by adding or dropping tables, attributes, constraints and
other schema elements.
The concept of an SQL schema is incorporated in SQL2 in order to group together tables and other
constructs that belong to the same database application. An SQL schema is identified by a
schemaname,and includesan authorizationidentifier toindicatetheuseroraccountwhoowns the
schema, as well as descriptors for each element in the schema. Schema elements include tables,
constraints, views, domains, and other constructs (such as authorization grants) that describe the
schema. A schema is created via the CREATE SCHEMA statement, which can include all the
schema elements‘ definitions. Alternatively, the schema can be assigned a name and authorization
identifier, and the elements can be defined later.
For example, the following statement creates a schema called COMPANY, owned by the user
with authorization identifier ‘Jsmith ‘. Note that each statement in SQL ends with a semicolon.
CREATESCHEMACOMPANYAUTHORIZATION‘Jsmith‘;
which the CREATE TABLE statements are executed. Alternatively, we can explicitly attach the
schema name to the relation name, separated bya period. For example, by writing
[Link]...
a) CREATEDOMAIN Command
Itispossibletospecifythedatatypeofeachattributedirectly,like CREATE
TABLE EMPLOYEE (Ssn CHAR (9) ….);
Or alternatively, a domain can be declared, and the domain name used with the attribute
specification. This makes it easier to change the data type for a domain that is used by numerous
attributes in a schema, and improves schema readability.
Forexample,wecancreateadomain SSN_TYPEbythefollowingstatement:
CREATEDOMAINSSN_TYPE ASCHAR(9);
We canuse SSN_TYPE in place of CHAR(9) asused in the above example, for the attributesSsn
and Super_ssn of EMPLOYEE, Mgr_ssn of DEPARTMENT, Essn of WORKS_ON, and Essn of
[Link] can alsohave an optionaldefault specification via a DEFAULT clause.
Q2)Explainthedifferent datatypesinSQL?
The data types available for attributes include numeric, character-string, bit-string, Boolean, date
and time, timestamp.
Numeric: Numeric data types include integer numbers of various sizes (INTEGER or INT, and
SMALLINT) and floating-point (real) numbers of various precision (FLOAT or REAL, and
DOUBLE PRECISION). Formatted numbers can be declared by using DECIMAL(i, j)—or
DEC(i, j) or NUMERIC(i, j)—where i, the precision, is the total number of decimal digits and j,
the scale, is the number of digits after the decimal point. The default for scale is zero, and the
default for precision is implementation-defined.
it is case sensitive. For fixed length strings, a shorter string is padded with blank characters to the
right. For example, if the value ‘Smith‘ is for an attribute of type CHAR(10), it is padded withfive
blank characters to become ‘Smith‘if needed. Padded blanks are generally ignored whenstrings are
compared. For comparison purposes, strings are considered ordered in alphabetic order; if a string
str1appears before another string str2 in alphabetic order, then str1isconsideredto be less than str2.
There is also a concatenation operator denoted by|| (double vertical bar) that can concatenate two
strings in SQL. For example, ‘abc‘||’XYZ‘ results in a single string ‘abcXYZ‘. Another variable-
length string data type called CHARACTER LARGE OBJECT or CLOB is also available to
specify columns that have large text values, such as documents. The CLOB maximum length can
be specified in kilobytes (K), megabytes (M), or gigabytes (G). For example, CLOB (20M)
specifies a maximum length of 20 megabytes.
Bit-string: Bit-string data types are either of fixed length n-BIT(n) or varying length-BIT
VARYING(n), where n is the maximum number of bits. The default for n, the length of a
character stringor bitstring,is1. Literalbitstringsare placed between single quotesbutpreceded by a
B to distinguish them from character strings.
Forexample: B’10101‘.
Another variable-length bit string data type called BINARY LARGE OBJECT or BLOB is also
available to specify columns that have large binary values, such as images. The maximum length
of a BLOB can be specified in kilobits (K), megabits (M), or gigabits (G).
Forexample,BLOB(30G)specifiesamaximumlengthof30gigabits.
Boolean: ABoolean data type hasthe traditionalvalues ofTRUE or FALSE. In SQL, because of the
presence ofNULL values,a three-valued logic isused,soa third possible value for a Boolean data
type is UNKNOWN.
DATE and TIME: The DATE data type has ten positions, and its components are YEAR,
MONTH, and DAY in the form YYYY-MM-DD. The TIME data type has at least eightpositions,
with the components HOUR, MINUTE, and SECOND in the form HH:MM:SS.
Literal values are represented bysingle-quoted strings preceded bythe keyword DATE or TIME; for example, DATE
AdditionaldatatypesusedinSQLareasfollows:
Timestamp: A timestamp data type (TIMESTAMP) includes the DATE and TIME fields, plus a
minimum of six positions for decimal fractions of seconds and an optional WITH TIME
ZONEqualifier. Literal values are represented by single quoted strings preceded by the keyword
TIMESTAMP, with a blank space between data and time.
Forexample,TIMESTAMP’2008-09-2709:12:47.648302‘.
INTERVAL: Another data type related to DATE, TIME, and TIMESTAMP is the INTERVAL
data type. This specifies an interval—a relative value that can be used toincrement or decrement
an absolute value of a date, time, or timestamp. Intervals are qualified to be either
YEAR/MONTH intervals or DAY/TIME intervals.
Q3) Explainthedifferent constraintsanddefault clause inSQL.
Constraints: After the attributes specifications the following constraints can be specified on a
table: Not null, Primary key, Foreign Key, Unique.
NOT NULL: As the SQL allows NULL as attribute value, NOT NULL constraint may be
specified if NULL is not permitted for a particular attribute. The NOT NULL constraint should
always be specified for the primary key attributes of each relation and for any other attributes
whose values are not to be NULL.
Another type of constraint can restrict attribute or domain values using the CHECK clause
following an attribute or domain definition.
For example, suppose that department numbers are restricted to integer numbers between 1 and20;
then, we can change the attribute declaration of Dnumber in the DEPARTMENT table to the
following:
DnumberINTNOTNULLCHECK(Dnumber>0 ANDDnumber<21);
TheCHECKclausecanalsobeusedinconjunctionwiththeCREATEDOMAINstatement. For
example, we can write the following statement:
CREATEDOMAIND_NUM ASINTEGER
CHECK (D_NUM>0ANDD_NUM<21);
SpecifyingConstraintsonTuplesUsingCHECK
In addition to key and referential integrity constraints, which are specified by special key words,
other table constraints can be specified through additional CHECK clauses at the end of
aCREATE TABLE statement. These can be called tuple-based constraints because theyapply to
each tuple individually and are checked whenever a tuple is inserted or modified.
For example, suppose that the DEPARTMENT table had an additional attributeDept_create_date,
which stores the date when thedepartment [Link] we could add the following CHECK
clause at the end of the CREATE TABLE statement for the DEPARTMENT table to make sure
that a manager‘s start date is later than the department creation date.
CHECK(Dept_create_date<=Mgr_start_date);
Default clause: It is also possible to define a default value for an attribute by appending the clause
DEFAULT <value> to an attribute definition. DEFAULT clause includes the specified value in
anynew tuple if an explicit value is not provided for that attribute. For example:
CREATE TABLE DEPARTMENT(DNAME VARCHAR(15) NOTNULL,DNUMBERINT
NOT NULL, DLOCATION VARCHAR(15) NOT NULL DEFAULT ‘MYSURU’);
Heredname,dumber,dlocationcannottakenullvaluesanddefaultvaluefordlocationis MYSURU.
PRIMARY KEY: This clause specifies one or more attributes that make up the primarykeyof a
relation.
FOREIGNKEY:Thisclause isusedtospecifyreferentialintegrity.
CONSTRAINT: This keyword is used to give a name to a constraint. The names of all constraints
within a particular schema must be unique. A constraint name is used to identify a particular
constraint in case the constraint must be dropped and replaced with another constraint. Example
CREATETABLEEMPLOYEE(,DNOINTNOTNULLDEFAULT1,CONSTRAINTEMPK
PRIMARY KEY(SSN), CONSTRAINT EMPFK FOREIGNKEY(DNO) REFERENCES
DEPARTMENT(DNUMBER)ON DELETE SET NULL);
Q4) Explain Update statements [Link] Insert, Delete and Update statement
inSQL.
In SQL three commands can be used to modify the database, they are INSERT ,DELETE ,and
UPDATE.
INSERT Command:
The insert command can be used to add data in to table. INSERT command can be used in
different forms as shown below.
The simplest form is:
INSERTINTO<table name>VALUES(val1,val2,val3,…,valn).
This form can be used to add a single tuple (row) toa relation. Here the values should be listed in
the same order in which the corresponding attributes were specified in the CREATE TABLE
command. For example:
INSERTINTOEMPLOYEEVALUES(‘Mohan‘,’12345‘,’1stmain‘,5000,’Physics‘,‘Lecturer‘);
The second form is:
INSERTINTO<tablename>(attr1,attr2,...,attrn)VALUES(val1,val2,val3,...valn);
This form allows the user to specify explicit attribute names that correspond to the values in the
INSERT command. In this case, attributes with NULL or DEFAULT values are left out. For
example:
INSERTINTOEMPLOYEE(FNAME,EMPNO)VALUES(‘Mohan‘,’123‘);
The third form is:
INSERTINTO<table name>[(attr1,attr2, ........ attrn)]SELECT<attributes>FROM<tables>
WHERE<condition>;
This form of INSERT command insert smultiple tuples into the relation based on result of the query.
For example:
INSERTINTODEPOSITSELECTBRANCH_NAME,LOAN_NUMBER,CUST_NAME
FROMBORROWWHEREBRANCH_NAME=‘Bengaluru‘;
The DELETE Command:
The DELETE command removes tuples (rows) from a table. This command includes WHERE
clause to select the tuples to be deleted. Depending on the number of tuples selected by the
condition in the WHERE clause 0, 1, 2, or several tuples can be deleted by single DELETE
command. If there is no WHERE clause in the DELETE commands, then all tuples (rows) in the
table are deleted. The general syntax is:
DELETEFROM<tablename>WHERE<condition>;
Forexample:DELETEFROMEMPLOYEEWHERESALARY=2000;
TheUPDATECommand:
The UPDATE command can be used to modify attribute values of one ormore selected [Link]
general syntax for using the UPDATE command is:
UPDATE<tablename>SETattr1=value,attr2=value,…,WHERE<condition>; The
SET clause specifies the attributes to be modified and their new values.
TheWHEREclauseselectsthetuplestobemodifiedfromasinglerelation(table). For
example: UPDATE EMPLOYEE SET SALARY = SALARY * 1.1WHERE
DNOIN(SELECTDNUMBERFROMDEPARTMENTWHERE
DNAME=’Research‘);
The above command updates the salary of all Research department employees by 10%.
Note:UpdatingtheprimaryKeyvaluesmaypropagatetotheforeignKeyvaluesoftuplesin other relation.
Q5) Give the complete syntax of SELECT statement in SQL and discuss all the clauses
with examples.
ThebasicstructureofanSQL expressionconsistsofsixclauses:SELECT,FROM,WHERE, GROUP
BY, HAVING, and ORDER BY has the following syntax.
SELECT<attributeandfunction
list>FROM< table list>
[WHERE <condition>]
[GROUPBY<groupingattribute(s)>]
[HAVING <group condition>]
[ORDERBY<attributelist>][ASC|DESC];
SELECT:This clause corresponds to the projection operation of the relational algebra. It is used
to list the attributes desired in the result of a query.
FROM:[Link] lists the
relations to be scanned in the evaluation of the expression.
WHERE: This clause corresponds to the selection predicate (condition) of the relational algebra. It consists of conditions
involving attributes of the relations that appears in the from clause.
[Link],usethekeyword DESC.
Forexample:RetrievetheSSNandNameofemployeesarranged indescendingorderbyname.
SELECT Ssn, Fname
FROM EMPLOYEE
ORDERBYFnameDESC;
Forexample,considerthebelow query.
[Link],[Link],[Link]
EMPLOYEEE,DEPARTMENTD
[Link]=’Research’[Link]=[Link];
Forexample:SELECTENAME, DNAMEFROMEMPLOYEE,DEPARTMENT;
Useof‘*’
To retrieve all the attribute values of the selected tuples, it is not required to list the attribute
names explicitly in SQL, instead we can just specify an asterisk (*) which stands for all the
attributes. For example:
SELECT *FROM EMPLOYEE, DEPARTMENT
WHEREDNAME=‘Research’ANDDNO=DNUMBER;
Q9)Explain why SQL does not automatically eliminate duplicate tuples in query results.
[Link] results of
queries, for the following reasons.
. Duplicate elimination is an expensive operation. One wayto implement it is to sort the tuples
first and then eliminate duplicates.
.Theusermaywantto seeduplicatetuplesin theresultofquery.
. When aggregate function is applied to tuples, in most cases the user do not want to eliminate
duplicates.
Q10)Explain the use of DISTINCT Key word in SQL.
ThekeywordDISTINCTcanbeusedinSELECTclauseto eliminateduplicatetuplesfrom theresult
of the queryi.e., only the distinct tuples remain in the result.
Forexample:Retrievethedistinctsalaryvaluesof employees.
SELECTDISTINCTSALARYFROMEMPLOYEE;