1
Subject: RDBMS
Semester:5th
Branch: Computer Engg.
1. Give brief answers to the following questions. (2 marks each)
UNIT-1
1. Define DBMS.
A method for structuring data in the form of sets of records or tuples so that relations
between different entities and attributes can be used for data access and transformation is
called DBMS.
2. Define RDBMS.
A database system made up of files with data elements in two dimensional array (rows
and columns). This database management system has the capability to recombine data
elements to form different relations resulting in a great flexibility of data usage.
3. Define Tuple.
A row that contains various data about an entity is called tuple.
4. Define Relation.
A relation is thought of as table of values, each row in the table represents a collection of
related data values. In the relational model, each row in the table represents a fact that
typically corresponds to a real world entity or relationship. The table name and column
names are used to help in interpreting the meaning of the values in each row.
5. What is an attribute?
A column in the table is called attribute.
6. Define cardinality.
The number of tuples in a relation is called cardinality.
7. Define degree of relation.
The degree of relation is the number of attributes in a relation.
8. Define 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 a 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 the name of this
relation.
9. Define domain of relation.
The data type describing the types of values that can appear in each column is called a
domain.
10. Define key.
The value of a key attribute can be used to identify uniquely each tuple in the relation A
key K is a superkey with the additional property that removal of any attribute from K will
cause K not to be a superkey any more. The difference between a key and a superkey is
that a key has to be minimal
11. Define Foreign Key.
A set of attributes in a relation whose value must also be present in another relation as set
of attributes for establishing a relation between the two is called foreign key.
12. Define Primary Key.
The value of a key attribute can be used to identify uniquely each tuple in the relation. It
is common to designate one of the candidate keys as the primary key of the relation.
13. Define candidate key.
The minimal superkey for which there is no proper subset of another super key for a
relation is called candidate key.
14. Define superkey.
A superkey SK specifies a uniqueness constraint that no two distinct tuples in a state r of
R can have the same value for SK. Every relation has at least one default superkey—the
set of all its attributes.
15. Define secondary key or alternate key.
An alternative key or secondary key that can be used, as the name suggests, as a
secondary or alternative key to the primary key.
16. Define relational constraints.
The various restrictions on data that can be specified on a relational database schema are
called relational constraints. These include domain constraints, key constraints, entity
integrity and referential integrity constraints.
17. Define relational Database.
2
A relational database is a collection of related information stored in two dimensional
tables.
18. What are Components of database?
Attributes
Tuples
Domains of attributes
Relations and their schemes
Relations representation
Keys
Relationship
Relational operations
Integrity rules
19. Define entity integrity.
The entity integrity constraint states that no primary key value can be null. This is
because the primary key value is used to identify individual tuples in a relation; having
null values for the primary key implies that we cannot identify some tuples. For example,
if two or more tuples had null for their primary keys, we might not be able to distinguish
them.
20. Define referential Integrity.
The conditions for a foreign key, given below, specify a referential integrity constraint
between the two relation schemas R1 and R2. A set of attributes FK in relation schema
R1 is a foreign key of R1 that references relation R2 if it satisfies the following two
rules:
1. The attributes in FK have the same domain(s) as the primary key attributes PK of R2;
the attributes FK are said to reference or refer to the relation R2.
2. A value of FK in a tuple t1 of the current state r1(R1) either occurs as a value of PK for
some tuple t2 in the current state r2(R2) or is null. In the former case, we have t1[FK] =
t2[PK], and we say that the tuple t1 references or refers to the tuple t2. R1 is called the
referencing relation and R2 is the referenced relation.
UNIT-II
21. Define normalization.
Normalization of data can be defined as a process of analyzing the given relation
schemas based on their FDs and primary keys to achieve the desirable properties of
(1) minimizing redundancy and
(2) minimizing the insertion, deletion, and update anomalies
22. What is decomposition?
The process of converting one relation into more than one relations is called
decomposition.
23. Define functional dependency.
A functional dependency is a constraint between two sets of attributes from the database.
24. Define Trivial & Non trivial Functional Dependency.
A FD is trivial if and only if RHS is subset of LHS
A FD is non trivial if and only if RHS is subset of LHS
25. Define closure of a set of dependencies.
A set of dependencies is called called the closure of F if it is logically implied by F and
written as F +
26. Define closure of a set of attributes.
If A is a set of attributes of relation R and S is a set of Functioal Dependencies that hold
for realtion R then A + is known as closure of a set of attributes A under S.
27. Define 1st normal form.
It states that the domain of an attribute must include only atomic (simple, indivisible)
values and that the value of any attribute in a tuple must be a single value from the
domain of that attribute. Hence, 1NF disallows having a set of values, a tuple of values,
or a combination of both as an attribute value for a single tuple. In other words, 1NF
disallows "relations within relations" or "relations as attributes of tuples." The only
attribute values permitted by 1NF are single atomic (or indivisible) values.
28. Define 2nd normal form.
Second normal form (2NF) is based on the concept of full functional dependency. A
functional dependency X -> Y is a full functional dependency if removal of any
attribute A from X means that the dependency does not hold any more. A functional
3
dependency X -> Y is a partial dependency if some attribute A from X can be removed
and the dependency still holds.
A relation schema R is in 2NF if every nonprime attribute A in R is fully functionally
dependent on the primary key of R.
29. Define 3rd normal form.
Third normal form (3NF) is based on the concept of transitive dependency.
A functional dependency X -> Y in a relation schema R is a transitive dependency if
there is a set of attributes Z that is neither a candidate key nor a subset of any key of R,
and both X -> Z and Z ->Y hold.
According to Codd’s original definition, a relation schema R is in 3NF if it satisfies 2NF
and no nonprime attribute of R is transitively dependent on the primary key.
30. Define BCNF.
Boyce-Codd normal form (BCNF) was proposed as a simpler form of 3NF, but it was
found to be stricter than 3NF, because every relation in BCNF is also in 3NF; however, a
relation in 3NF is not necessarily in BCNF.
The formal definition of BCNF differs slightly from the definition of 3NF.
A relation schema R is in BCNF if whenever a nontrivial functional dependency X -> A
holds in R, then X is a superkey of R. The only difference between the definitions of
BCNF and 3NF is that condition (b) of 3NF, which allows A to be prime, is absent from
BCNF.
31. Define 4th Normal Form
Definition of fourth normal form (4NF), which is violated when a relation has
undesirable multivalued dependencies, and hence can be used to identify and decompose
such relations.
A relation schema R is in 4NF with respect to a set of dependencies F (that includes
functional dependencies and multivalued dependencies) if, for every nontrivial
multivalued dependency X Y in , X is a superkey for R.
32. Define 5th Normal Form.
Fifth normal form is also called project-join normal form. A relation schema R is in fifth
normal form (5NF) (or project-join normal form (PJNF)) with respect to a set F of
functional, multivalued, and join dependencies if, for every nontrivial join dependency
JD in (that is, implied by F), every is a superkey of R.
UNIT-III
33. Define query language.
Query language is the language in which user requests information from database
34. Define procedural language.
In procedural language the user instructs the system to perform a sequence of operations
on the database to compute the desired result.
35. Define nonprocedural language
In non procedural language the user describes the desired information without giving a
specific procedure for obtaining that information.
36. Define relational Algebra.
Relational algebra which is part of the relational model that provides a more procedural
way for specifying queries. It consists of a set of operations that take one or two relations
as input and produces a new relation as their output.
37. Define relational calculus.
Relational calculus consists of two calculi, the tuple relational calculus and the domain
relational calculus, that are part of the relational model for databases and provide a
declarative way to specify database queries.
38. Define tuple calculus.
Tuple calculus is a calculus that was introduced by Edgar F. Codd as part of the
relational model, in order to provide a declarative database-query language for this data
model. It formed the inspiration for the database-query languages QUEL and SQL, of
which the latter, although far less faithful to the original relational model and calculus, is
now the de-facto-standard database-query language; a dialect of SQL is used by nearly
every relational-database-management system.
39. Define free variable
A tuple variable is said to be a free variable unless it is quantified by a or a .
40. Define bound variable
A tuple variable is said to be a bound variable when it is quantified by a or a .
4
41. Define domain calculus.
Domain relational calculus (DRC) is a calculus that was introduced as a declarative
database query language for the relational data model.
In DRC, queries have the form:
where each Xi is either a domain variable or constant, and
denotes a DRC formula. The result of the query is the set of tuples Xi to Xn which makes
the DRC formula true.
42. Differentiate between tuple calculus and domain calculus
Tuple calculus is a calculus that was introduced by Edgar F. Codd as part of the
relational model, in order to provide a declarative database-query language for this data
model. It formed the inspiration for the database-query languages QUEL and SQL, of
which the latter, although far less faithful to the original relational model and calculus, is
now the de-facto-standard database-query language; a dialect of SQL is used by nearly
every relational-database-management system.
In computer science, Domain relational calculus (DRC) is a calculus that was
introduced as a declarative database query language for the relational data model.
In DRC, queries have the form:
where each Xi is either a domain variable or constant, and
denotes a DRC formula. The result of the query is the set of tuples Xi to Xn which makes
the DRC formula true.
This language uses the same operators as tuple calculus, the logical connectives ∧ (and),
∨ (or) and ¬ (not). The existential quantifier (∃) and the universal quantifier (∀) can be
used to bind the variables.
43. Define fundamental operations of relational algebra.
Six primitive operators of Codd's algebra are the selection, the projection, the Cartesian
product (also called the cross product or cross join), the set union, and the set difference
and rename.
44. Define select operation.
A generalized selection is a unary operation written as
where
is a
propositional formula that consists of atoms as allowed in the normal selection and the
logical operators (and), (or) and (negation). This selection selects all those tuples
in R for which
holds.
45. Define project operation.
A projection is a unary operation written as
where
is a set of
attribute names. The result of such projection is defined as the set that is obtained when
all tuples in R are restricted to the set
.
46. Define Set difference operation.
Set difference finds tuples in one relation but not in other.
It is denoted as ( –)
Example:
Find the names of all customers who have an account but not a loan.
Code:
Π customer-name (Depositor) - Π customer-name (Borrower)
47. Define Cartesian product operation.
For the Cartesian product to be defined, the two relations involved must have disjoint
headers—that is, they must not have a common attribute name.
In addition, the Cartesian product is defined differently from the one in set theory in the
sense that tuples are considered to be "shallow" for the purposes of the operation. That is,
the Cartesian product of a set of n-tuples with a set of m-tuples yields a set of "flattened"
(n + m)-tuples (whereas basic set theory would have prescribed a set of 2-tuples, each
containing an n-tuple and an m-tuple). More formally, R × S is defined as follows:
R × S = {(r1, r2, ..., rn, s1, s2, ..., sm) | (r1, r2, ..., rn) ∈ R, (s1, s2, ..., sm) ∈ S}
The cardinality of the Cartesian product is the product of the cardinalities of its factors,
i.e., |R × S| = |R| × |S|.
48. Define union operation.
5
The union operation is used when we need some attributes that appear in either or both of
the two relations.It is denoted as U.
Example:
Borrower (customer-name, loan-number)
Depositor (customer-name, account-number)
Customer (customer-name, street-number, customer-city)
List all the customers who have either an account or a loan or both
Code:
Π customer-name (Borrower) U Π customer-name (Depositor)
For a union operation r U s to be valid, two conditions must hold:
The relation r and s must be of the same arity, i.e. they must have the same number of
attributes.
The domains of the ith attribute of r and the ith attribute of s must be the same for all i.
49. Define rename operation.
The rename operation is used to rename.It is denoted as ρ.
E : relational algebra expression
ρ x (E): returns the result of expression E under the name x.
ρ x (A1, A2, A3… An) (E): returns the result of expression E under the name x with
attributes renamed to A1, A2, A3… An.
50. Give formal definition of relation algebra
A basic expression consists of either
a. A relation in the database.
b. A constant relation.
General expressions are formed out of smaller subexpressions using
c.
select (p a predicate)
d.
project (s a list of attributes)
e.
rename (x a relation name)
f.
union
g.
set difference
h. E1*E2 Cartesian Product
51. Give formal definition of tuple calculus.
1. A tuple relational calculus expression is of the form
where is a formula.
Several tuple variables may appear in a formula.
2. A tuple variable is said to be a free variable unless it is quantified by a or a . Then it
is said to be a bound variable.
3. A formula is built of atoms. An atom is one of the following forms:
o
, where is a tuple variable, and r is a relation ( is not allowed).
o
, where and are tuple variables, and and are attributes, and is a
comparison operator (
).
o
, where is a constant in the domain of attribute .
4. Formulae are built up from atoms using the following rules:
o An atom is a formula.
o If is a formula, then so are
and
.
o If
and are formulae, then so are
,
and
.
o If
is a formula containing a free tuple variable , then
are formulae also.
5. Note some equivalences:
o
o
o
6
52. Give formal definition of domain calculus.
1. Domain variables take on values from an attribute's domain, rather than values for an
entire tuple.
Formal Definitions
1. An expression is of the form
where the
represent domain variables, and
is a formula.
2. An atom in the domain relational calculus is of the following forms
o
where is a relation on attributes, and
, are
domain variables or constants.
o
, where and are domain variables, and is a comparison operator.
o
, where c is a constant.
3. Formulae are built up from atoms using the following rules:
o An atom is a formula.
o If is a formula, then so are
and
.
o If
and are formulae, then so are
,
and
.
o If
is a formula where x is a domain variable, then so are
and
.
53. What are additional operations of relational algebra.
Additional operations are defined in terms of the fundamental operations. They do not
add power to the algebra, but are useful to simplify common queries. The Set Intersection
Operation , The Natural Join Operation , The Division Operation , The Assignment
Operation
54. Define natural join.
Natural join ( ) is a binary operator that is written as (R
S) where R and S are
relations. The result of the natural join is the set of all combinations of tuples in R and S
that are equal on their common attribute names.
55. Define join
A SQL join clause combines records from two or more tables in a relational database. It
creates a set that can be saved as a table or used as it is. A JOIN is a means for
combining fields from two tables (or more) by using values common to each.
56. Define intersection operation.
Set intersection is denoted by
both of its argument relations.
, and returns a relation that contains tuples that are in
It does not add any power as
To find all customers having both a loan and an account at the SFU branch, we write
57. Define division operation.
The division is a binary operation that is written as R ÷ S. The result consists of the
restrictions of tuples in R to the attribute names unique to R, i.e., in the header of R but
not in the header of S, for which it holds that all their combinations with tuples in S are
present in R
58. Define assignment operation.
7
Sometimes it is useful to be able to write a relational algebra expression in parts using a
temporary relation variable (as we did with and in the division example).The
assignment operation, denoted , works like assignment in a programming language.
We could rewrite our division definition as
No extra relation is added to the database, but the relation variable created can be used in
subsequent expressions. Assignment to a permanent relation would constitute a
modification to the database.
UNIT-IV
59. What are sql’s basic objects?
A database object in a relational database is a data structure used to either store or
reference data. The most common object that most people interact with is the table. Other
objects are indexes, stored procedures, sequences, views and many more.
60. What are aggregate functions?
Computing various functions on a column, like the summing up its elements, is also not
possible using the relational algebra introduced so far. There are five aggregate functions
that are included with most relational database systems. These operations are Sum,
Count, Average, Maximum and Minimum.
61. What are scalar functions?
Single row or Scalar functions return a value for every row that is processed in a query.
e.g.ABS(x),CEIL(x),FLOOR(x),LOWER(String_value)etc.
UNIT-V
62. Write syntax of create table and drop table commands.
The Syntax for the CREATE TABLE Statement is:
CREATE TABLE table_name
(column_name1 datatype,
column_name2 datatype,
... column_nameN datatype
);
table_name - is the name of the table.
column_name1, column_name2.... - is the name of the columns
datatype - is the datatype for the column like char, date, number etc.
63. Insert and update are _ commands.
Data Manipulation Language
64. Define DCL
A data control language (DCL) is a syntax similar to a computer programming
language used to control access to data stored in a database. In particular, it is a
component of Structured Query Language (SQL). Examples of DCL commands
include: GRANT to allow specified users to perform specified tasks.
65. Define insert statement.
An INSERT statement adds new rows to an existing table.
When you use the INSERT statement to add a row of data to a table, the data inserted
must be valid for the data type and size of each column of the table.
The general syntax of the INSERT command looks like the following. Note that the list
of values has to be in the same order as the columns of the table.
INSERT INTO table_name VALUES
(list_of_values_for_new_row);
8
66. Define update statement.
An UPDATE statement modifies the values of a set of existing table rows.
When you use the UPDATE statement to update data in a row of a table, the new data
must be valid for the data type and size of each column of the table.
The general syntax of the UPDATE command looks like the following. Note that the
columns that are altered must be identified, and the matching conditions must be met.
UPDATE table_name
SET column_name = value;
WHERE condition;
To update information in a row that is missing data, the missing data column should be
specified.
67. Define delete Statement.
A DELETE statement removes existing rows from a table.
Using the DELETE statement, you can delete specific rows in a table. If you want to
delete all the rows in the table, the empty table still exists. If you want to remove the
entire table from the database, use the DROP TABLE statement.
Note that if you accidentally delete rows, you can restore the rows with the ROLLBACK
statement.
68. Define query
A query includes a list of columns to include in the final result, immediately following
the SELECT keyword.
69. What are sub queries?
In Oracle, a subquery is a query within a query. You can create subqueries within your
SQL statements. These subqueries can reside in the WHERE clause, the FROM clause, or
the SELECT clause.
70. What are different clauses of select statement
SELECT is the most complex statement in SQL, with optional keywords and clauses that
include:
The FROM clause, which indicates the table(s) to retrieve data from. The FROM clause
can include optional JOIN subclauses to specify the rules for joining tables.
The WHERE clause includes a comparison predicate, which restricts the rows returned
by the query. The WHERE clause eliminates all rows from the result set where the
comparison predicate does not evaluate to True.
The GROUP BY clause is used to project rows having common values into a smaller set
of rows. GROUP BY is often used in conjunction with SQL aggregation functions or to
eliminate duplicate rows from a result set. The WHERE clause is applied before the
GROUP BY clause.
The HAVING clause includes a predicate used to filter rows resulting from the GROUP
BY clause. Because it acts on the results of the GROUP BY clause, aggregation functions
can be used in the HAVING clause predicate.
The ORDER BY clause identifies which columns to use to sort the resulting data, and in
which direction to sort them (ascending or descending). Without an ORDER BY clause,
the order of rows returned by an SQL query is undefined.
71. What are correlated subquery?
Oracle performs a correlated subquery when a nested subquery references a column
from a table referred to a parent statement any number of levels above the subquery. The
parent statement can be a SELECT, UPDATE, or DELETE statement in which the
subquery is nested. A correlated subquery is evaluated once for each row processed by
9
the parent statement. Oracle resolves unqualified columns in the subquery by looking in
the tables named in the subquery and then in the tables named in the parent statement.
A correlated subquery answers a multiple-part question whose answer depends on the
value in each row processed by the parent statement. For example, you can use a
correlated subquery to determine which employees earn more than the average salaries
for their departments. In this case, the correlated subquery specifically computes the
average salary for each department.
72. What are derived tables.
A "derived table" is essentially a statement-local temporary table created by means of a
subquery in the FROM clause of a SQL SELECT statement. It exists only in memory and
behaves like a standard view or table.
UNIT-VI
73. What are procedural extensions?
In Oracle database management, PL/SQL is a procedural language extension to
Structured Query Language (SQL). The purpose of PL/SQL is to combine database
language and procedural programming language. The basic unit in PL/SQL is called a
block, which is made up of three parts: a declarative part, an executable part, and an
exception-building part.
74. Define local variables.
Local variables are declared in a inner block and cannot be referenced by outside Blocks.
75. Define stored procedures.
A stored procedure is a named set of PL/SQL statements designed to perform an action.
Stored procedures are stored inside the database. They define a programming interface
for the database rather than allowing the client application to interact with database
objects directly. Stored procedures are typically used for data validation or to encapsulate
large, complex processing instructions that combine several SQL queries.Stored
functions have a single return value parameter. Unlike functions, procedures may or may
not return values.
76. Define user defined functions.
User-defined functions combine the advantages of stored procedures with the capabilities
of SQL predefined functions. They can accept parameters, perform specific calculations
based on data retrieved by one or more SELECT statement, and return results directly to
the calling SQL statement.
77. Define system catalog.
In the SQL Standard a CATALOG is a collection of schemas that contains, among other
things, INFORMATION_SCHEMA. It comprises the tables and/or views that provide all
the information about all the other objects and records defined in the database: schemas,
tables, privileges, and so on. The main idea is to provide both users and the RDBMS with
a consistent standardized way of accessing metadata (the data about data: table
definitions, user-defined types, etc.) as well as some system information. By definition,
the INFORMATION_SCHEMA tables and views cannot be updated directly, though
some vendors allow this (e.g., IBM DB2 UDB).
UNIT-VII
78. Define index.
In Oracle SQL /PLSQL an INDEX is basically a performance tuning method which
allows
us
to
retrieve
or
fetch
the
desired
records
faster.
An INDEX will create an entry for each value that is stored in the indexed columns.
79. Define views.
A VIEW is a virtual table, through which a selective portion of the data from one or more
tables can be seen. Views do not contain data of their own. They are used to restrict
10
access to the database or to hide data complexity. A view is stored as a SELECT
statement in the database. DML operations on a view like INSERT, UPDATE, DELETE
affects the data in the original table upon which the view is based.
80. Define database security.
Database security concerns the use of a broad range of information security controls to
protect databases (potentially including the data, the database applications or stored
functions, the database systems, the database servers and the associated network links)
against compromises of their confidentiality, integrity and availability. It involves various
types or categories of controls, such as technical, procedural/administrative and physical.
Database security is a specialist topic within the broader realms of computer security,
information security and risk management.
81. Define role.
Roles are a collection of privileges or access rights. When there are many users in a
database it becomes difficult to grant or revoke privileges to users. Therefore, if you
define roles, you can grant or revoke privileges to users, thereby automatically granting
or revoking privileges. You can either create Roles or use the system roles pre-defined by
oracle.
82. Define authorization.
Authorization or authorisation is the function of specifying access rights to resources
related to information security and computer security in general and to access control in
particular. More formally, "to authorize" is to define an access policy. For example,
human resources staff is normally authorized to access employee records and this policy
is usually formalized as access control rules in a computer system. During operation, the
system uses the access control rules to decide whether access requests from
(authenticated) consumers shall be approved (granted) or disapproved (rejected).
Resources include individual files or an item's data, computer programs, computer
devices and functionality provided by computer applications. Examples of consumers are
computer users, computer programs and other devices on the computer.
83. Define grant.
SQL GRANT is a command used to provide access or privileges on the database objects
to the users. The Syntax for the GRANT command is:
GRANT privilege_name
ON object_name
TO {user_name |PUBLIC |role_name}
[WITH GRANT OPTION];
84. Define Revoke statements.
The REVOKE command removes user access rights or privileges to the database objects.
The Syntax for the REVOKE command is:
REVOKE privilege_name
ON object_name
FROM {user_name |PUBLIC |role_name}
85. Define triggers.
Triggers are stored programs, which are automatically executed or fired when some
events occur. Triggers are, in fact, written to be executed in response to any of the
following events:
A database manipulation (DML) statement (DELETE, INSERT, or UPDATE).
A database definition (DDL) statement (CREATE, ALTER, or DROP).
11
A database operation (SERVERERROR, LOGON, LOGOFF, STARTUP, or
SHUTDOWN).
Triggers could be defined on the table, view, schema, or database with which the event is
associated.
86. Define database level triggers.
Triggers can be created to be fired on database events, including errors, logins, logoffs,
shutdowns, and startups. You can use this type of trigger to automate database
maintenance or auditing actions. Virtual Private Databases, rely on database-level
triggers to establish session-context variable values.
Give brief answers to the following questions. (4 marks & 10 marks)
1. Difference between Database and RDBMS.
Ans.
• Relationship among tables is maintained in a RDBMS whereas this not the case
in DBMS as it is used to manage the database.
• DBMS accepts the ‘flat file’ data that means there is no relation among different
data whereas RDBMS does not accepts this type of design.
• DBMS is used for simpler business applications whereas RDBMS is used for
more complex applications.
• Although the foreign key concept is supported by both DBMS and RDBMS but
its only RDBMS that enforces the rules.
• RDBMS solution is required by large sets of data whereas small sets of data can
be managed by DBMS.
2. Advantages and Disadvantages of RDBMS.
Advantages of a relational database
1. Data is only stored once. In the previous example, the city data was gathered into one
table so now there is only one record per city. The advantages of this are
No multiple record changes needed
More efficient storage
Simple to delete or modify details.
All records in other tables having a link to that entry will show the change.
2. Complex queries can be carried out. A language called SQL has been developed to
allow programmers to 'Insert', 'Update', 'Delete', 'Create', 'Drop' table records.
These actions are further refined by a 'Where' clause. For example
SELECT * FROM Customer WHERE ID = 2
This SQL statement will extract record number 2 from the Customer table. Far
more complicated queries can be written that can extract data from many tables at
once.
3. Better security. By splitting data into tables, certain tables can be made confidential.
When a person logs on with their username and password, the system can then
limit access only to those tables whose records they are authorized to view. For
example, a receptionist would be able to view employee location and contact
details but not their salary. A salesman may see his team's sales performance but
not competing teams.
4. Cater for future requirements. By having data held in separate tables, it is simple to
add records that are not yet needed but may be in the future. For example, the city
table could be expanded to include every city and town in the country, even
though no other records are using them all as yet. A flat file database cannot do
this.
5. Ease of use: The revision of any information as tables consisting of rows and columns
is much easier to understand.
6. Flexibility: Different tables from which information has to be linked and extracted can
be easily manipulated by operators such as project and join to give information in
the form in which it is desired.
7. Precision: The usage of relational algebra and relational calculus in the manipulation of
the relations between the tables ensures that there is no ambiguity, which may
otherwise arise in establishing the linkages in a complicated network type
database.
Summary - advantages of a relational database over flat file
Avoids data duplication
12
Avoids inconsistent records
Easier to change data
Easier to change data format
Data can be added and removed easily
Easier to maintain security.
Disadvantages of the Relational Database
The main problem when using a relational database is the complexity that arises when it is first
created. It is absolutely vital that the defined relationships between the tables are correct and that
each set of information is linked to its pair. Although less information has to be entered in total
than with other databases, making sure every point is set up correctly is a slow process.
Furthermore, the relationships can become extremely intricate when a relational database
contains more than just two tables.
1. Performance: A major constraint and therefore disadvantage in the use of relational database
system is machine performance. If the number of tables between which relationships to be
established are large and the tables themselves effect the performance in responding to the SQL
queries.
2. Physical Storage Consumption: With an interactive system, for example an operation like join
would depend upon the physical storage also. It is, therefore common in relational databases to
tune the databases and in such a case the physical data layout would be chosen so as to give good
performance in the most frequently run operations. It therefore would naturally result in the fact
that the lays frequently run operations would tend to become even more shared.
3. Slow extraction of meaning from data: if the data is naturally organized in a hierarchical
manner and stored as such, the hierarchical approach may give quick meaning for that data.
4. Data Complexity: Data in an RDBMS resides in multiple tables, which are linked to each
other through shared key values. An RDBMS does not force database designers to impose a
coherent table structure; inexperienced programmers may design systems that create unnecessary
complexity or limit the future development of the database through poorly chosen data types.
The flexibility of an RDBMS presents a double-edged sword. Experienced designers work
magic, but inexperienced designers wreak havoc on a company's data.
5. Broken Keys and Records: Relational databases require shared keys to link information spread
across several tables. For example, a customer table may include client demographics, with a
unique index number identifying the record within the table. A sales table may identify the
customer only by that index number. If the data types linking the keys are different, the database
cannot link the records without additional rework by the report developer. Likewise, if a table
lacks a unique key, the database may return inaccurate results. If the application accessing a
database isn't coded to lock records during an edit, users could inadvertently corrupt data,
leading to broken records.
6. Developer Expertise: As the complexity of a relational database increases, the skill set
required by the RDBMS administrator, various users and report developers also increases. A
mission-critical database may require expertise that exceeds the budget of a small business;
furthermore, if the developers did not uniformly engage in best practice design, a subsequent
developer may not understand hidden intricacies that could lead to broken queries or inaccurate
reports. This risk increases if database and application development is performed by different
people.
7. Hardware Performance: Complex queries require sophisticated processing power. Although
most desktop computers can manage the databases of the size and complexity often encountered
in a small business setting, a database with external data sources or very complex data structures
may require more powerful servers to return results within an acceptable response time.
3. Describe the following key constraints
A)unique key
B)alternate key
A) The UNIQUE constraint uniquely identifies each record in a database table.
The UNIQUE and PRIMARY KEY constraints both provide a guarantee for uniqueness
for a column or set of columns.
A PRIMARY KEY constraint automatically has a UNIQUE constraint defined on it.
You can have many UNIQUE constraints per table, but only one PRIMARY KEY
constraint per table.
13
B) If any table have more than one candidate key, then after choosing primary key from
those candidate key, rest of candidate keys are known as an alternate key of that table.
Like here we can take a very simple example to understand the concept of alternate key.
Suppose we have a table named Employee which has two columns EmpID and EmpMail,
both have not null attributes and unique value. So both columns are treated as candidate
key. Now we make EmpID as a primary key to that table then EmpMail is known as
alternate key.
4. What is attribute and domain of attribute
A domain D is a set of atomic values. By atomic we mean that each value in the domain
is indivisible as far as the relational model is concerned. A common method of specifying
a domain is to specify a data type from which the data values forming the domain are
drawn. It is also useful to specify a name for the domain, to help in interpreting its values.
Some examples of domains follow:
• USA_phone_numbers: The set of 10-digit phone numbers valid in the United States.
• Local_phone_numbers: The set of 7-digit phone numbers valid within a particular area
code in the United States.
The preceding are called logical definitions of domains. A data type or format is also
specified for each domain. For example, the data type for the domain
USA_phone_numbers can be declared as a character string of the form (ddd)ddd-dddd,
where each d is a numeric (decimal) digit and the first three digits form a valid telephone
area code.
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 a role played by some domain D in the relation schema
R.
D is called the domain of Ai and is denoted by dom(Ai).
5. Explain relational constraints.
Relational Constraints are various restrictions on data that can be specified on a relational
database schema in the form of constraints. These include domain constraints, key
constraints, entity integrity, and referential integrity constraints. Other types of constraints,
called data dependencies (which include functional dependencies and multivalued
dependencies ), are used mainly for database design by normalization .
1. Domain Constraints
Domain constraints specify that the value of each attribute A must be an atomic value
from the domain dom(A). The data types associated with domains typically include
standard numeric data types for integers (such as short-integer, integer, long-integer) and
real numbers (float and double-precision float). Characters, fixed-length strings, and
variable-length strings are also available, as are date, time, timestamp, and money data
types. Other possible domains may be described by a subrange of values from a data type
or as an enumerated data type where all possible values are explicitly listed
2. Key Constraints and Constraints on Null
A relation is defined as a set of tuples. By definition, all elements of a set are distinct;
hence, all tuples in a relation must also be distinct. This means that no two tuples can
have the same combination of values for all their attributes. Usually, there are other
subsets of attributes of a relation schema R with the property that no two tuples in any
relation state r of R should have the same combination of values for these attributes.
Suppose that we denote one such subset of attributes by SK; then for any two distinct
tuples t1 and t2 in a relation state r of R, we have the constraint that
t1[SK] =t2[SK]
Any such set of attributes SK is called a superkey of the relation schema R.
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 attributes K’ that is not a superkey of R.
Hence, a key is a minimal superkey—that is, a superkey from which we cannot remove
any attributes and still have the uniqueness constraint hold.
14
The value of a key attribute can be used to identify uniquely each tuple in the relation.
Notice that a set of attributes constituting a key is a property of the relation schema; it is a
constraint that should hold on every relation state of the schema.
In general, a relation schema may have more than one key. In this case, each of the keys
is called a candidate key.
It is common to designate one of the candidate keys as the primary key of the relation.
This is the candidate key whose values are used to identify tuples in the relation. When a
relation schema has several candidate keys, the choice of one to become primary key is
arbitrary; however, it is usually better to choose a primary key with a single attribute or a
small number of attributes.
Another constraint on attributes specifies whether null values are or are not permitted.
For example, if every STUDENT tuple must have a valid, non-null value for the Name
attribute, then Name of STUDENT is constrained to be NOT NULL.
3. Entity Integrity
The entity integrity constraint states that no primary key value can be null. This is
because the primary key value is used to identify individual tuples in a relation; having
null values for the primary key implies that we cannot identify some tuples. For example,
if two or more tuples had null for their primary keys, we might not be able to distinguish
them.
Key constraints and entity integrity constraints are specified on individual relations.
4. The referential integrity constraint A foreign key constraint is used to ensure the
referential integrity of the data in one table to match values in another table. It is specified
between two relations and is used to maintain the consistency among tuples of the two
relations. Informally, the referential integrity constraint states that a tuple in one relation
that refers to another relation must refer to an existing tuple in that relation.
To define referential integrity more formally, we first define the concept of a foreign key.
The conditions for a foreign key, given below, specify a referential integrity constraint
between the two relation schemas R1 and R2. A set of attributes FK in relation schema
R1 is a foreign key of R1 that references relation R2 if it satisfies the following two
rules:
1. The attributes in FK have the same domain(s) as the primary key attributes PK of R2; the
attributes FK are said to reference or refer to the relation R2.
2. A value of FK in a tuple t1 of the current state r1(R1) either occurs as a value of PK for
some tuple t2 in the current state r2(R2) or is null. In the former case, we have t1[FK] =
t2[PK], and we say that the tuple t1 references or refers to the tuple t2. R1 is called the
referencing relation and R2 is the referenced relation.
Notice that a foreign key can refer to its own relation. We can diagrammatically display
referential integrity constraints by drawing a directed arc from each foreign key to the
relation it references. For clarity, the arrowhead may point to the primary key of the
referenced relation.
6. Explain integrity rules.
1. Entity Integrity
The entity integrity constraint states that no primary key value can be null. This is because
the primary key value is used to identify individual tuples in a relation; having null values for
the primary key implies that we cannot identify some tuples. For example, if two or more
tuples had null for their primary keys, we might not be able to distinguish them.
Key constraints and entity integrity constraints are specified on individual relations.
2. The referential integrity constraint A foreign key constraint is used to ensure the
referential integrity of the data in one table to match values in another table. It is specified
between two relations and is used to maintain the consistency among tuples of the two
relations. Informally, the referential integrity constraint states that a tuple in one relation that
refers to another relation must refer to an existing tuple in that relation.
To define referential integrity more formally, we first define the concept of a foreign key.
The conditions for a foreign key, given below, specify a referential integrity constraint
15
between the two relation schemas R1 and R2. A set of attributes FK in relation schema R1 is
a foreign key of R1 that references relation R2 if it satisfies the following two rules:
1. The attributes in FK have the same domain(s) as the primary key attributes PK of R2; the
attributes FK are said to reference or refer to the relation R2.
2. A value of FK in a tuple t1 of the current state r1(R1) either occurs as a value of PK for
some tuple t2 in the current state r2(R2) or is null. In the former case, we have t1[FK] =
t2[PK], and we say that the tuple t1 references or refers to the tuple t2. R1 is called the
referencing relation and R2 is the referenced relation.
A foreign key can refer to its own relation. We can diagrammatically display referential
integrity constraints by drawing a directed arc from each foreign key to the relation it
references. For clarity, the arrowhead may point to the primary key of the referenced
relation.
7. Explain in brief need of normalization.
Need or objective of normalization: The objective is to isolate data so that additions,
deletions, and modifications of a field can be made in just one table and then propagated
through the rest of the database using the defined relationships. Its purpose is to ensure
data stored within the database adheres to best practices by following a set of rules with
the purpose of eliminating redundancies and optimizing the process of information
retrieval.
A basic objective of the first normal form defined by Codd in 1970 was to permit data to
be queried and manipulated using a "universal data sub-language" grounded in first-order
logic. (SQL is an example of such a data sub-language)
The objectives of normalization beyond 1NF (First Normal Form) were stated as follows
by Codd:
1. To free the collection of relations from undesirable insertion, update and deletion
dependencies;
2. To reduce the need for restructuring the collection of relations, as new types of data are
introduced, and thus increase the life span of application programs;
3. To make the relational model more informative to users;
4. To make the collection of relations neutral to the query statistics, where these statistics
are liable to change as time goes by.
8. What are trivial and non trivial Function dependencies
Trivial − 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 − If an FD X → Y holds, where Y is not a subset of X, then it is called a nontrivialFD.
9. Discuss 3 NF and BCNF. What is difference in them?
3NF
3NF is the Third normal form used in relational database normalization. According to the
Codd’s definition, a table is said to be in 3NF, if and only if, that table is in the second
normal form (2NF), and every attribute in the table that do not belong to a candidate key
should directly depend on every candidate key of that table. Tables that comply with the
3NF generally do not contain anomalies that occur when inserting, deleting or updating
records in the table.
BCNF
BCNF (also known as 3.5NF) is another normal form used in relational database
normalization. It was introduced to capture some the anomalies that are not addressed by
the 3NF. A table is said to be in BCNF, if and only if, for each of the dependencies of the
form A → B that are non-trivial, A is a super-key.
Difference between 3NF and BCNF
Both 3NF and BCNF are normal forms that are used in relational databases to minimize
redundancies in tables. In a table that is in the BCNF normal form, for every non-trivial
functional dependency of the form A → B, A is a super-key whereas, a table that
complies with 3NF should be in the 2NF, and every non-prime attribute should directly
depend on every candidate key of that table. BCNF is considered as a stronger normal
form than the 3NF and it was developed to capture some of the anomalies that could not
be captured by 3NF. Obtaining a table that complies with the BCNF form will require
decomposing a table that is in the 3NF. This decomposition will result in additional join
16
operations (or Cartesian products) when executing queries. This will increase the
computational time. On the other hand, the tables that comply with BCNF would have
fewer redundancies than tables that only comply with 3NF. Furthermore, most of the
time, it is possible to obtain a table that comply with 3NF without hindering dependency
preservation and lossless joining. But this is not always possible with BCNF.
10. Explain relational algebra and its operations.
The relational algebra is a procedural query language. It consists of a set of operations that
take one or two relations as input and produces a new relation as output.
Fundamental Operations
SELECT
PROJECT
UNION
SET DIFFERENCE
CARTESIAN PRODUCT
RENAME
Select and project operations are unary operation as they operate on a single
relation.Union, set difference, Cartesian product and rename operations are binary
operations as they operate on pairs of relations.
Other Operations
SET INTERSECTION
NATURAL JOIN
DIVISION
ASSIGNMENT
1. The select operation: - to identify a set of tuples which is a part of a relation and to extract
only these tuples out. The select operation selects tuples that satisfy a given predicate or
condition.
It is a unary operation defined on a single relation.
It is denoted as σ.
Example1:- Select from the relation “Book” all the books whose year of publication is 1992.
Code:
σ Yr-pub=1992(Book)
2. The project operation: - returns its argument relation with certain attributes left out.
It is a unary operation defined on a single relation
It is denoted as Π.
Example:- List all the Title and Acc-no of the “Book” relation.
Code:
Π Acc-no, Title (Book)
3. The union operation: - is used when we need some attributes that appear in either or
both of the two relations.
It is denoted as U.
Example:
Borrower (customer-name, loan-number)
Depositor (customer-name, account-number)
Customer (customer-name, street-number, customer-city)
List all the customers who have either an account or a loan or both
17
Code:
Π customer-name (Borrower) U Π customer-name (Depositor)
For a union operation r U s to be valid, two conditions must hold:
The relation r and s must be of the same arity, i.e. they must have the same number of attributes.
The domains of the ith attribute of r and the ith attribute of s must be the same for all i.
4. The set difference operation: - finds tuples in one relation but not in other.
It is denoted as –
Example:
Find the names of all customers who have an account but not a loan.
Code:
Π customer-name (Depositor) - Π customer-name (Borrower)
5. The Cartesian product operation: - allows combining information from two relations.
It is denoted as r X s where r and s are relations.
Consider the following relation or table "r" :Code:
+--------+-------+
| A |B |
+--------+-------+
| a | 1 |
| b | 2 |
| a | 2 |
+--------+-------+
Consider another relation or table "s" :Code:
+--------+-------+
| B |C |
+--------+-------+
| 3 | 1a |
| 2 | 2b |
+--------+-------+
Therefore, rXs gives:Code:
+-----------+---------+---------+----------+
| r.A
|r.B
| s.B | s.C
|
+-----------+---------+---------+----------+
| a
| 1 | 3 | 1a
|
| a
| 1 | 2 | 2b
|
| b
| 2 | 3 | 1a
|
| b
| 2 | 2 | 2b
|
| a
| 2 | 3 | 1a
|
| a
| 2 | 2 | 2b
|
+-----------+---------+---------+----------+
If relation r has n1 tuples and relation s has n2 tuples then r X s has n1*n2 tuples.
6.The rename operation: - used to rename.
It is denoted as ρ.
18
E : relational algebra expression
ρ x (E): returns the result of expression E under the name x.
ρ x (A1, A2, A3… An) (E): returns the result of expression E under the name x with attributes
renamed to A1, A2, A3… An.
7.The set intersection operation: - finds tuples in both the relations.
It is denoted as ∩.
Example:
Borrower (customer-name, loan-number)
Depositor (customer-name, account-number)
Customer (customer-name, street-number, customer-city)
List all the customers who have both a loan and an account.
Code:
Π customer-name (Borrower) ∩ Π customer-name (Depositor)
8.The natural join operation: - it is a binary operation and a combination of certain selections
and a Cartesian product into one operation.
It is denoted as |X| .
It is associative.
It forms a Cartesian product of its two arguments.
Then performs a selection forcing equality on those attributes those appear in both the relations.
And finally removes duplicates attributes.
r(R): r is a relation with attributes R.
s(S): s is a relation with attributes S.
If R ∩ S = Ф i.e. they have no attributes in common then r |X| s = r X s
i.e;
if r (A, B, C), s (B, D) then
Code:
r|X|s = Π r.A, r.B, r.C, s.D (σ r.B = s.B (r X s))
9.The division / quotient operation: It is denoted as ÷.
Let r(R) and s(S) be relations
r ÷ s: - the result consists of the restrictions of tuples in r to the attribute names unique to R, i.e.
in the Header of r but not in the Header of s, for which it holds that all their combinations with
tuples in s are present in r.
Example:
Relation or table "r":Code:
+--------+-------+
| A |B |
+--------+-------+
| a | 1 |
| b | 2 |
| a | 2 |
| p | 3 |
| p | 4 |
+--------+-------+
Relation or table "s":Code:
+------+
19
| B |
+------+
| 2 |
| 3 |
+------+
Therefore, r ÷ s
Code:
+------+
| A |
+------+
| b |
| a |
| p |
+------+
11. Explain 2nd and 3rd normal form with Examples
Second-Normal Form (2NF)
We know we don’t have any repeating groups as we removed these with First Normal Form.
But if we look at our example we can see for every UnitCode we are also storing the
UnitName.
We can consider a relation to be in
Second Normal Form when: The
relation is in First Normal Form and
all partial key dependencies are
removed so that all non key domains
are functionally dependant on all of
the domains that make up the primary
key.
Before we start with the steps, if we
have a table with only a single simple key this can’t have any partial dependencies as
there is only one domain that is a key therefore these relations can be moved directly to
2nd normal form.
Third-Normal Form (3NF)
Third Normal Form deals with something called
‘transitive’ dependencies. This means if we have
a primary key A and a non-key domain B and C
where C is more dependent on B than A and B is
directly dependent on A, then C can be
considered transitively dependant on A.
Before we start with the steps, if we have any
relations with zero or only one non-key domain we can’t have a transitive dependency so these
move straight to 3rd Normal Form
20
For the rest the steps from 2NF to 3NF are:
1. Take each non-key domain in turn and check it is more dependent on another non-key
domain than the primary key.
2. If yes
a. Move the dependent domain, together with a copy of the non-key attribute upon
which it is dependent, to a new relation.
b. Make the non-key domain, upon which it is dependent, the key in the new
relation.
c. Underline the key in this new relation as the primary key.
d. Leave the non-key domain, upon which it was dependent, in the original relation
and mark it a foreign key (*).
3. Move down the relation to each of the domains repeating steps 1 and 2 till you have
covered the whole relation.
4. Once completed with all transitive dependencies removed, the table is in 3rd normal
form.
In our example above, we have unitCode as our primary key, we also have a courseName that is
dependent on courseCode and courseCode, dependent on unitCode. Though couseName could be
dependent on unitCode it more dependent on courseCode, therefore it is transitively dependent
on unitCode.
So following the steps, remove courseName with a copy of course code to another relation and
make courseCode the primary key of the new relation. In the original table mark courseCode as
our foreign key.
12. Explain tuple calculus.
The tuple relational calculus is a nonprocedural language. (The relational algebra was
procedural.)
We must provide a formal description of the information desired.
1. A query in the tuple relational calculus is expressed as
i.e. the set of tuples for which predicate
is true.
21
2. We also use the notation
o
to indicate the value of tuple on attribute .
o
to show that tuple is in relation .
13. Explain domain calculus.
Domain variables take on values from an attribute's domain, rather than values for an
entire tuple.
Formal Definitions
1. An expression is of the form
where the
represent domain variables, and
is a formula.
2. An atom in the domain relational calculus is of the following forms
o
where is a relation on attributes, and
, are
domain variables or constants.
o
, where and are domain variables, and is a comparison operator.
o
, where c is a constant.
3. Formulae are built up from atoms using the following rules:
o An atom is a formula.
o If is a formula, then so are
and
.
o If
and are formulae, then so are
,
and
.
o If
is a formula where x is a domain variable, then so are
and
.
14. Explaain aggregate functions.
Group (Aggregate) Functions
SQL aggregate functions return a single value, calculated from values in a column.
Useful aggregate functions:
AVG() - Returns the average value
COUNT() - Returns the number of rows
MAX() - Returns the largest value
MIN() - Returns the smallest value
SUM() - Returns the sum
1.The AVG() Function
The AVG() function returns the average value of a numeric column.
AVG() Syntax
SELECT AVG(column_name) FROM table_name;
2.The COUNT() function
It returns the number of rows that matches a specified criteria.
COUNT(column_name) Syntax
The COUNT(column_name) function returns the number of values (NULL values will
not be counted) of the specified column:
SELECT COUNT(column_name) FROM table_name;
22
COUNT(*) Syntax
The COUNT(*) function returns the number of records in a table:
SELECT COUNT(*) FROM table_name;
SQL COUNT(DISTINCT column_name) Syntax
The COUNT(DISTINCT column_name) function returns the number of distinct values of
the specified column:
SELECT COUNT(DISTINCT column_name) FROM table_name;
Note:COUNT(DISTINCT) works with ORACLE and Microsoft SQL Server, but not
with Microsoft Access.
3.The MAX() Function
The MAX() function returns the largest value of the selected column.
MAX() Syntax
SELECT MAX(column_name) FROM table_name;
4.The MIN() Function
The MIN() function returns the smallest value of the selected column.
MIN() Syntax
SELECT MIN(column_name) FROM table_name;
5.The SUM() Function
The SUM() function returns the total sum of a numeric column.
SUM() Syntax
SELECT SUM(column_name) FROM table_name;
15. Exaplain scalar functions.
1) Numeric Functions:
Numeric functions are used to perform operations on numbers. They accept numeric values
as input and return numeric values as output. Few of the Numeric functions are:
Function
Name
Return Value
ABS (x)
Absolute value of the number 'x'
CEIL (x)
Integer value that is Greater than or equal to the number 'x'
FLOOR (x)
Integer value that is Less than or equal to the number 'x'
23
TRUNC (x, y) Truncates value of number 'x' up to 'y' decimal places
ROUND (x, y) Rounded off value of the number 'x' up to the number 'y' decimal places
The following examples explains the usage of the above numeric functions
2) Character or Text Functions:
Character or text functions are used to manipulate text strings. They accept strings or
characters as input and can return both character and number values as output.
Few of the character or text functions are as given below:
Function Name
Return Value
LOWER (string_value)
All the letters in 'string_value' is converted to lowercase.
UPPER (string_value)
All the letters in 'string_value' is converted to uppercase.
INITCAP (string_value)
All the letters in 'string_value' is converted to mixed case.
LTRIM
(string_value, All occurrences of 'trim_text' is removed from the left of
trim_text)
RTRIM
'string_value'.
(string_value, All occurrences of 'trim_text' is removed from the right of
trim_text)
'string_value' .
TRIM (trim_text FROM All occurrences of 'trim_text' from the left and right of
string_value)
SUBSTR
'string_value' , 'trim_text' can also be only one character long .
(string_value, Returns 'n' number of characters from 'string_value' starting from
m, n)
the 'm' position.
LENGTH (string_value)
Number of characters in 'string_value' in returned.
LPAD (string_value, n, Returns 'string_value' left-padded with 'pad_value' . The length of
pad_value)
the whole string will be of 'n' characters.
RPAD (string_value, n, Returns 'string_value' right-padded with 'pad_value' . The length
pad_value)
of the whole string will be of 'n' characters.
The following examples explains the usage of the above character or text functions
24
LOWER(string_value)
LOWER('Good Morning')
UPPER(string_value)
UPPER('Good Morning')
good morning
GOOD
MORNING
INITCAP(string_value)
INITCAP('GOOD MORNING')
Good Morning
LTRIM(string_value, trim_text)
LTRIM ('Good Morning', 'Good)
Morning
RTRIM (string_value, trim_text)
RTRIM
('Good
Morning',
'
Good
Morning')
TRIM
(trim_text
FROM
string_value)
TRIM ('o' FROM 'Good Morning') Gd Mrning
SUBSTR (string_value, m, n)
SUBSTR ('Good Morning', 6, 7)
Morning
LENGTH (string_value)
LENGTH ('Good Morning')
12
LPAD (string_value, n, pad_value)
LPAD ('Good', 6, '*')
**Good
RPAD (string_value, n, pad_value)
RPAD ('Good', 6, '*')
Good**
3) Date Functions:
These are functions that take values that are of datatype DATE as input and return values
of datatypes DATE, except for the MONTHS_BETWEEN function, which returns a
number as output.
Few date functions are as given below.
Function Name
Return Value
ADD_MONTHS (date, n) Returns a date value after adding 'n' months to the date 'x'.
MONTHS_BETWEEN
(x1, x2)
ROUND (x, date_format)
Returns the number of months between dates x1 and x2.
Returns the date 'x' rounded off to the nearest century, year,
month, date, hour, minute, or second as specified by the
25
'date_format'.
Returns the date 'x' lesser than or equal to the nearest century,
TRUNC (x, date_format)
year, month, date, hour, minute, or second as specified by the
'date_format'.
NEXT_DAY
(x, Returns the next date of the 'week_day' on or after the date 'x'
week_day)
occurs.
It is used to determine the number of days remaining in a month
LAST_DAY (x)
from the date 'x' specified.
SYSDATE
NEW_TIME
Returns the systems current date and time.
(x,
zone1, Returns the date and time in zone2 if date 'x' represents the time in
zone2)
zone1.
The below table provides the examples for the above functions
4) Conversion Functions:
These are functions that help us to convert a value in one form to another form. For Ex: a
null value into an actual value, or a value from one datatype to another datatype like
NVL, TO_CHAR, TO_NUMBER, TO_DATE.
Few of the conversion functions available in oracle are:
Function Name
Return Value
TO_CHAR (x [,y])
TO_DATE
date_format])
NVL (x, y)
(x
Converts Numeric and Date values to a character string value. It
cannot be used for calculations since it is a string value.
[, Converts a valid Numeric and Character values to a Date value. Date
is formatted to the format specified by 'date_format'.
If 'x' is NULL, replace it with 'y'. 'x' and 'y' must be of the same
datatype.
DECODE (a, b, c, d, e, Checks the value of 'a', if a = b, then returns 'c'. If a = d, then
default_value)
returns 'e'. Else, returns default_value.
26
The below table provides the examples for the above functions
16. How objects of database can be created?
The CREATE TABLE Statement is used to create tables to store data. Integrity
Constraints like primary key, unique key, foreign key can be defined for the columns
while creating the table. The integrity constraints can be defined at column level or table
level.
The Syntax for the CREATE TABLE Statement is:
CREATE TABLE table_name
(column_name1 datatype,
column_name2 datatype,
... column_nameN datatype
);
table_name - is the name of the table.
column_name1, column_name2.... - is the name of the columns
datatype - is the datatype for the column like char, date, number etc.
Oracle provides another way of creating a table.
CREATE TABLE temp_employee
SELECT * FROM employee
In the above statement, temp_employee table is created with the same number of columns
and datatype as employee table.
17. Define IF statement.
In Oracle, the IF-THEN-ELSE statement is used to execute code when a condition is
TRUE, or execute different code if the condition evaluates to FALSE.
Syntax
There are different syntaxes for the IF-THEN-ELSE statement.
Syntax (IF-THEN)
The syntax is for IF-THEN in Oracle/PLSQL is:
IF condition THEN
{...statements to execute when condition is TRUE...}
END IF;
You use the the IF-THEN syntax, when you want to execute statements only when
condition is TRUE.
Syntax (IF-THEN-ELSE)
The syntax is for IF-THEN-ELSE in Oracle/PLSQL is:
27
IF condition THEN
{...statements to execute when condition is TRUE...}
ELSE
{...statements to execute when condition is FALSE...}
END IF;
You use the IF-THEN-ELSE syntax, when you want to execute one set of statements
when condition is TRUE or a different set of statements when condition is FALSE.
Syntax (IF-THEN-ELSIF)
The syntax for IF-THEN-ELSIF in Oracle/PLSQL is:
IF condition1 THEN
{...statements to execute when condition1 is TRUE...}
ELSIF condition2 THEN
{...statements to execute when condition2 is TRUE...}
END IF;
You use the IF-THEN-ELSIF syntax, when you want to execute one set of statements
when condition1 is TRUE or a different set of statements when condition2 is TRUE.
Syntax (IF-THEN-ELSIF-ELSE)
The syntax for IF-THEN-ELSIF-ELSE in Oracle/PLSQL is:
IF condition1 THEN
{...statements to execute when condition1 is TRUE...}
ELSIF condition2 THEN
{...statements to execute when condition2 is TRUE...}
ELSE
{...statements to execute when both condition1 and condition2 are FALSE...}
END IF;
You use the IF-THEN-ELSIF-ELSE syntax, when you want to execute one set of
statements when condition1 is TRUE, a different set of statements when condition2 is
TRUE, or a different set of statements when all previous conditions (ie: condition1 and
condition2) are FALSE.
18. Define WHILE statement.
A WHILE LOOP statement in PL/SQL programming language repeatedly executes a target
statement as long as a given condition is true.
Syntax:
WHILE condition LOOP
sequence_of_statements
END LOOP;
Example:
DECLARE
28
a number(2) := 10;
BEGIN
WHILE a < 20 LOOP
dbms_output.put_line('value of a: ' || a);
a := a + 1;
END LOOP;
END;
/
When the above code is executed at SQL prompt, it produces the following result:
value of a: 10
value of a: 11
value of a: 12
value of a: 13
value of a: 14
value of a: 15
value of a: 16
value of a: 17
value of a: 18
value of a: 19
PL/SQL procedure successfully completed
19. How objects of database can be modified.
SQL ALTER TABLE Statement
The SQL ALTER TABLE command is used to modify the definition (structure) of a table by
modifying the definition of its columns. The ALTER command is used to perform the
following functions.
1) Add, drop, modify table columns
2) Add and drop constraints
3) Enable and Disable constraints
Syntax to add a column
ALTER TABLE table_name ADD column_name datatype;
For Example: To add a column "experience" to the employee table, the query would be like
ALTER TABLE employee ADD experience number(3);
Syntax to drop a column
ALTER TABLE table_name DROP column_ columnname;
For Example: To drop the column "location" from the employee table, the query would be like
ALTER TABLE employee DROP column location;
Syntax to modify a column
ALTER TABLE table_name MODIFY column_name datatype;
For Example: To modify the column salary in the employee table, the query would be
like ALTER TABLE employee MODIFY salary number(15,2);
20. How objects of database can be removed?
29
The SQL DROP command is used to remove an object from the database. If you drop a
table, all the rows in the table is deleted and the table structure is removed from the
database. Once a table is dropped we cannot get it back, so be careful while using DROP
command. When a table is dropped all the references to the table will not be valid.
Syntax to drop a sql table structure:
DROP TABLE table_name;
For Example: To drop the table employee, the query would be like
DROP TABLE employee;
21. Explain insert, delete and update statement.
Adding, changing and deleting operations in the database are commonly called Data
Manipulation Language (DML) statements:
An INSERT statement adds new rows to an existing table.
An UPDATE statement modifies the values of a set of existing table rows.
A DELETE statement removes existing rows from a table.
Because these statements change the data in your table, Oracle recommends that you use
transaction management to group all dependent DML statements together.
1.SQL INSERT Statement
The INSERT Statement is used to add new rows of data to a table.
We can insert data to a table in two ways,
1) Inserting the data directly to a table.
Syntax for SQL INSERT is:
INSERT INTO TABLE_NAME [ (col1, col2, col3,...colN)] VALUES (value1,
value2, value3,...valueN);
col1, col2,...colN -- the names of the columns in the table into which you want to insert
data.
While inserting a row, if you are adding value for all the columns of the table you need
not specify the column(s) name in the sql query. But you need to make sure the order of
the values is in the same order as the columns in the table. The sql insert query will be as
follows
INSERT INTO TABLE_NAME VALUES (value1, value2, value3,...valueN);
For Example: If you want to insert a row to the employee table, the query would be like,
INSERT INTO employee (id, name, dept, age, salary location) VALUES (105,
'Srinath', 'Aeronautics', 27, 33000);
NOTE:When adding a row, only the characters or date values should be enclosed with
single quotes.
If you are inserting data to all the columns, the column names can be omitted. The above
insert statement can also be written as,
INSERT INTO employee VALUES (105, 'Srinath', 'Aeronautics', 27, 33000);
2.Inserting data to a table through a select statement.
Syntax for SQL INSERT is:
INSERT INTO table_name
[(column1, column2, ... columnN)]
SELECT column1, column2, ...columnN
FROM table_name [WHERE condition];
For Example: To insert a row into the employee table from a temporary table, the sql
insert query would be like,
30
INSERT INTO employee (id, name, dept, age, salary location) SELECT
emp_id, emp_name, dept, age, salary, location
FROM temp_employee;
If you are inserting data to all the columns, the above insert statement can also be written
as,
INSERT INTO employee
SELECT * FROM temp_employee;
NOTE:We have assumed the temp_employee table has columns emp_id, emp_name,
dept, age, salary, location in the above given order and the same datatype.
IMPORTANT NOTE:
1) When adding a new row, you should ensure the datatype of the value and the column
matches
2) You follow the integrity constraints, if any, defined for the table.
2. SQL UPDATE statement
The UPDATE Statement is used to modify the existing rows in a table.When you use the
UPDATE statement to update data in a row of a table, the new data must be valid for the
data type and size of each column of the table.
The general syntax of the UPDATE command looks like the following. Note that the
columns that are altered must be identified, and the matching conditions must be met.
UPDATE table_name
SET column_name = value;
WHERE condition;
To update information in a row that is missing data, the missing data column should be
specified. In Example , you will update the salary column for a previously inserted
record.
Example Using the UPDATE Statement to Add Missing Data
UPDATE employees SET salary = 8500 WHERE last_name = 'Keats';
The results of the query appear.
1 row updated.
Your result shows that the matching row has been updated.
Example shows how you can use the UPDATE statement to update multiple rows.
Example Using the UPDATE Statement to Change Data
UPDATE employees SET commission_pct=commission_pct + 0.05 WHERE
department_id = 80;
The results of the query appear.
36 rows updated.
Your result shows that the specified rows are updated.
NOTE:In the Update statement, WHERE clause identifies the rows that get affected. If
you do not include the WHERE clause, column values for all the rows get affected.
3. SQL DELETE Statement
The DELETE Statement is used to delete rows from a table.
Syntax of a SQL DELETE Statement
DELETE FROM table_name [WHERE condition];
31
table_name -- the table name which has to be updated.
NOTE: The WHERE clause in the sql delete command is optional and it identifies the
rows in the column that gets deleted. If you do not include the WHERE clause all the
rows in the table is deleted, so be careful while writing a DELETE query without
WHERE clause.
SQL DELETE Example
To delete an employee with id 100 from the employee table, the sql delete query would be
like,
DELETE FROM employee WHERE id = 100;
To delete all the rows from the employee table, the query would be like,
DELETE FROM employee;
22. Explain queries in SQL.
The most common operation in SQL is the query, which is performed with the
declarative SELECT statement. SELECT retrieves data from one or more tables, or
expressions. Standard SELECT statements have no persistent effects on the database. Some
non-standard implementations of SELECT can have persistent effects, such as the SELECT
INTO syntax that exists in some databases.[20]
Queries allow the user to describe desired data, leaving the database management system
(DBMS) responsible for planning, optimizing, and performing the physical operations
necessary to produce that result as it chooses.
A query includes a list of columns to include in the final result, immediately following
the SELECT keyword. An asterisk (" * ") can also be used to specify that the query should
return all columns of the queried tables. SELECT is the most complex statement in SQL,
with optional keywords and clauses that include:
The FROM clause, which indicates the table(s) to retrieve data from. The FROM clause
can include optional JOIN subclauses to specify the rules for joining tables.
The WHERE clause includes a comparison predicate, which restricts the rows returned by
the query. The WHERE clause eliminates all rows from the result set where the comparison
predicate does not evaluate to True.
The GROUP BY clause is used to project rows having common values into a smaller set of
rows. GROUP BY is often used in conjunction with SQL aggregation functions or to
eliminate duplicate rows from a result set. The WHERE clause is applied before
the GROUP BY clause.
The HAVING clause includes a predicate used to filter rows resulting from the GROUP
BY clause. Because it acts on the results of the GROUP BY clause, aggregation functions
can be used in the HAVING clause predicate.
The ORDER BY clause identifies which columns to use to sort the resulting data, and in
which direction to sort them (ascending or descending). Without an ORDER BY clause, the
order of rows returned by an SQL query is undefined.
The following is an example of a SELECT query that returns a list of expensive books. The
query retrieves all rows from the Book table in which the price column contains a value greater
than 100.00. The result is sorted in ascending order by title. The asterisk (*) in the select
list indicates that all columns of the Book table should be included in the result set.
32
SELECT *
FROM Book
WHERE price > 100.00
ORDER BY title;
23. Explain subqueries with the help of examples.
Subqueries
Subquery or Inner query or Nested query is a query in a query. SQL subquery is usually added in
the WHERE Clause of the SQL statement. Most of the time, a subquery is used when you know
how to search for a value using a SELECT statement, but do not know the exact value in the
database.
Subqueries are an alternate way of returning data from multiple tables.
Subqueries can be used with the following SQL statements along with the comparison operators
like =, <, >, >=, <= etc.
SELECT
INSERT
UPDATE
DELETE
Subquery Example:
1) Usually, a subquery should return only one record, but sometimes it can also return multiple
records when used with operators like IN, NOT IN in the where clause. The query would be like,
SELECT first_name, last_name, subject FROM student_details WHERE games
NOT IN ('Cricket', 'Football');
Subquery output would be similar to:
first_name
------------Shekar
Priya
last_name subject
------------- ---------Gowda
Badminton
Chandra Chess
2) Lets consider the student_details table which we have used earlier. If you know the name of
the students who are studying science subject, you can get their id's by using this query below,
SELECT id, first_name FROM student_details WHERE first_name IN ('Rahul',
'Stephen');
but, if you do not know their names, then to get their id's you need to write the query in this
manner,
SELECT id, first_name FROM student_details WHERE first_name IN (SELECT
first_name FROM student_details WHERE subject= 'Science');
Subquery Output:
id
-------100
102
first_name
------------Rahul
Stephen
In the above sql statement, first the inner query is processed first and then the outer query is
processed.
33
3) Subquery can be used with INSERT statement to add rows of data from one or more tables to
another table. Lets try to group all the students who study Maths in a table 'maths_group'.
INSERT INTO maths_group(id, name) SELECT id, first_name || ' ' || last_name FROM
student_details WHERE subject= 'Maths'
4) A subquery can be used in the SELECT statement as follows. Lets use the product and
order_items table defined in the sql_joins section.
select p.product_name, p.supplier_name, (select order_id from order_items where
product_id = 101) as order_id from product p where p.product_id = 101
product_name
-----------------Television
supplier_name order_id
------------------ ---------Onida
5103
24. Explain types of join operator.
SQL Joins can be classified into Equi join and Non Equi join.
1) SQL Equi joins
It is a simple sql join condition which uses the equal sign as the comparison operator.
Two types of equi joins are SQL Outer join and SQL Inner join.
For example: You can get the information about a customer who purchased a product
and the quantity of product.
2) SQL Non equi joins
It is a sql join condition which makes use of some comparison operator other than the
equal sign like >, <, >=, <=
1) SQL Equi Joins:
An equi-join is further classified into two categories:
a) SQL Inner Join
b) SQL Outer Join
a) SQL Inner Join:
All the rows returned by the sql query satisfy the sql join condition specified.
For example: If you want to display the product information for each order the query will
be as given below. Since you are retrieving the data from two tables, you need to identify
the common column between these two tables, which is theproduct_id.
The query for this type of sql joins would be like,
SELECT order_id, product_name, unit_price, supplier_name, total_units
FROM product, order_items
WHERE order_items.product_id = product.product_id;
The columns must be referenced by the table name in the join condition, because
product_id is a column in both the tables and needs a way to be identified. This avoids
ambiguity in using the columns in the SQL SELECT statement.
The number of join conditions is (n-1), if there are more than two tables joined in a query
where 'n' is the number of tables involved. The rule must be true to avoid Cartesian
product.
We can also use aliases to reference the column name, then the above query would be
like,
SELECT o.order_id, p.product_name, p.unit_price, p.supplier_name,
o.total_units
FROM product p, order_items o
WHERE o.product_id = p.product_id;
34
b) SQL Outer Join:
This sql join condition returns all rows from both tables which satisfy the join condition along
with rows which do not satisfy the join condition from one of the tables. The sql outer join
operator in Oracle is ( + ) and is used on one side of the join condition only.
The syntax differs for different RDBMS implementation. Few of them represent the join
conditions as "sql left outer join", "sql right outer join".
If you want to display all the product data along with order items data, with null values displayed
for order items if a product has no order item, the sql query for outer join would be as shown
below:
SELECT p.product_id, p.product_name, o.order_id, o.total_units
FROM order_items o, product p
WHERE o.product_id (+) = p.product_id;
The output would be like,
product_id
100
101
102
103
104
product_name order_id total_units
Camera
Television
Refrigerator
Ipod
Mobile
5103
5101
5102
5100
10
5
25
30
NOTE:If the (+) operator is used in the left side of the join condition it is equivalent to left outer
join. If used on the right side of the join condition it is equivalent to right outer join.
SQL Self Join:
A Self Join is a type of sql join which is used to join a table to itself, particularly when the table
has a FOREIGN KEY that references its own PRIMARY KEY. It is necessary to ensure that the
join statement defines an alias for both copies of the table to avoid column ambiguity.
The below query is an example of a self join,
SELECT a.sales_person_id, a.name, a.manager_id, b.sales_person_id, b.name
FROM sales_person a, sales_person b
WHERE a.manager_id = b.sales_person_id;
2) SQL Non Equi Join:
A Non Equi Join is a SQL Join whose condition is established using all comparison operators
except the equal (=) operator. Like >=, <=, <, >
For example: If you want to find the names of students who are not studying either Economics,
the sql query would be like, (lets use student_details table defined earlier.)
SELECT first_name, last_name, subject
FROM student_details
WHERE subject != 'Economics'
The output would be something like,
first_name
last_name
subject
Anajali
Bhagwat
Maths
Shekar
Gowda
Maths
Rahul
Sharma
Science
35
Stephen
Fleming
Science
25. Explain correlated queries.
A query is called correlated subquery when both the inner query and the outer query are
interdependent. For every row processed by the inner query, the outer query is processed
as well. The inner query depends on the outer query before it can be processed.
SELECT p.product_name FROM product p
WHERE p.product_id = (SELECT o.product_id FROM order_items o
WHERE o.product_id = p.product_id);
The following subquery selects those employees whose salary is greater than the
minimum salary for their jobs.
select emp_last_name from emp where emp_salary > (select job_min_sal from job
where emp.job_key = job.job_key);
EMP_LAST_NAME
------king
jackson
korn
linus
tokheim
johnson
baker
coleman
brannigan
9 rows selected.
This is known as a correlated subquery because the subquery references the outer query
in the subqueries WHERE clause. Internally, correlated subqueries are very expensive to
process because the inner query must be executed for every row returned by the outer
query.
26.
Explain Derived Tables.
A "derived table" is essentially a statement-local temporary table created by means of a
subquery in the FROM clause of a SQL SELECT statement. It exists only in memory and
behaves like a standard view or table.
For example, assume an Oracle 9i database table is called "state_table" and has the
following row values in the "state" column.
State
CA
CA
CA
FL
If you used the following inner SELECT statement which includes a derived table to
evaluate the "state_table", you could return the count and percentage of each state. The
SQL has been written for Oracle 9i.
Select state, count(state) as State_Count,(count(state)/derived_table.tot_state_count) as
State_Percentage from state_table,
(select count(state) tot_state_count from state) derived_table
group by state, derived_table.tot_state_count;
The results of the query is displayed below:
36
State
CA
FL
State_Count
3
1
State_Percentage
0.75
0.25
Derived tables are useful when you need to generate aggregates in a table that would
otherwise contain dimension type data and join the resulting aggregate with detail level
facts in another table.
Additionally, the aggregate values in the derived tables can be used in the outer query's
WHERE clause (i.e., "where salary > average_salary", average_salary has been derived
by the subquery). These tables can also optimize a query's performance in some
circumstances, such as minimizing sorting when some DISTINCT values are needed
from some tables but not all. Finally, it might eliminate the need in some cases, to build
"local results" queries. This feature enables users to access this type of SQL construct in
an easy-to-build manner.
27. Explain stored procedures.
A stored procedure or in simple a proc is a named PL/SQL block which performs one
or more specific task. This is similar to a procedure in other programming languages.
A procedure has a header and a body. The header consists of the name of the procedure
and the parameters or variables passed to the procedure. The body consists or declaration
section, execution section and exception section similar to a general PL/SQL Block.
A procedure is similar to an anonymous PL/SQL Block but it is named for repeated
usage.
We can pass parameters to procedures in three ways.
1) IN-parameters
2) OUT-parameters
3) IN OUT-parameters
A procedure may or may not return any value.
General Syntax to create a procedure is:
CREATE [OR REPLACE] PROCEDURE proc_name [list of parameters]
IS
Declaration section
BEGIN
Execution section
EXCEPTION
Exception section
END;
28. Explain user defined functions with example.
A function is a named PL/SQL Block which is similar to a procedure. The major
difference between a procedure and a function is, a function must always return a value,
but a procedure may or may not return a value.
General Syntax to create a function is
CREATE [OR REPLACE] FUNCTION function_name [parameters]
RETURN return_datatype;
IS
Declaration_section
BEGIN
Execution_section
Return return_variable;
EXCEPTION
exception section
Return return_variable;
END;
37
29. What are the uses of index?
Index in sql is created on existing tables to retrieve the rows quickly.
When there are thousands of records in a table, retrieving information will take a long
time. Therefore indexes are created on columns which are accessed frequently, so that the
information can be retrieved quickly. Indexes can be created on a single column or a
group of columns. When a index is created, it first sorts the data and then it assigns a
ROWID for each row.
30. What are the uses of Views?
A VIEW is a virtual table, through which a selective portion of the data from one or more
tables can be seen. Views do not contain data of their own. They are used to restrict
access to the database or to hide data complexity. A view is stored as a SELECT
statement in the database. DML operations on a view like INSERT, UPDATE, DELETE
affects the data in the original table upon which the view is based.
31. Explain the use of triggers.
Triggers are stored programs, which are automatically executed or fired when some
events occur. Triggers are, in fact, written to be executed in response to any of the
following events:
A database manipulation (DML) statement (DELETE, INSERT, or UPDATE).
A database definition (DDL) statement (CREATE, ALTER, or DROP).
o
A database operation (SERVERERROR, LOGON, LOGOFF, STARTUP, or
SHUTDOWN).
Triggers could be defined on the table, view, schema, or database with which the event is
associated.
Benefits of Triggers
Triggers can be written for the following purposes:
Generating some derived column values automatically
Enforcing referential integrity
Event logging and storing information on table access
Auditing
Synchronous replication of tables
Imposing security authorizations
Preventing invalid transactions
32. Explain data control statement of SQL in brief.
A data control language (DCL) is a syntax similar to a computer programming
language used to control access to data stored in a database. In particular, it is a component
ofStructured Query Language (SQL).
Examples of DCL commands include:
GRANT to allow specified users to perform specified tasks.
REVOKE to cancel previously granted or denied permissions.
The operations for which privileges may be granted to or revoked from a user or role may
include CONNECT, SELECT, INSERT, UPDATE, DELETE, EXECUTE, and USAGE.
In the Oracle database, executing a DCL command issues an implicit commit. Hence you
cannot roll back the command.
33. Discuss the Boolean operators used in SQL queries.
38
The Boolean are those that are true or false. They returns a true or false values to
combine one or more true or false values.
Operator
Description
AND
Logical AND compares between two Booleans as expression and return true when both
expressions are true...
OR
Logical OR compares between two Booleans as expression and return true when one of the
expression is true...
NOT
Not takes a single Boolean as an argument and changes its value from false to true or from
true to false....
IN
The IN operator checks a value within a set of values separated by commas and retrieve the
rows from the table which are matching....
BETWEEN
The SQL BETWEEN operator tests an expression against a range. The range consists of a
beginning, followed by an AND keyword and an end expression....
ANY
ANY compares a value to each value in a list or results from a query and evaluates to true
if the result of an inner query contains at least one row....
ALL
ALL is used to select all records of a SELECT STATEMENT. It compares a value to every
value in a list or results from a query. The ALL must be preceded by the comparison
operators and evaluates to TRUE if the query returns no rows....
SOME
SOME compares a value to each value in a list or results from a query and evaluates to true
if the result of an inner query contains at least one row...
EXISTS
The EXISTS checks the existence of a result of a subquery. The EXISTS subquery tests
whether a subquery fetches at least one row. When no data is returned then this operator
returns 'FALSE'...
34. Define the following functions with example:a)count
b)avg
SQL COUNT (): This function returns the number of rows in the table that satisfies the
condition specified in the WHERE condition. If the WHERE condition is not specified,
then the query returns the total number of rows in the table.
For Example: If you want the number of employees in a particular department, the query
would be:
SELECT
COUNT
(*)
FROM
employee
WHERE dept = 'Electronics';
The output would be '2' rows.
If you want the total number of employees in all the department, the query would take the
form:
SELECT COUNT (*) FROM employee;
The output would be '5' rows.
SQL AVG(): This function is used to get the average value of a numeric column.
To get the average salary, the query would be
SELECT AVG (salary) FROM employee;
39
35. Differentiate the delete and truncate commands in SQL.
DELETE
The DELETE command is used to remove rows from a table. A WHERE clause can be used
to only remove some rows. If no WHERE condition is specified, all rows will be removed.
After performing a DELETE operation you need to COMMIT or ROLLBACK the
transaction to make the change permanent or to undo it. Note that this operation will cause all
DELETE triggers on the table to fire.
SQL> SELECT COUNT(*) FROM emp;
COUNT(*)
---------14
SQL> DELETE FROM emp WHERE job = 'CLERK';
4 rows deleted.
SQL> COMMIT;
Commit complete.
SQL> SELECT COUNT(*) FROM emp;
COUNT(*)
---------10
TRUNCATE
TRUNCATE removes all rows from a table. The operation cannot be rolled back and no triggers
will be fired. As such, TRUCATE is faster and doesn't use as much undo space as a DELETE.
SQL> TRUNCATE TABLE emp;
Table truncated.
SQL> SELECT COUNT(*) FROM emp;
COUNT(*)
---------0
36. Describe the following statements_
a)Grant
b)Revoke
40
DCL command
Data Control Language(DCL) is used to control privilege in Database. To perform any operation
in the database, such as for creating tables, sequences or views we need privileges. Privileges are
of two types,
System : creating session, table etc are all types of system privilege.
Object : any command or query to work on tables comes under object privilege.
DCL defines two commands,
Grant : Gives user access privileges to database.
Revoke : Take back permissions from user.
To Allow a User to create Session
grant create session to username;
To Allow a User to create Table
grant create table to username;
To provide User with some Space on Tablespace to store Table
alter user username quota unlimited on system;
To Grant all privilege to a User
grant sysdba to username
To Grant permission to Create any Table
grant create any table to username
To Grant permission to Drop any Table
grant drop any table to username
To take back Permissions
revoke create table from username
37. Give SQL statement which create a student table consisting of following fields
NAME CHAR(40)
CLASS CHAR (60)
MARKS NUMBER(4)
RANK CHAR(8)
CREATE TABLE student
( name char(40),
class char(60),
marks char(4),
rank char(8),
);
41
38.Describe advantages and disadvantages of views.
Advantages of views:
1. View the data without storing the data into the object.
2. Restict the view of a table i.e. can hide some of columns in the tables.
3. Join two or more tables and show it as one object to user.
4. Restict the access of a table so that nobody can insert the rows into the table.
Disadvatages:
1. Cannot use DML operations on this.
2. When table is dropped view becomes inactive.. it depends on the table objects.
3. It is an object, so it occupies space.
© Copyright 2026 Paperzz