Completely Solved C, C++ Programs Assignment.




Showing posts with label DBMS. Show all posts
Showing posts with label DBMS. Show all posts

The Relational Algebra

Filed Under:

  Relational algebra is a notation for representing the types of operations which can be performed on relational databases. It is used in a RDBMS as the intermediate language for query optimization.
A relation is a set of k-tuples, for some k called the arity of the relation. In general, names are given to the components of the tuple (a tuple corresponds to a record - Pascal or structure - C with fields corresponding to the names of the components). Note: this definition implies that each tuple is unique. Each relation is described by a schema which consists of a relation name and a list of attribute names - relation-name(attribute-list). R(A1, ..., An), R.Ai.
A relational algebra is an algebraic language based on a small number of operators which operate on relations (tables). It is the intermediate language used by a RDBMS. Queries are expressed by applying special operators to relations.

Figure 1: Relational Algebra
expression
::=
relation | monadic-expression | dyadic-expression
monadic-expression
::=
selection | projection | renaming
dyadic-expression
::=
expression diadic-operation expression
selection
::=
σselection-condition (relation-name)
projection
::=
π attribute - list ( relation - name )
renaming
::=
ρattribute-list(relation-name)
dyadic-operation
::=
U| − | × | ∩ | ÷ | |〉〈|join-condition
selection-condition
::=
logical-condition | comparison

Eight operations were originally defined for relations. Each of these creates a new relation from an existing relation or set of relations.

• Basic Operators
1. Selection: Selects a subset of tuples from a particular relation, based upon a specified selection condition. The selection condition is a boolean expression formed from the names of the attributes of the relation and constants.
2. Projection: Drops columns from a relation retaining only those in the attribute list.
3. Set union: Combines tuples of two relations with like attributes.

  • Both relations must have the same number of columns.
  • The names of the attributes are the same in both relations.
  • Attributes with the same name in both relations have the same domain.

4. Set difference: Finds tuples in two relations with like attributes which are in the first relation but not the second.
5. Cartesian product: Creates a new relation from all concatenations of two relations. NOTE: this is the most computationally expensive operator in the relational algebra.
Renaming: The attribute names in the attribute list replace the attribute names of the relation. ρS(A1,...,An)(R) is the same relation as R but its name is S with the attributes named. A1,...,An.

• Derived operators
1. Set intersection: Finds the common tuples in two relations with like attributes.
2. Divide: Takes two relations, with attributes {X1...XN,Y1...YM} and {Y1...YM} respectively, and returns a relation with attributes {X1...XN} representing all the tuples in the first with matched every tuple in the second relation.
3. Join: Creates new relation from all combinations of tuples in two relations with some matching attributes - R|〉〈|join-conditionS = σjoin-condition (R × S). While this relation has the potential to be computationally expensive (due to the cartesian product) the join-condition typically allows the operation to be relatively inexpensive.

  • The join defined above is called a theta-join.
  • Equijoins are joins where the join-condition only involves equalities.






Back to main directory:  DBMS



DATABASE SYSTEM ARCHITECTURES

Filed Under:

1. Client-Server Database Systems
A client is defined as a requester of services and a server is defined as the provider of services.
Today centralized systems act as server systems that satisfy requests generated by client systems.
Functionally database systems can be broadly divided into two parts:
• Front end: front end of a database system consists of tools such as SQL user interface, forms interfaces, reports generation tools, and analysis tools.
• Back end: The back end of a database system manages query evaluation and optimization, access structures, concurrency control and recovery management.



2. Parallel Systems
In parallel processing, many operations are performed simultaneously and the computational steps are performed sequentially. It can process thousands of transactions per second.
There are four types of Architectural Models for Parallel Processing:
• Shared Memory (tightly coupled) architecture: Multiple processors share secondary (disk) storage and also share primary memory.
• Shared Disk (loosely coupled) architecture: Multiple processors share secondary (disk) storage but each has their own primary memory.
• Shared Nothing: The processors share neither a common memory nor common disk.
• Hierarchical: this model is the combination of preceding three architectures.

3. Distributed Systems
Distributed database is a collection of multiple logically interrelated databases distributed over a computer network and a distributed database management system is a software system that manages a distributed database while making the distribution transparent to the user. Transparency means hiding the details of where the data is physically stored within the system.
Reasons for building a distributed database are sharing of data, autonomy, and availability.
Functions of distributed databases:
• Keeping track of data.
• Query Processing by a communication network.
• Security Management.
• Distributed Transaction Management
• Database Recovery.

Back to main directory:  DBMS



THREE-SCHEMA ARCHITECTURE OF DATABASE SYSTEMS

Filed Under:

The goal of Three-Schema architecture is to separate the user applications and physical database. In this architecture, schemas can be defined at the following three levels:
The internal level:- The internal level has an internal schema which describes the physical storage structure of the database.
The conceptual level:-The conceptual level has a conceptual schema, it describes the entities, data types, relationships, user operations and constraints.
The external level or view level:- The external or view level includes a number of external schemas or user views. It describes the part of the database that a particular user group is interested in and hides the rest of the database from that user group.




Back to main directory:  DBMS



DATA MODELS

Filed Under:

Data model is defined as the collection of conceptual tools for describing data, data relationships, data semantics and consistency constraints. There are following four Data Model exists.

THE HIERARCHICAL DATA MODEL
A hierarchical database consists of the following:
1. It contains nodes connected by branches same as the trees in datastructers.
2. The top node is called the root.
3. If multiple nodes appear at the top level, the nodes are called root segments.
4. The parent of node nx is a node directly above nx and connected to nx by a branch.
5. Each node (with the exception of the root) has exactly one parent.
6. The child of node nx is the node directly below nx and connected to nx by a branch.
7. One parent may have many children.

THE NETWORK DATA MODEL
Like the The Hierarchical Data Model the Network Data Model also consists of nodes and branches, but a child may have multiple parents within the network structure.

