Você está na página 1de 9

Database Management System

Homework type/no: #2 . Course code: CSE301


Course instructor: Lect.Vijay kumar Garg Course tutor:
Date of allotment: Date of
submission: 29/09/2010
Student roll no: RB2805A21 Section no: B2805

Declaration:
I declare that this assignment is my individual work. I have not copied from any other student’s
work or from any other source except where due acknowledgment is made explicitly in the text,
nor has been written for me another person.
Student’s signature:- Rahul Keshri

Evaluator’s comments:
Marks obtained _____________________ out of ______________________________
Content of home work should start from this page only:
CSE301
Homework: 2
DOA :-------------- DOS:---------------
PART-A

Question 1: Why do we use indexing? Give a suitable example in support of your answer.
Ans Indexing is a technique for improving database performance. The many types of index
share the common property that they eliminate the need to examine every entry when running a
query. In large databases, this can reduce query time/cost by orders of magnitude. The simplest
form of index is a sorted list of values that can be searched using a binary search with an
adjacent reference to the location of the entry, analogous to the index in the back of a book. The
same data can have multiple indexes (an employee database could be indexed by last name
and hire date.)

Indexes affect performance, but not results. Database designers can add or remove indexes
without changing application logic, reducing maintenance costs as the database grows and
database usage evolves.

Given a particular query, the DBMS' query optimizer is responsible for devising the most
efficient strategy for finding matching data. The optimizer decides which index or indexes to use,
how to combine data from different parts of the database, how to provide data in the order
requested, etc.

Indexes can speed up data access, but they consume space in the database, and must be
updated each time the data are altered. Indexes therefore can speed data access but slow data
maintenance. These two properties determine whether a given index is worth the cost.

Question2: Under what circumstances, we will use foreign key? Give an example.

Ans One of the difficulties involved in managing a SQL Server database is that
certain types of database changes require that you drop and re-create tables. Usually,
when you are in the initial stages of defining your database structure, this is not too
much of a problem. However, once the database design has settled down a little and
all your foreign keys and declarative referential integrity is in place it can be quite
painful.
Let's say for example that you have a central table to which several other tables have
foreign keys and you want to add a bit field to that table. Well, you can't add a bit
field without recreating the table. So, you will need to perform all of the following
tasks to achieve this:
• Remove the foreign keys from the other tables.
• Drop the required table.
• Recreate the table with the new field.
• Add the foreign keys back to the other tables.
If you have data in the table you need to drop you will also need to save and recreate
that.
This whole task can become extremely arduous for large databases and where there
are many foreign keys. It can easily get to a point where you spend a great deal of
time recording and destroying and then re-creating foreign keys just so you can spend
a couple of minutes changing a table or two.
Faced with this sort of situation (a database with over 120 foreign keys) and needing
to modify a few tables I decided to spend a little while coming up with a better way to
handle this. That is to say, some way to not have to do it all manually.
The first step in the process seemed to be, to make sure I could restore any foreign
keys that I removed. To approach this problem I consulted some SQL manuals,
looked at saving information somewhere or doing some other crazy dynamic thing to
neatly allow me to restore foreign keys. After some furious research I grabbed a
coffee, took a deep breath and decided to use SQL Server's built In 'Generate SQL'
functionality to dump the SQL required to create all the foreign keys out to a SQL
script. It's an approach that's simple and required no work on my part to implement.
Simply right click on some object in your database (in Enterprise Manager) and select
Generate SQL Scripts. You then make sure you have selected all the tables in the
database (I find it easiest to just do all of them), then you make sure you the
'Keys/DRI' option selected but you have 'object drop' and 'object creation' turned off.
This will generate a script for the selected items (all the tables) that only generates all
their foreign key constraints. Save this script somewhere safe.
OK, so now we have a way to create all the foreign keys again, given that we can
delete them. At this point I started snooping around the system tables and catalogue
stored procedures. I figured the easiest way I could get all the required information
about the existing foreign keys was to use the sp_fkeys stored procedure. This stored
procedure returnes more than enough information about foreign keys. Certainly
enough information for me to be able to destroy them .
The only problem was that I needed to pass a table name to the sp_fkeys stored
procedure to get the data about the foreign keys for that table. This simply resulted
with me opening another cursor against one of the system tables so that I could get a
complete list of the User tables (SELECT name FROM sysobjects WHERE Type =
'U' ORDER BY name). Now that I could extract the information about each foreign
key I figured the easiest thing I could do with it would be to place it into a temporary
table. This would also allow me review the data I was collecting before I wrote the
code to start destroying things.
So, I added a little code to create a table that matched the data returned by the
sp_fkeys stored procedure.
CREATE TABLE #tempFK (
PKTABLE_QUALIFIER varchar(64),
PKTABLE_OWNER varchar(64),
PKTABLE_NAME varchar(64),
PKCOLUMN_NAME varchar(64),
FKTABLE_QUALIFIER varchar(64),
FKTABLE_OWNER varchar(64),
FKTABLE_NAME varchar(64),
FKCOLUMN_NAME varchar(64),
KEY_SEQ int,
UPDATE_RULE int,
DELETE_RULE int,
FK_NAME varchar(64),
PK_NAME varchar(64))