THE RELATIONAL DATA MODEL
The Relational Data Model has the relation at its heart, but then a whole series of rules governing keys, relationships, joins, functional dependencies, transitive dependencies, multi-valued dependencies, and modification anomalies. A relation is subject to the following rules:
1. Relation (file, table) is a two-dimensional table.
2. Attribute (i.e. field or data item) is a column in the table.
3. Each column in the table has a unique name within that table.
4. Each column is homogeneous. Thus the entries in any column are all of the same type (e.g. age, name, employee-number, etc).
5. Each column has a domain, the set of possible values that can appear in that column.
6. A Tuple (i.e. record) is a row in the table.
7. The order of the rows and columns is not important.
8. Values of a row all relate to some thing or portion of a thing.
9. Repeating groups (collections of logically related attributes that occur multiple times within one record occurrence) are not allowed.
10. Duplicate rows are not allowed (candidate keys are designed to prevent this).
11. Cells must be single-valued (but can be variable length). Single valued means the following:
o Cannot contain multiple values such as 'A1,B2,C3'.
o Cannot contain combined values such as 'ABC-XYZ' where 'ABC' means one thing and 'XYZ' another.



Object Oriented Model
In object oriented model information is represented in the form of objects as used in object oriented programming. Object Oriented Database Management Systems is a combination of object oriented programming language capabilities and database capabilities. It contains some properties like transparently persisted data, concurrency control, data recovery, associative queries, and other capabilities. Some object oriented programming languages are Java, C++, .NET, Visual Basic, Python etc. Most object databases also offer some kind of query language, allowing objects to be found by a more declarative programming approach.

Back to main directory:  DBMS



INTRODUCTION TO DATABASE

Filed Under:

DBMS stands for Database Management System. A DBMS consists of collection of interrelated data and a set of program to access that data. The collection of data is known as a database. A database consists of the data related to one organization. Prior to DBMS systems, the data was kept under the file system in forms of multiple files. The following are the disadvantages of the File system:-

1. Difficulty in Accessing data:- In the file system it is very difficult to find the data which is needed for some specific purpose. Like to get the average sale of the quarter needs to process all files for the quarter and then do some processing.
2. Data inconsistency and redundancy:- As the files and processing systems created by different vendors and programmers, so there is a inconsistency of data as different people prefer the different style of data handling. Also the different systems may use the different programming languages to develop the processing systems so the multiple copies of the same file kept under various places so redundancy is another problem we have with file system.
3. Security Problem:- There is a great risk of unauthroized person access the file system and get the data. So security is the major concern in the file system.
4. Integrity Problem:- The integrity issue is also a major concern as the data stored in the file can be changed easily. While creating files there is no specific rules checked while storing the data.

ADVANTAGES OF DATABASE MANAGEMENT SYSTEM:-
The following are the advantages of DBMS systems:-
1. A data can be validated before storing into the DBMS system.These rules for data validation are known as Constraints in DBMS.
2. Different users can be created with different rights for the database.So DBMS systems are more secure than the conventional file system.
3. The relationships of the data can also be stored along with the data which is not possible for the files.
4. A simple english like language SQL is introduced which helps to access data more efficiently and quickly.
5. Multiple users can access the data simultenously and DBMS system will take care the conflicts.
6. The dependent tasks can be controlled with transaction management facility of the DBMS. For example:- Transfering the cash from one account to second account consits of withdrawing the amount from one account and deposit in other. What if the application fails after the withdrawl so DBMS system will rollback the withdrawl automatically.

Back to main directory:  DBMS



Different Database Keys

Filed Under:

Databases use tables to organize information. Each table consists of a number of rows, each of which corresponds to a single database record. Databases keep all of these records through the use of keys.

Candidate Key
A candidate key is a combination of attributes that can be uniquely used to identify a database record without any extraneous data. Each table may have one or more candidate keys. One of these candidate keys is selected as the table primary key.
Alternately, Candidate Key is a column or group of columns that uniquely describe every row in a table.
For instance, in a table that describes people (employees, customers, club members, whatever), there are many columns that describe those people. If you accept the assertion that you can't have two people with the same name, one of your CKs could be the person's name. If you accept the assertion that you can't have two people with a given phone number, one of your CKs could be the phone number. A candidate key must possess the following properties:
  • Unique identification - For every row the value of the key must uniquely identify that row.
  • Non redundancy - No attribute in the key can be discarded without destroying the property of unique identification.
Surrogate Key
A Surrogate Key (SK) is an arbitrary value that is used solely by the database (and therefore by any programs that use that database) to uniquely identify a row. This can be a GUID, an "automagically" assigned number, or just some arbitrary value that happens to be unique for every row. SKs are guaranteed to be unique (that is part of their definition), so they are always CKs. Using an SK can be extremely convenient because it allows the database to function independently of any changes to the business rules that make other CKs unique.

Primary Key
A unique key or primary key is a candidate key to uniquely identify each row in a table. A unique key or primary key comprises a single column or set of columns. No two distinct rows in a table can have the same value (or combination of values) in those columns. Depending on its design, a table may have arbitrarily many unique keys but at most one primary key.
The value this key holds should be unique for each record in the database. For example, assume we have a table called Employees that contains personnel information for every employee in our firm. We’d need to select an appropriate primary key that would uniquely identify each employee. Your first thought might be to use the employee’s name.
This wouldn’t work out very well because it’s conceivable that you’d hire two employees with the same name. A better choice might be to use a unique employee ID number that you assign to each employee when they’re hired. Most organizations have used unique identifiers (employee ID, student ID, etc.).
Once you decide upon a primary key and set it up in the database, the database management system will enforce the uniqueness of the key. If you try to insert a record into a table with a primary key that duplicates an existing record, the insert will fail.
Most databases are also capable of generating their own primary keys. Microsoft Access, for example, may be configured to use the AutoNumber data type to assign a unique ID to each record in the table. While effective, this is a bad design practice because it leaves you with a meaningless value in each record in the table.

Alternate Key
An alternate key (or secondary key) is any candidate key which is not selected to be the primary key (PK).
For example, a relational database with a table "employee" could have attributes like "employee_id", "bank_acct_no", and so on. In this case, both "employee_id" and "bank_acct_no" serve as unique identifiers for a given employee, and could thus arguably be used for a primary key. Hence, both of them are called "candidate keys". If, for example, "bank_acct_no" was chosen as the primary key, "employee_id" would become the alternate key.

Foreign Keys
These keys are used to create relationships between tables. Natural relationships exist between tables in most database structures. Returning to our Employees database, let’s imagine that we wanted to add a table containing departmental information to the database. This new table might be called Departments and would contain a large amount of information about the department as a whole. We’d also want to include information about the employees in the department, but it would be redundant to have the same information in two tables (Employees and Departments). Instead, we can create a relationship between the two tables.
Let’s assume that the Departments table uses the Department Name column as the primary key. To create a relationship between the two tables, we add a new column to the Employees table called Department. We then fill in the name of the department to which each employee belongs. We also inform the database management system that the Department column in the Employees table is a foreign key that references the Departments table. The database will then enforce referential integrity by ensuring that all of the values in the Departments column of the Employees table have corresponding entries in the Departments table.
Note that there is no uniqueness constraint for a foreign key. We may have more than one employee belonging to a single department. Similarly, there’s no requirement that an entry in the Departments table have any corresponding entry in the Employees table. It is possible that we’d have a department with no employees.

Superkey
Definition: A superkey is a combination of attributes that can be uniquely used to identify a database record. A table might have many superkeys. Candidate keys are a special subset of superkeys that do not have any extraneous (unrelated) information in them.

Examples: Imagine a table with the fields , , and . This table has many possible superkeys. Three of these are , and . Of those listed, only is a candidate key, as the others contain information not necessary to uniquely identify records. 






Back to main directory:  DBMS



DATABASE MANAGEMENT SYSTEM

Filed Under:

1. Introduction to Database
   Advantages of Database Management System

2. Data Models
The Hierachical Data Model
The Network data Model
The Relational Data Model

5.Codd's Rules for Relational Database
7.Concept of Normalisation
First Normal Form
Second Normal Form
Third Normal Form
Boyce-Codd Normal Form(BCNF)
Fourth Normal Form
Fifth Normal Form (Projection-Join Normal Form)

8. Transactions in DBMS
9. Steps to Design Database for a System
10. The Relational Algebra



SQL(Structured Query Language)-Assignment

Filed Under: ,



SQL-Query performs on a Project Management Database system.

Filed Under: ,

Problem Statement- Query performs on a Project Management Database system.

Consider the following database:-
i)Employee(Fname,Lname,Ssn,Bdate,Address,Sex,Salary,Superssn,Dno)
ii)Department(Dname,Dnumber,Mgrssn)
iii)Project(Pname,Pnumber,Plocation,Dnumber)
iv)Workson(Empssn,Pnumber,Hours)

Given Queries:-
1.Find the name and address of the employees who work for the research department.
2.For every project located in ‘Stafford’, list the project number,the controlling department number
and the department manager’s last name and birth date.
3.Make a list of all project numbers for projects that involve an employee whose last name Smith,
either as a worker or as a manager of the department that controls the project.
4.Find all employees whose address is in Houston.
5.Show the resulting salaries if every employee working on the product x project is given a 10%
raise.
6.Retrieve a list of employees and the project they are working on, ordered by department and
within each department, ordered alphabetically by last name, first name.
7.Retrieve the names of the employees who have no departments.
8.List the names of manager who have atleast one department.
9.Retrieve the name of each employee who works on all the projects controlled by department
number 5.
10.For each project on which more than two employees work, retrieve the project number,the
project name, and the number of employees who work on the project.
11.For each department that has more than five employees, retrieve the department number and
the number of its employees who are making than $40,000.
12.Retrieve the names of all the employees who do not have supervisors.


Commands for table creations of the schemas in:-

i) SQL> create table Employee
2 ( fname varchar2(15) NOT NULL,
3 lname varchar2(15) NOT NULL,
4 ssn char(9) NOT NULL,
5 bdate date,
6 address varchar2(30),
7 sex char(1),
8 salary number(10,2),
9 superssn char(9),
10 dno number(1) NOT NULL,
11 PRIMARY KEY (ssn),
12 FOREIGN KEY (superssn) references Employee(ssn),
13 FOREIGN KEY (dno) references Department(dnumber) );
Table Created.

SQL> INSERT INTO Employee VALUES
(‘John’,’Smith’,’123456789’,’09-Jan-65’,’Houston’,’m’,30000,’333445555’,5);
1 row created.
SQL> INSERT INTO Employee VALUES
(‘Franklyn’,’Wong’,’333445555’,’08-Dec-55’,’Houston’,’m’,40000,’888665555’,5);
1 row created.
SQL> INSERT INTO Employee VALUES
(‘Alicia’,’Zelaya’,’999887777’,’19-Jul-68’,’Spring’,’f’,25000,’987654321’,4);
1 row created.
SQL> INSERT INTO Employee VALUES
(‘Jennifer’,’Wallace’,’987654321’,’20-Jun-61’,’Bellaire’,’f’,43000,’888665555’,4);
1 row created.
SQL> INSERT INTO Employee VALUES
(‘Vincent’,’Fernandez’,’666884444’,’15-Sep-62’,’Humble’,’m’,25000,’333445555’,5);
1 row created.
SQL> INSERT INTO Employee VALUES
(‘Joyce’,’English’,’453453453’,’31-Jul-72’,’Houston’,’f’,25000,’987654321’,4);
1 row created.
SQL> INSERT INTO Employee VALUES
(‘Ahmad’,’Jabbar’,’987987987’,’29-Mar-69’,’Houston’,’m’,25000,’987654321’,4);
1 row created.
SQL> INSERT INTO Employee VALUES
(‘James’,’Borg’,’888665555’,’10-Nov-67’,’Houston’,’m’,30000,’333445555’,1);
1 row created.