Question3: Produces a new relation with some of the attributes of relation and remove
duplicate tuples, give two different examples.
Ans The relational model is conceptually simple and more importantly based on
mathematical theory of relation. It also frees the users from details of storage structure
and access methods.
The relational model like all other models consists of three basic components
Advantages of Relational approach

The popularity of the relational database approach has been apart from access of
availability of a large variety of products also because it has certain inherent
advantages.

1. Ease of use: The revision of any information as tables consisting 0f rows and
columns is quite natural and therefore even first time users find it attractive.

2. 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.

3. Precision: The usage of relational algebra and relational calculus in the


manipulation of he relations between the tables ensures that there is no ambiguity,
which may otherwise arise in establishing the linkages in a complicated network type
database.

4. Security: Security control and authorization can also be implemented more easily
by moving sensitive attributes in a given table into a separate relation with its own
authorization controls. If authorization requirement permits, a particular attribute
could be joined back with others to enable full information retrieval.
5. Data Independence: Data independence is achieved more easily with normalization
structure used in a relational database than in the more complicated tree or network
structure.

6. Data Manipulation Language: The possibility of responding to ad-hoc query by


means of a language based on relational algebra and relational calculus is easy in the
relational database approach. For data organized in other structure the query language
either becomes complex or extremely limited in its capabilities.

Disadvantages of Relational Approach

One should not get carried way into believing that there can be no alternative to the
RDBMS. This is not so. 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 are
voluminous, the performance in responding to queries is definitely degraded. It must
be appreciated that the simplicity in the relational database approach arises in the
logical view. 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.

While the relational database approach is a logically attractive, commercially feasible


approach, but if the data is for example naturally organized in a hierarchical manner
and stored as such, the hierarchical approach may give better results. It is helpful to
have a summary view of the differences between the relational and the non-relational
approach in the following section.

PART-B

Question 4: Can we use a virtual table for security purpose? Justify your answer and give
an example to create a view.
Ans Databases may store relational tables/indexes in memory or on hard disk in one of many
forms:
ordered/unordered flat files
ISAM
heaps
hash buckets
logically-blocked files
B+ trees
The most commonly used[citation needed] are B+ trees and ISAM.
Object databases use a range of storage mechanisms. Some use virtual memory-mapped files to
make the native language (C++, Java etc.) objects persistent. This can be highly efficient but it
can make multi-language access more difficult. Others disassemble objects into fixed- and
varying-length components that are then clustered in fixed sized blocks on disk and reassembled
into the appropriate format on either the client or server address space. Another popular technique
involves storing the objects in tuples (much like a relational database) which the database server
then reassembles into objects for the client.[citation needed]
Other techniques include clustering by category (such as grouping data by month, or location),
storing pre-computed query results, known as materialized views, partitioning data by range (e.g.,
a data range) or by hash.
Memory management and storage topology can be important design choices for database
designers as well. Just as normalization is used to reduce storage requirements and improve
database designs, conversely denormalization is often used to reduce join complexity and reduce
query execution time.

Question 5: write an SQL query without using a with clause , to find all branches where the
total account deposit is less than the average total account deposit at all branches
a) Using a nested query in the from clause
CREATE TABLE t1 (s1 INT, s2 CHAR(5), s3 FLOAT);
Here is how to use a subquery in the FROM clause, using the example table:
INSERT INTO t1 VALUES (1,'1',1.0);
INSERT INTO t1 VALUES (2,'2',2.0);
SELECT sb1,sb2,sb3
FROM (SELECT s1 AS sb1, s2 AS sb2, s3*2 AS sb3 FROM t1) AS sb
WHERE sb1 > 1;
Here is another example: Suppose that you want to know the average of a set of sums for a
grouped table. This does not work:

SELECT AVG(SUM(column1)) FROM t1 GROUP BY column1;


However, this query provides the desired information:

SELECT AVG(sum_column1)
FROM (SELECT SUM(column1) AS sum_column1
FROM t1 GROUP BY column1) AS t1;
Notice that the column name used within the subquery (sum_column1) is recognized in the outer
query.

Subqueries in the FROM clause can return a scalar, column, row, or table. Subqueries in the
FROM clause cannot be correlated subqueries, unless used within the ON clause of a JOIN
operation.
Subqueries in the FROM clause are executed even for the EXPLAIN statement (that is, derived
temporary tables are built). This occurs because upper-level queries need information about all
tables during the optimization phase, and the table represented by a subquery in the FROM
clause is unavailable unless the subquery is executed.
b) Using a nested query in a Having clause ?
The ORDER BY clause is optional. If used, it must be the last clause in the SELECT statement.
The ORDER BY clause requests sorting for the results of a query.
When the ORDER BY clause is missing, the result rows from a query have no defined order
(they are unordered). The ORDER BY clause defines the ordering of rows based on columns
from the SELECT clause. The ORDER BY clause has the following general format:

ORDER BY column-1 [ASC|DESC] [ column-2 [ASC|DESC] ] ...


column-1, column-2, ... are column names specified (or implied) in the select list. If a select
column is renamed (given a new name in the select entry), the new name is used in the ORDER
BY list. ASC and DESC request ascending or descending sort for a column. ASC is the default.
ORDER BY sorts rows using the ordering columns in left-to-right, major-to-minor order. The
rows are sorted first on the first column name in the list. If there are any duplicate values for the
first column, the duplicates are sorted on the second column (within the first column sort) in the
Order By list, and so on. There is no defined inner ordering for rows that have duplicate values
for all Order By columns.

Database nulls require special processing in ORDER BY. A null column sorts higher than all
regular values; this is reversed for DESC.

In sorting, nulls are considered duplicates of each other for ORDER BY. Sorting on hidden
information makes no sense in utilizing the results of a query. This is also why SQL only allows
select list columns in ORDER BY.

For convenience when using expressions in the select list, select items can be specified by
number (starting with 1). Names and numbers can be intermixed.
Example queries:
SELECT * FROM sp ORDER BY 3 DESC
sno pno qty
S1 P1 NULL
S3 P1 1000
S3 P2 200
S2 P1 200
SELECT name, city FROM s ORDER BY name
name city
John London
Mario Rome
Pierre Paris
SELECT * FROM sp ORDER BY qty DESC, sno
sno pno qty
S1 P1 NULL
S3 P1 1000
S2 P1 200
S3 P2 200

Question 6: Consider the table EMPLOYEE and Department with following fields:
Employee( Emp_id,Emp_name, Dept_no, salary)
Department(dep_no, Dept_name,Location)
Perform the following computations on table data:
a) List all the employees whose location is ‘Pune’ and dept_name is ‘Computer’.
b) Count the total number of departments. Also count the total number of employees
whose dept_name is ‘computer’
c) Add a new department ‘R&D’ in the database.
d) List the names of employees whose salary is greater than 50000 and dept_ name is
‘computer'.
e) List the names of employees having maximum and minimum salary
f) Now change the department name from ‘computer’ to ‘software design’, wherever
applicable in the table.

Ans:- create table Employee( Emp_id varchar(8),Emp_name char(8), Dept_no varchar(10)


primary key, salary number(8,0));

insert into employee values('007', ' pratibha' ,'A10801670',30,000);

create table Department(dept_no varchar(8), Dept_name varchar(8),Location varchar(8), foreign


key(dept_no) references employee(dept_no));

insert into dept values('A10801670','deposit','pilibhit');

A. select employee.emp_name from employee join department on employee.


Dept_name=department. Dept_name where dept_name='account' and location='pune';

B.
a) select count( distinct dept_name) as department from dept;
b) select count(eply.emp_name) from employee join dept on employee. Dept_name=department.
Dept_name where dept_name=‘computer’;

C. insert into dept (dept_name) values('R&D');

D.select employee.emp_name from employee join department on employee.


Dept_name=department. Dept_name where dept_name='computer' and salary>50000;

E. select Emp_name ,salary from employee where salary=(select max(salary) from employee) or
salary=(select min(salary) from employee);
F. update department set dept_na.

Você também pode gostar