ii) SQL> create table Department
2 ( dname varchar2(15) NOT NULL,
3 dnumber number(1) NOT NULL,
4 mgrssn char(9) NOT NULL,
5 PRIMARY KEY (dname),
6 UNIQUE (dname),
7 FOREIGN KEY (mgrssn) references Employee(ssn) );
Table Created.

SQL> INSERT INTO Department VALUES (‘Research’ , 5 , ‘333445555’);
1 row created.
SQL> INSERT INTO Department VALUES (‘Administration’ , 4 , ‘987654321’);
1 row created.
SQL> INSERT INTO Department VALUES (‘Headquarters’ , 1 , ‘888665555’);
1 row created.


iii) SQL> create table Project
2 ( pname varchar2(15) NOT NULL,
3 pnumber number(1) NOT NULL,
4 plocation varchar2(15),
5 dnumber number(1) NOT NULL,
6 PRIMARY KEY (pnumber),
7 UNIQUE (pname),
8 FOREIGN KEY (dnum) references Department(dnumber) );
Table Created.

SQL> INSERT INTO Project VALUES (‘Productx’ , 1 , ‘Ballaire’ , 5);
1 row created.
SQL> INSERT INTO Project VALUES (‘Producty’ , 2 , ‘Sugarland’ , 5);
1 row created.
SQL> INSERT INTO Project VALUES (‘Productz’ , 3 , ‘Houston’ , 5);
1 row created.
SQL> INSERT INTO Project VALUES (‘Computerization’ , 10 , ‘Stafford’ , 4);
1 row created.
SQL> INSERT INTO Project VALUES (‘Reorganization’ , 20 , ‘Houston’ , 1);
1 row created.
SQL> INSERT INTO Project VALUES (‘Newbenefits’ , 30 , ‘Stafford’ , 4);
1 row created.


iv) SQL> create table Workson
2 ( empssn char(9) NOT NULL,
3 pnumber number(1) NOT NULL,
4 hours number(3,1) NOT NULL,
5 PRIMARY KEY (empssn,pnumber),
6 FOREIGN KEY (empssn) references Employee(ssn),
7 FOREIGN KEY (pnumber) references Project(pnumber) );
Table Created.

SQL> INSERT INTO Workson VALUES (‘123456789’ , 1 , 32.5);
1 row created.
SQL> INSERT INTO Workson VALUES (‘123456789’ , 2 , 7.5);
1 row created.
SQL> INSERT INTO Workson VALUES (‘666884444’ , 3 , 40);
1 row created.
SQL> INSERT INTO Workson VALUES (‘453453453’ , 1 , 20);
1 row created.
SQL> INSERT INTO Workson VALUES (‘453453453’ , 2 , 20);
1 row created.
SQL> INSERT INTO Workson VALUES (‘333445555’ , 2 , 10);
1 row created.
SQL> INSERT INTO Workson VALUES (‘333445555’ , 3 , 10);
1 row created.
SQL> INSERT INTO Workson VALUES (‘333445555’ , 10 , 10);
1 row created.
SQL> INSERT INTO Workson VALUES (‘333445555’ , 20 , 10);
1 row created.
SQL> INSERT INTO Workson VALUES (‘987987987’ , 10 , 35);
1 row created.
SQL> INSERT INTO Workson VALUES (‘987987987’ , 30 , 5);
1 row created.
SQL> INSERT INTO Workson VALUES (‘987654321’ , 30 , 20);
1 row created.
SQL> INSERT INTO Workson VALUES (‘987654321’ , 20 , 15);
1 row created.
SQL> INSERT INTO Workson VALUES (‘123456789’ , 3 , 10);
1 row created.
SQL> INSERT INTO Workson VALUES (‘333445555’ , 1 , 33.1);
1 row created.
SQL> INSERT INTO Workson VALUES (‘333445555’ , 30 , 15);
1 row created.


Solution of the queries:-

Query Number 1 :
Find the name and address of the employees who work for the research department.

SQL Statement
SQL> select fname,lname,address
2 from Employee,Department
3 where dname=’Research’ and
4 dnumber=dno;

Output to Query number 1

FNAME LNAME ADDRESS
---------------------- ---------------------- ---------------------------------
John Smith Houston
Franklyn Wong Houston
Vincent Fernandez Humble
Joyce English Houston


Query Number 2 :
For every project located in ‘Stafford’, list the project number,the controlling department number,
and the department manager’s last name and birth date.


SQL Statement
SQL> select pnumber,dnumber,lname,bdate
2 from Project,Department,Employee
3 where Department.dnumber=Project.dnumber and

4 mgrssn=ssn and
5 plocation=’Stafford’;

Output to Query number 2

PNUMBER DNUMBER LNAME BDATE
-------------- --------------- ---------------------- --------------------
10 4 Wallace 20-Jun-61
30 4 Wallace 20-Jun-61


Query Number 3 :
Make a list of all project numbers for projects that involve an employee whose last name Smith,
either as a worker or as a manager of the department that controls the project.

SQL Statement
SQL> (select distinct pnumber
2 from Project,Department,Employee
3 where Department.dnumber=Project.dnumber and
4 empssn=ssn and
5 Lname=’Smith’)
6 union
7 (select distinct pnumber
8 from Project,Workson,Employee
9 where Project.pnumber=Workson.pnumber and
10 empssn=ssn and
11 lname=’Smith’);

Output to Query number 3

PNUMBER
--------------
1
2
3
20
30


Query Number 4 :
Find all employees whose address is in Houston.

SQL Statement
SQL> select fname,lname
2 from Employee
3 where address like ‘Houston’;


Output to Query number 4

FNAME LNAME
------------------------- -------------------------
John Smith
Franklyn Wong
Joyce English
Ahmad Jabbar
James Borg

Query Number 5 :
Show the resulting salaries if every employee working on the product x project is given a 10%
raise.

SQL Statement
SQL> select fname,lname,1.1*salary
2 from Employee,Workson,Project
3 where ssn=empssn and
4 Workson.pnumber=Project.pnumber and
5 pname=’Productx’;

Output to Query number 5

FNAME LNAME 1.1*SALARY
-------------------------- ------------------------ ----------------
John Smith 33000
Joyce English 27500



Query Number 6 :
Retrieve a list of employees and the project they are working on, ordered by department and
within each department, ordered alphabetically by last name, first name.

SQL Statement
SQL> select dname,lname,fname,pname
2 from Department,Employee,Workson,Project
3 where dnumber=dno and
4 ssn=empssn and
5 Workson.pnumber=Project.pnumber
6 order by dname,lname,fname;

Output to Query number 6

DNAME LNAME FNAME PNAME
--------------------------- ------------------------ ------------------------ ----------------------------
Administration Jabbar Ahmad Computerization
Administration Jabbar Ahmad Newbenifits
Administration Wallace Jennifer Newbenifits
Administration Wallace Jennifer Reorganization
Administration Zelaya Alicia Computerization
Administration Zelaya Alicia Newbenifits
Headquarters Borg James Reorganization
Research English Joyce Productx
Research English Joyce Producty
Research Fernandez Vincent Productz
Research Smith John Productx
Research Smith John Producty
Research Smith John Computerization
Research Wong Franklyn Producty
Research Wong Franklyn Productz
Research Wong Franklyn Reorganization


Query Number 7 :
Retrieve the names of the employees who have no departments.

SQL Statement
SQL> select fname,lname
2 from Employee
3 where not exists(select *
4 from Department
5 where ssn=empssn);


Output to Query number 7

FNAME LNAME
------------------------- -------------------------
Alicia Zelaya
Vincent Fernandez
Joyce English
Ahmad Jabbar
James Borg


Query Number 8 :
List the names of manager who have atleast one department.

SQL Statement
SQL> select fname,lname
2 from Employee
3 where exists(select *
4 from Department
5 where ssn=empssn)
6 and
7 exists(select *
8 from Department
9 where ssn=empssn);

Output to Query number 8

FNAME LNAME
------------------------- -------------------------
Franklyn Wong
Jennifer Wallace

Query Number 9 :
Retrieve the name of each employee who works on all the projects controlled by department
number 5.

SQL Statement
SQL> select lname,fname
2 from Employee
3 where not exists(select *
4 from Workson b
5 where(b.number in (select pnumber
6 from Project
7 where dnumber=5))
8 and
9 c.pnumber=b.pnumber));

Output to Query number 9

LNAME FNAME
------------------------- -------------------------
Zelaya Alicia
Wallace Jennifer
Jabbar Ahmad
Borg James


Query Number 10 :
For each project on which more than two employees work, retrieve the project number,the
project name, and the number of employees who work on the project.

SQL Statement
SQL> select pnumber,pname,count(*)
2 from Project,Workson
3 where Project.pnumber=Workson.pnumber
4 group by pnumber,pname
5 having count(*) > 2;

Output to Query number 10

PNUMBER PNAME COUNT(*)
-------------- ------------------------- --------------
2 Producty 3
10 Computerization 3
20 Reorganization 3
30 Newbenifits 3


Query Number 11 :
For each department that has more than five employees, retrieve the department number and
the number of its employees who are making than $40,000.

SQL Statement
SQL> select dnumber,count(*)
2 from Department,Employee
3 where dnumber=dno
4 Salary > 40000 and
5 dno in (select dno
6 from Employee
7 group by dno
8 having count(*) > 5)
9 group by dnumber;


Output to Query number 11

DNUMBER COUNT(*)
-------------- --------------
4 3
5 4


Query Number 12 :
Retrieve the names of all the employees who do not have supervisors.

SQL Statement
SQL> select fname,lname
2 from Employee
3 where superssn is null;

Output to Query number 12

FNAME LNAME
---------------------- ----------------------
James Borg



Discussion:-
The above database created is used to find out different information bout a companies employee details, departments, projects and project allocation. We have solved some given queries using this database, some of which have alternatives methods.

Example:-
Query no. 7 as written above to Find the employee who have no department can also be done by selecting the name of the employee who has an entre in employee table but not in project allocation table (Workson) ,on assumption that an employee without being in a particular department can not get any project allocation so will not get an entry in Workson table.
  We can write this as follows:-
“select fname,lname from employee where ssn not in(select empssn from Workson);”
 This would also give us the same output we desire.
 Back to main directory: Software Practical | Structured Query Language | DBMS



SQL-Query performs on a Book Borrower Database system

Filed Under: ,

Problem Statement:- Query performs on a Book Borrower Database system

Consider the following employee database:-
i)Book(Bookid,Title,Author,Subject)
ii)Borrower(Bid,Bname)
iii)Borrows(Bookid,Bid,Date_of_issue,Date_of_return)

Given Queries:-
1.Give all books on Physics and Mathematics.
2.Find out the title and author of all the books issued to a person whose Bid=B001.
3.Find out the names of the person who has issued books written by C.J.Date.
4.Find all the books written by Maity Ghosh on Mathematics.
5.Find the total number of books in the library.
6.Find the name of the person who has borrowed one or more books on DBMS.

Commands for table creations of the schemas in:-
i) SQL> create table Book
2 ( bookid varchar2(4) primary key,
3 title varchar2(20) NOT NULL,
4 author varchar2(20) NOT NULL,
5 subject varchar2(20) NOT NULL );
Table Created.

Name Null? Type
----------------------------------------- -------- -------------
BOOKID NOT NULL VARCHAR2(4)
TITLE NOT NULL VARCHAR2(20)
AUTHOR NOT NULL VARCHAR2(20)
SUBJECT NOT NULL VARCHAR2(20)

SQL> INSERT INTO Book VALUES (‘C001’ , ‘DB1’ , ‘C.J.Date’ , ‘DBMS’);
1 row created.
SQL> INSERT INTO Book VALUES (‘C002’ , ‘MAT1’ , ‘Maity Ghosh’ , ‘MATH’);
1 row created.
SQL> INSERT INTO Book VALUES (‘C003’ , ‘DB2’ , ‘Korth’ , ‘DBMS’);
1 row created.
SQL> INSERT INTO Book VALUES (‘C004’ , ‘ECO’ , ‘Amartya Sen’ , ‘ECONOMICS’);
1 row created.
SQL> INSERT INTO Book VALUES (‘C005’ , ‘NET’ , ‘Forouzan’ , ‘NETWORKING’);
1 row created.
SQL> INSERT INTO Book VALUES (‘C006’ , ‘MAT2’ , ‘Ghosh Chakraborty’ , ‘MATH’);
1 row created.
SQL> INSERT INTO Book VALUES (‘C007’ , ‘MAT3’ , ‘S.N.De’ , ‘MATH’);
1 row created.
SQL> INSERT INTO Book VALUES (‘C008’ , ‘OS1’ , ‘Peter Galvin’ , ‘OPERATING SYSTEMS’);
1 row created.
SQL> INSERT INTO Book VALUES (‘C009’ , ‘PHY1’ , ‘Doyari Majumder Maity’ , ‘PHYSICS’);
1 row created.
SQL> INSERT INTO Book VALUES (‘C010’ , ‘ARC1’ , ‘J.P.Hayes’ , ‘ARCHITECTURE’);
1 row created.

BOOK TITLE AUTHOR SUBJECT
---- -------------------- -------------------- -----------------
C001 DB1 C.J.Date DBMS
C002 MAT1 Maity Ghosh MATH
C003 DB2 Korth DBMS
C004 ECO Amartya Sen ECONOMICS
C005 NET Forouzan NETWORKING
C006 MAT2 Ghosh Chakraborty MATH
C007 MAT3 S.N.De MATH
C008 OS1 Peter Galvin OPERATING SYSTEMS

ii) SQL> create table Borrower
2 ( bid varchar2(4) primary key,
3 name varchar2(20) );
Table Created.

Name Null? Type
----------------------------------------- -------- ------------
BID NOT NULL VARCHAR2(4)
NAME VARCHAR2(20)

SQL> INSERT INTO Borrower VALUES (‘B001’ , ‘Ranjan Mehra’);
1 row created.
SQL> INSERT INTO Borrower VALUES (‘B002’ , ‘Tanmoy Das’);
1 row created.
SQL> INSERT INTO Borrower VALUES (‘B003’ , ‘Tarun Saha’);
1 row created.
SQL> INSERT INTO Borrower VALUES (‘B004’ , ‘Sanjay Saha’);
1 row created.
SQL> INSERT INTO Borrower VALUES (‘B005’ , ‘Deep Dutta’);
1 row created.
SQL> INSERT INTO Borrower VALUES (‘B006’ , ‘Govind Sarkar’);
1 row created.



BID NAME
---- --------------
B001 Ranjan Mehra
B002 Tanmoy Das
B003 Tarun Saha
B004 Sanjay Saha
B005 Deep Dutta
B006 Govind Sarkar

iii) SQL> create table Borrows
2 ( bookid varchar2(4),
3 bid varchar2(4),
4 date_of_issue date,
5 date_of_return date,
6 constraints fk_book_bookid
7 FOREIGN KEY (bookid) references Book(bookid),
8 constraints fk_borrower_bid
9 FOREIGN KEY (bid) references Borrower(bid) );
Table Created.

Name Null? Type
----------------------------------------- -------- -----------
BOOKID VARCHAR2(4)
BID VARCHAR2(4)
DATE_OF_ISSUE DATE
DATE_OF_RETURN DATE

SQL> INSERT INTO Borrows VALUES (‘C001’ , ‘B001’ , ’02-May-09’ , ’09-May-09’);
1 row created.
SQL> INSERT INTO Borrows VALUES (‘C002’ , ‘B002’ , ’03-May-09’ , ’10-May-09’);
1 row created.
SQL> INSERT INTO Borrows VALUES (‘C003’ , ‘B003’ , ’03-May-09’ , ’10-May-09’);
1 row created.
SQL> INSERT INTO Borrows VALUES (‘C001’ , ‘B005’ , ’04-May-09’ , ’11-May-09’);
1 row created.
SQL> INSERT INTO Borrows VALUES (‘C009’ , ‘B006’ , ’05-May-09’ , ’12-May-09’);
1 row created.
SQL> INSERT INTO Borrows VALUES (‘C003’ , ‘B001’ , ’07-May-09’ , ’14-May-09’);
1 row created.

BOOK BID DATE_OF_I DATE_OF_R
---- ---- --------- ---------
C001 B001 02-MAY-09 09-MAY-09
C002 B002 03-MAY-09 10-MAY-09
C003 B003 03-MAY-09 10-MAY-09
C001 B005 04-MAY-09 11-MAY-09
C003 B001 07-MAY-09 14-MAY-09


Solution of the queries:-

Query Number 1 :
Give all books on Physics and Mathematics.

SQL Statement
SQL> select bookid,title
2 from Book
3 where subject=’PHYSICS’ or subject=’MATH’;

Output to Query number 1

BOOK TITLE
--------- ----------------------
C002 MAT1
C006 MAT2
C007 MAT3
C009 PHY1


Query Number 2 :
Find out the title and author of all the books issued to a person whose Bid=B001.

SQL Statement
SQL> select title,author
2 from Book,Borrows
3 where Book.bookid=Borrows.bookid and
4 bid=’B001’;

Output to Query number 2

TITLE AUTHOR
---------------------- -----------------------
DB1 C.J.Date
DB2 Korth


Query Number 3 :
Find out the names of the person who has issued books written by C.J.Date.

SQL Statement
SQL> select distinct bname
2 from Borrower,Borrows,Book
3 where Borrower.bid=Borrows.bid and
4 Borrows.bookid=Book.bookid and
5 author=’C.J.Date’;

Output to Query number 3

BNAME
-----------------------------
Deep Dutta
Ranjan Mehra



Query Number 4 :
Find all the books written by Maity Ghosh on Mathematics.

SQL Statement
SQL> select title
2 from Book
3 where author=’Maity Ghosh’ and
4 subject=’MATH’;

Output to Query number 4

TITLE
-----------------------------
MAT1


Query Number 5 :
Find the total number of books in the library.

SQL Statement
SQL> select count(bookid) total_no_of_books
2 from Book;

Output to Query number 5

TOTAL_NO_OF_BOOKS
--------------------------------
10


Query Number 6 :
Find the name of the person who has borrowed one or more books on DBMS.

SQL Statement
SQL> select distinct bname
2 from Borrower,Borrows,Book
3 where Borrower.bid=Borrows.bid and
4 Borrows.bookid=Book.bookid and
5 subject=’DBMS’;

Output to Query number 6

BNAME
-----------------------------
Deep Dutta
Ranjan Mehra
Tarun Saha


Discussion:-
The above database created is used to find out different information about a libraries books, borrowers and borrows.
We have solved some given queries using this database, some of which have alternative methods.
Example:-
Query no. 6 as written above to find the name of the person who has borrowed one or more books on DBMS can also be done by selecting the borrower name whose id is the same with the id of borrower who borrowed the book whose book id is the same with that of the book with name ‘DBMS’.
We can write this as follows:-
“select bname from borrower where bid in(select bid from borrows where bookid in(select bookid from book where subject='DBMS'));”

This would also give us the same output we desire.
 Back to main directory: Software Practical | Structured Query Language | DBMS



SQL-Query performs on a Hospital Management Database system

Filed Under: ,

Problem Statement:- Query performs on a Hospital Management Database system

Consider the following employee database:-
i)Physician(Phregno,Phname,Phadd,Phtelno)
ii)Patient(Ptname,Ptadd)
iii)Visits(Phregno,Ptname,Date_of_visit,Feescharged)

Given Queries:-
1.Calculate the total fees obtained by the physicians.Also print the registration number,name and
address of the physician.
2.Find the name of the physicians and there telephone numbers who have visited at least 1 patient.
3.Find the name of the physicians with their telephone numbers whom has been visited by only
patient.
4.Find the names of the patients and their address who have visited to more than one physician.
5.Find the registration number of the physician who has been visited by more than one patient in
the month of November.
6.Find the name and registration number of the physician who has not been visited by any of the
patients.

Commands for table creations of the schemas in:-
i) SQL> create table Physician
2 ( phregno varchar2(5),
3 phname varchar2(15) NOT NULL,
4 phadd varchar2(20) NOT NULL,
5 phtelno number(9),
6 PRIMARY KEY(phreg no));
Table Created.

Name Null? Type
----------------------------------------- -------- ------------
PHREGNO NOT NULL VARCHAR2(5)
PHNAME NOT NULL VARCHAR2(15)
PHADD NOT NULL VARCHAR2(20)
PHTELNO NUMBER(9)

SQL> INSERT INTO Physician VALUES (‘P1001’ , ‘Asim Mitra’ , ‘Baranagar’ , 23438976);
1 row created.
SQL> INSERT INTO Physician VALUES (‘P1002’ , ‘Vikram Singh’ , ‘Park Circus’, 21234567);
1 row created.
SQL> INSERT INTO Physician VALUES (‘P1003’ , ‘S.K.Gupta’ , ‘Kankurgachi’ , 27651290);
1 row created.
SQL> INSERT INTO Physician VALUES (‘P1004’ , ‘Aniruddha Roy’ , ‘Salt lake’ , 23376721);
1 row created.
SQL> INSERT INTO Physician VALUES (‘P1005’ , ‘Devi Shetty’ , ‘Alipur’ , 26753400);
1 row created.
SQL> INSERT INTO Physician VALUES (‘P1006’ , ‘Sougata Basu’ , ‘Sealdah’ , 25670911);

PHREG PHNAME PHADD PHTELNO
----- --------------- -------------------- ----------
P1001 Asim Mitra Baranagar 23438976
P1002 Vikram Singh Park Circus 21234567
P1003 S.K.Gupta Kankurgachi 27651290
P1004 Aniruddha Roy Salt lake 23376721
P1005 Devi Shetty Alipur 26753400
P1006 Sougata Basu Sealdah 25670911

1 row created.
ii) SQL> create table Patient
2 ( ptname varchar2(15),
3 ptadd varchar2(20) NOT NULL,
4 PRIMARY KEY(ptname) );
Table Created.
Name Null? Type
----------------------------------------- -------- ------------
PTNAME NOT NULL VARCHAR2(15)
PTADD NOT NULL VARCHAR2(20)

SQL> INSERT INTO Patient VALUES (‘Vikash’ , ‘Salt lake’);
1 row created.
SQL> INSERT INTO Patient VALUES (‘Salim’ , ‘Moulali’);
1 row created.
SQL> INSERT INTO Patient VALUES (‘Abhirup’ , ‘Garia’);
1 row created.
SQL> INSERT INTO Patient VALUES (‘Akash’ , ‘Hedua’);
1 row created.
SQL> INSERT INTO Patient VALUES (‘Shyam’ , ‘Gariahat’);
1 row created.
SQL> INSERT INTO Patient VALUES (‘Jasbir’ , ‘Ultadanga’);
1 row created.
PTNAME PTADD
--------------- ---------
Vikash Salt lake
Salim Moulali
Abhirup Garia
Akash Hedua
Shyam Gariahat


iii) SQL> create table Visits
2 ( phregno varchar2(5),
3 ptname varchar2(15),
4 date_of_visit date,
5 feescharged number(5) NOT NULL,
6 PRIMARY KEY(phregno,ptname,date_of_visit),
7 FOREIGN KEY (phregno) references Physician,
8 FOREIGN KEY (ptname) references Patient );
Table Created.

Name Null? Type
----------------------------------------- -------- -------------
PHY_NO NOT NULL NUMBER(5)
P_NAME NOT NULL VARCHAR2(20)
DATE_OF_VISIT NOT NULL VARCHAR2(12)
FEES NUMBER(4)

SQL> INSERT INTO Visits VALUES (‘P1003’ , ‘Jasbir’ , ’23-Mar-09’ , 450);
1 row created.
SQL> INSERT INTO Visits VALUES (‘P1001’ , ‘Shyam’ , ’29-Jul-09’ , 700);
1 row created.
SQL> INSERT INTO Visits VALUES (‘P1001’ , ‘Akash’ , ’05-May-09’ , 300);
1 row created.
SQL> INSERT INTO Visits VALUES (‘P1002’ , ‘Vikash’ , ’02-Apr-09’ , 650);
1 row created.
SQL> INSERT INTO Visits VALUES (‘P1002’ , ‘Salim’ , ’01-Jan-09’ , 700);
1 row created.
SQL> INSERT INTO Visits VALUES (‘P1005’ , ‘Jasbir’ , ’20-Nov-09’ , 800);
1 row created.
SQL> INSERT INTO Visits VALUES (‘P1005’ , ‘Vikash’ , ’10-Nov-09’ , 800);
1 row created.
SQL> INSERT INTO Visits VALUES (‘P1005’ , ‘Akash’ , ’25-Dec-09’ , 650);
1 row created.
SQL> INSERT INTO Visits VALUES (‘P1004’ , ‘Salim’ , ’17-Oct-09’ , 500);
1 row created.
SQL> INSERT INTO Visits VALUES (‘P1004’ , ‘Salim’ , ’17-Jun-09’ , 800);
1 row created.



PHREG PTNAME DATE_OF_V FEESCHARGED
----- --------------- --------- -----------
P1001 Shyam 29-JUL-09 700
P1001 Akash 05-MAY-09 300
P1002 Vikash 02-APR-09 650
P1002 Salim 01-JAN-09 700
P1005 Vikash 10-NOV-09 800
P1004 Salim 17-OCT-09 500
P1004 Salim 17-JUN-09 800

Solution of Queries:-

Query Number 1 :
Calculate the total fees obtained by the physicians.Also print the registration number,name and
address of the physician.

SQL Statement
SQL> select v.phregno “REGIS”, phname “NAME”, phadd “ADDRESS”, sum(feescharged) “TOTAL
2 FEES”
3 from Physician p,Visits v
4 where p.phregno=v.phregno
5 group by v.phregno,phname,phadd;

Output to Query number 1

REGIS NAME ADDRESS TOTAL FEES
-------- -------------------------- ------------------------- ----------------
P1001 Asim Mitra Baranagar 1000
P1002 Vikram Singh Park Circus 1350
P1003 S.K.Gupta Kankurgachi 450
P1004 Aniruddha Roy Salt lake 1300
P1005 Devi Shetty Alipur 2250

Query Number 2 :
Find the name of the physicians and there telephone numbers who have visited at least 1 patient.

SQL Statement
SQL> select phname,phtelno
2 from Physician
3 where phregno in (select phregno
4 from Visits
5 group by phregno
6 having count(ptname)>=(select count(ptname)
7 from Visits
8 group by(phregno)));

Output to Query number 2

PHNAME PHTELNO
-------------------------- --------------
Asim Mitra 23438967
Vikram Singh 21234567
S.K.Gupta 27651290
Aniruddha Roy 23376721
Devi Shetty 26753400



Query Number 3 :
Find the name of the physicians with their telephone numbers whom has been visited by only patient.

SQL Statement
SQL> select phname,phtelno,count(v.phregno)
2 from Physician p, Visits v
3 where p.phregno=v.phregno
4 group by phname,phtelno
5 having count(v.phregno)=1;


Output to Query number 3

PHNAME PHTELNO COUNT(V.PHREGNO)
-------------------- -------------- -----------------------------
S.K.Gupta 27651290 1



Query Number 4 :
Find the names of the patients and their address who have visited to more than one physician.

SQL Statement
SQL> select t.ptname,t.ptadd,count(v.phregno)
2 from Patient t, Visits v
3 where t.ptname=v.ptname
4 group by t.ptname,t.ptadd
5 having count(v.phregno) > 1;

Output to Query number 4

PTNAME PTADD COUNT(V.PHREGNO)
----------------------------- ------------------------ ----------------------------
Akash Hedua 2
Jasbir Ultadanga 2
Salim Moulali 3
Vikash Salt lake 2

Query Number 5 :
Find the registration number of the physician who has been visited by more than one patient in
the month of November.

SQL Statement
SQL> select v.phregno,count(v.ptname)
2 from Visits v, Physician p
3 where p.phregno=v.phregno and
4 to_char(v.date_of_visit, ’MON’)=’NOV’
5 group by v.phregno
6 having count(v.ptname) > 1;

Output to Query number 5

PHREG COUNT(V.PTNAME)
--------- --------------------------
P1001 2

Query Number 6 :
Find the suppliers who live in the same city as parts.

SQL Statement
SQL> select p.phregno, p.phnname
2 from Physician p
3 where p.phregno not in (select v.phregno
4 from Visits v);

Output to Query number 6

PHREG PHNAME
--------- -------------------------
P1006 Sougata Basu

Discussion-
The above database created is used to find out different information about a hospital’s physicians, patients and visits.
We have solved some given queries using this database, some of which have alternative methods.
Example:-
Query no. 2 as written above to find the name of the physicians and there telephone numbers who have visited at least 1 patient can also be done by selecting physicians except physicians who have record in physician table but not in visits table( on assumption that physicians who did not visited any patient will not get entered in visits table).
We can write this as follows:-
“select phname,phtel_no from physician where phregno not in(select phregno from physician minus select phregno from visits);”
This would also give us the same output we desire.
 Back to main directory: Software Practical | Structured Query Language | DBMS