DBMS 7
DBMS 7
Ans: SQL stands for Structured Query Language. SQL is a database computer language designed for
managing data in relational database management systems (RDBMS), and originally based upon Relational Algebra.
SQL was one of the first languages for Edgar F. Codd's relational model in his influential 1970 paper, "A Relational
Model of Data for Large Shared Data Banks" and became the most widely used language for relational databases.
IBM developed SQL in mid of 1970’s.
Oracle incorporated in the year 1979.
SQL used by IBM/DB2 and DS Database Systems.
SQL adopted as standard language for RDBS by ASNI (American National Standards Institute) in 1989.
Q) WRITE SQL HISTORY
SQL BACKGROUND: SQL language is a “query language. It can define the structure of the data, modify data in the
database, and specify security constraints.IBM developed the original version of SQL at its San Jose Research
Laboratory. IBM implemented the language, originally called Sequel, in the early 1970s.
The SQL language has several parts:
• Data-definition language (DDL). The SQL DDL provides commands for defining relation schemas, deleting
relations, and modifying relation schemas.
• Data-manipulation language (DML). It includes commands to insert tuples into, delete tuples from, and modify
tuples in the database.
• View definition. The SQL DDL includes commands for defining views.
• Transaction control. SQL includes commands for specifying the beginning and ending of transactions.
• Embedded SQL and dynamic SQL. Embedded and dynamic SQL define how SQL statements can be embedded
within general-purpose programming languages, such as C, C++, Java, PL/I, Cobol, Pascal, and Fortran.
• Integrity. The SQL DDL includes commands for specifying integrity constraints that the data stored in the database
must satisfy.
• Authorization. The SQL DDL includes commands for specifying access rights to relations and views.
From Clause
1. The from clause by itself defines a Cartesian product of the relations in the clause.
2. When an attribute is present in more than one relation they can be referred as relation-
name.attribute-name to avoid the ambiguity.
3. For all customers who have loan from the bank, find their names and loan numbers
SQL> select distinct customer-name, Borrower.loan-number from Borrower, Loan where Borrower.loan-number
= Loan.loan-number
Q) Describe briefly about SQL Commands (OR) Explain the components of SQL.
ANS: SQL commands are instructions used to communicate with the database to perform specific task that work with
data. SQL commands are grouped into four major categories depending on their functionality:
Data Definition Language (DDL) - These SQL commands are used for creating, modifying, and dropping
the structure of database objects. The commands are CREATE, ALTER, DROP, RENAME, and TRUNCATE.
Data Manipulation Language (DML) - These SQL commands are used for storing, retrieving, modifying,
and deleting data. These commands are SELECT, INSERT, UPDATE, and DELETE.
Transaction Control Language (TCL) - These SQL commands are used for managing changes affecting the
data. These commands are COMMIT, ROLLBACK, and SAVEPOINT.
Data Control Language (DCL) - These SQL commands are used for providing security to database objects.
These commands are GRANT and REVOKE.
Q) Explain briefly about DDL Commands (or) Data Definition Language Commands
DDL Commands are as follows
1. CREATE
2. ALTER
3. DROP
4. RENAME and
5. TRUNCATE.
1. CREATE TABLE Statement: The CREATE TABLE Statement is used to create tables to store data.
The Syntax for the CREATE TABLE Statement is:
2
CREATE TABLE table_name (column_name1 datatype, column_name2 datatype,
... column_nameN datatype );
Example: CREATE TABLE employee ( id number(5), name char(20), dept char(10), age number(2),
salary number(10), location char(10) );
2. 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.
a. Add table columns
b. Drop table columns
c. modify table columns
d. Rename table columns
a) To add a column:
b) To drop a column:
c) To modify a column:
3. DROP Statement: 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.
4. RENAME Command: The SQL RENAME command is used to change the name of the table or a
database object.
RENAME old_table_name To new_table_name;
5. TRUNCATE statement: This command is used to delete all the rows from the table and free the
space containing the table.
3
Q) Explain DML Command (OR) Data Manipulation Langage Command.
Ans: DML Stands for Data Manipulation Commands and hence work with data in the table or tables rather than the
objects. The commands that are part of DML are
1. Insert
2. Update and
3. Delete.
1. Insert Command: The INSERT Statement is used to add new rows of data to a table.
INSERT INTO TABLE_NAME [ (col1, col2, col3,...colN)] VALUES (value1, value2, value3,...valueN);
Example: INSERT INTO employee (id, name, dept, age, salary location) VALUES (105, 'Srinath', 'Aeronautics', 27,
33000);
2. UPDATE Command: The UPDATE Statement is used to modify the existing rows in a table.
3. DELETE Command: The DELETE Statement is used to delete rows from a table.
Q) Explain briefly about DCL Commands (OR) Data Control Language Commands
DCL commands are used to enforce database security in a multiple user database environment. Two types of DCL
commands are
1) GRANT and 2) REVOTE.
1) GRANT Command: SQL GRANT is a command used to provide access or privileges on the database
objects to the users.
privilege_name is the access right or privilege granted to the user. Some of the access rights are ALL, EXECUTE,
and SELECT.
object_name is the name of an database object like TABLE, VIEW, STORED PROC and SEQUENCE.
user_name is the name of the user to whom an access right is being granted.
Example: GRANT SELECT ON employee TO user1;
This command grants a SELECT permission on employee table to user1.You should use the WITH GRANT option
carefully because for example if you GRANT SELECT privilege on employee table to user1 using the WITH GRANT
option, then user1 can GRANT SELECT privilege on employee table to another user, such as user2 etc. Later, if you
REVOKE the SELECT privilege on employee from user1, still user2 will have SELECT privilege on employee table.
2) SQL REVOKE Command: The REVOKE command removes user access rights or privileges to the database
objects.
ENAME SALARY
RAJU 5000
JOHN 2000
ROSE 6000
ABHI 8000
SQL allows the use of null values to indicate absence of information about the value of an attribute. We can use the
special keyword null in a predicate to test for a null value.
Thus, to find all loan numbers that appear in the loan relation with null values for amount, we write
select loan-number
from loan
where amount is null
The predicate is not null tests for the absence of a null value. The use of a null value in arithmetic and comparison
operations causes several complications.
SQL treats as unknown the result of any comparison involving a null value (other than is null and is not null).
Since the predicate in a where clause can involve Boolean operations such as and, or, and not on the results of
comparisons, the definitions of the Boolean operations are extended to deal with the value unknown,
• and: The result of true and unknown is unknown, false and unknown is false,
while unknown and unknown is unknown.
• or: The result of true or unknown is true, false or unknown is unknown, while
unknown or unknown is unknown.
• not: The result of not unknown is unknown.
5
Q) WHAT ARE THE SET OPERATORS IN SQL?
Set operators are mainly used to combine the same type of data from two or more tables. The four set operations
union, union all intersect and except allow us to combine two or more SELECT Statements.
Students2003 -Table Students2004 -Table
Name Marks Name Marks
Raju 900 Raju 900
John 1070 Boss 1086
Rose 1032 Rose 1032
Abhi 1002 Marry 1034
Union Operation: The SQL Union is used to combine two tables having same number of columns into a single set.
It will automatically eliminate duplicates.
SQL> (select name, marks from Students2003 ) Name Marks
union Abhi 1002
(select name, marks from Students2004 )
Boss 1086
John 1070
Marry 1034
Raju 900
Rose 1032
Union all: The SQL Union all is used to combine two tables having same number of columns into a single set,
including all duplicates.
SQL> (select name, marks from Students2003 ) Name Marks
Union all Abhi 1002
(select name, marks from Students2004 )
Boss 1086
John 1070
Marry 1034
Raju 900
Raju 900
Rose 1032
Rose 1032
Intersect Operation : The SQL intersect takes the data from both, result sets which are in common.
SQL> (select name, marks from Students2003 )
intersect Name Marks
(select name, marks from Students2004 ) Abhi 1002
Rose 1032
Except Operation: The SQL intersect takes the data from first set, but not the second.
SQL> (select name, marks from Students2003 ) Name Marks
except John 1070
(select name, marks from Students2004 ) Rose 1032
6
Q explain briefly about SUBQUERY
A subquery is a SELECT statement inside the WHERE clause of another SELECT statement. Subqueries can be
used with SELECT, INSERT, UPDATE, DELETE SQL statements along with the comparision operators like =, <,
>, >=, <= etc.
The basic syntax for a subquery is:
SELECT [DISTINCT] select_list FROM table_list WHERE {expression { [NOT] IN | comparison
operator } } ( SELECT [DISTINCT] subquery_select_list FROM table_list WHERE search_conditions
Subqueries are evaluated from the inside out. That is the outer queries action is based on the evaluation of the inner
query
+----+----------+-----+-----------+----------+
| ID | NAME | AGE | ADDRESS | SALARY |
+----+----------+-----+-----------+----------+
| 1 | Ramesh | 35 | Ahmedabad | 2000.00 |
| 2 | Khilan | 25 | Delhi | 1500.00 |
| 3 | kaushik | 23 | Kota | 2000.00 |
| 4 | Chaitali | 25 | Mumbai | 6500.00 |
| 5 | Hardik | 27 | Bhopal | 8500.00 |
| 6 | Komal | 22 | MP | 4500.00 |
| 7 | Muffy | 24 | Indore | 10000.00 |
+----+----------+-----+-----------+----------+
SQL> SELECT * FROM CUSTOMERS WHERE ID IN (SELECT ID FROM CUSTOMERS WHERE SALARY >
4500) ;
+----+----------+-----+---------+----------+
| ID | NAME | AGE | ADDRESS | SALARY |
+----+----------+-----+---------+----------+
| 4 | Chaitali | 25 | Mumbai | 6500.00 |
| 5 | Hardik | 27 | Bhopal | 8500.00 |
| 7 | Muffy | 24 | Indore | 10000.00 |
+----+----------+-----+---------+----------+
SUBQUERIES WITH THE INSERT STATEMENT:
Example: Consider a table CUSTOMERS_1 with similar structure as CUSTOMERS table. Now to copy
complete CUSTOMERS table into CUSTOMERS_BKP, following is the syntax:
SQL> INSERT INTO CUSTOMERS_1 SELECT * FROM CUSTOMERS WHERE ID IN (SELECT ID FROM
CUSTOMERS) ;
SUBQUERIES WITH THE UPDATE STATEMENT:
Example: Following example updates SALARY by 0.25 times in CUSTOMERS table for all the
customers whose AGE is greater than or equal to 27:
SQL> UPDATE CUSTOMERS SET SALARY = SALARY * 0.25 WHERE AGE IN (SELECT AGE FROM
CUSTOMERS1 WHERE AGE >= 27 );
+----+----------+-----+-----------+----------+
| ID | NAME | AGE | ADDRESS | SALARY |
+----+----------+-----+-----------+----------+
| 1 | Ramesh | 35 | Ahmedabad | 125.00 |
| 2 | Khilan | 25 | Delhi | 1500.00 |
| 3 | kaushik | 23 | Kota | 2000.00 |
| 4 | Chaitali | 25 | Mumbai | 6500.00 |
| 5 | Hardik | 27 | Bhopal | 2125.00 |
| 6 | Komal | 22 | MP | 4500.00 |
7
| 7 | Muffy | 24 | Indore | 10000.00 |
+----+----------+-----+-----------+----------+
Subqueries with the DELETE Statement:
Example:Assuming, we have CUSTOMERS1 table available which is backup of CUSTOMERS
table.Following example deletes records from CUSTOMERS table for all the customers whose AGE is
greater than or equal to 27:
SQL> DELETE FROM CUSTOMERS WHERE AGE IN (SELECT AGE FROM CUSTOMERS1 WHERE AGE > 27
);
This would impact two rows and finally CUSTOMERS table would have the following records:
+----+----------+-----+---------+----------+
| ID | NAME | AGE | ADDRESS | SALARY |
+----+----------+-----+---------+----------+
| 2 | Khilan | 25 | Delhi | 1500.00 |
| 3 | kaushik | 23 | Kota | 2000.00 |
| 4 | Chaitali | 25 | Mumbai | 6500.00 |
| 6 | Komal | 22 | MP | 4500.00 |
| 7 | Muffy | 24 | Indore | 10000.00 |
+----+----------+-----+---------+----------+
View: A definition of a restricted portion of the database. Views are useful for maintaining confidentiality and restricts
access to selected parts of the database and for simplifying frequently used query types.
The formats of create view command is
Create view V As
select statement
A view is a database object that represents one or more database tables. It doesn’t occupy any table Space. Views are
mechanism of data independence. They provide automatic security of hidden data. A view is window to a specific use
of the database. Usage of views:
Views are used to secure attributes that contain private information.
Views can be used for creating short cuts for complex queries involving multiple tables.
Views can be created with a Check option that prevents the updating of rows and attributes that are not part of
the view but are part of complete database
8
Q) Describe briefly about SQL Joins
The SQL Joins clause is used to combine records from two or more tables in a database. A JOIN is a means for
combining fields from two tables by using values common to each.
+----+----------+-----+-----------+----------+
| ID | NAME | AGE | ADDRESS | SALARY |
+----+----------+-----+-----------+----------+
| 1 | Ramesh | 32 | Ahmedabad | 2000.00 |
| 2 | Khilan | 25 | Delhi | 1500.00 |
| 3 | kaushik | 23 | Kota | 2000.00 |
| 4 | Chaitali | 25 | Mumbai | 6500.00 |
| 5 | Hardik | 27 | Bhopal | 8500.00 |
| 6 | Komal | 22 | MP | 4500.00 |
| 7 | Muffy | 24 | Indore | 10000.00 |
+----+----------+-----+-----------+----------+
+-----+---------------------+-------------+--------+
|OID | DATE | CUSTOMER_ID | AMOUNT |
+-----+---------------------+-------------+--------+
| 102 | 2009-10-08 00:00:00 | 3 | 3000 |
| 100 | 2009-10-08 00:00:00 | 3 | 1500 |
| 101 | 2009-11-20 00:00:00 | 2 | 1560 |
| 103 | 2008-05-20 00:00:00 | 4 | 2060 |
+-----+---------------------+-------------+--------+
9
INNER JOIN:
The most frequently used and important of the joins is the INNER JOIN. They are also referred to as an EQUIJOIN.
The INNER JOIN creates a new result table by combining column values of two tables (table1 and table2) based upon
the join-predicate. The query compares each row of table1 with each row of table2 to find all pairs of rows which
satisfy the join-predicate. When the join-predicate is satisfied, column values for each matched pair of rows of A and B
are combined into a result row.
Syntax:
Now let us join these two tables using INNER JOIN as follows:
10
| ID | NAME | AMOUNT | DATE |
+----+----------+--------+---------------------+
| 1 | Ramesh | NULL | NULL |
| 2 | Khilan | 1560 | 2009-11-20 00:00:00 |
| 3 | kaushik | 3000 | 2009-10-08 00:00:00 |
| 3 | kaushik | 1500 | 2009-10-08 00:00:00 |
| 4 | Chaitali | 2060 | 2008-05-20 00:00:00 |
| 5 | Hardik | NULL | NULL |
| 6 | Komal | NULL | NULL |
| 7 | Muffy | NULL | NULL |
+----+----------+--------+---------------------+
RIGHT JOIN
The SQL RIGHT JOIN returns all rows from the right table, even if there are no matches in the left table.
Now let us join these two tables using RIGHT JOIN as follows:
FULL JOIN
The SQL FULL JOIN combines the results of both left and right outer joins.
The joined table will contain all records from both tables, and fill in NULLs for missing matches on either side.
SQL> SELECT ID, NAME, AMOUNT, DATE FROM CUSTOMERS
FULL JOIN ORDERS ON CUSTOMERS.ID = ORDERS.CUSTOMER_ID;
11
SQL> SELECT a.ID, b.NAME, a.SALARY FROM CUSTOMERS a, CUSTOMERS b
WHERE a.SALARY < b.SALARY;
CARTESIAN JOIN
The CARTESIAN JOIN or CROSS JOIN returns the cartesian product of the sets of records from the two or more
joined tables. Thus, it equates to an inner join where the join-condition always evaluates to True or where the join-
condition is absent from the statement.
Syntax:
Now let us join these two tables using INNER JOIN as follows:
12
| 3 | kaushik | 3000 | 2009-10-08 00:00:00 |
| 3 | kaushik | 1500 | 2009-10-08 00:00:00 |
| 3 | kaushik | 1560 | 2009-11-20 00:00:00 |
| 3 | kaushik | 2060 | 2008-05-20 00:00:00 |
| 4 | Chaitali | 3000 | 2009-10-08 00:00:00 |
| 4 | Chaitali | 1500 | 2009-10-08 00:00:00 |
| 4 | Chaitali | 1560 | 2009-11-20 00:00:00 |
| 4 | Chaitali | 2060 | 2008-05-20 00:00:00 |
| 5 | Hardik | 3000 | 2009-10-08 00:00:00 |
| 5 | Hardik | 1500 | 2009-10-08 00:00:00 |
| 5 | Hardik | 1560 | 2009-11-20 00:00:00 |
| 5 | Hardik | 2060 | 2008-05-20 00:00:00 |
| 6 | Komal | 3000 | 2009-10-08 00:00:00 |
| 6 | Komal | 1500 | 2009-10-08 00:00:00 |
| 6 | Komal | 1560 | 2009-11-20 00:00:00 |
| 6 | Komal | 2060 | 2008-05-20 00:00:00 |
| 7 | Muffy | 3000 | 2009-10-08 00:00:00 |
| 7 | Muffy | 1500 | 2009-10-08 00:00:00 |
| 7 | Muffy | 1560 | 2009-11-20 00:00:00 |
| 7 | Muffy | 2060 | 2008-05-20 00:00:00 |
+----+----------+--------+---------------------+
Q) Explain briefly about the structure of tuple relational calculus or formal definition of
tuple relational calculs.
Formal Definitions
where is 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.
13
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
Example Queries
1. For example, to find the branch-name, loan number, customer name and amount for loans over $1200:
This gives us all attributes, but suppose we only want the customer names.
In English, we may read this equation as ``the set of all tuples such that there exists a tuple in the relation
borrow for which the values of and for the cname attribute are equal, and the value of for the amount attribute
is greater than 1200.''
The notation means ``there exists a tuple in relation such that predicate is true''.
How did we get the above expression? We needed tuples on scheme cname such that there were tuples in
borrow pertaining to that customer name with amount attribute .
The tuples get the scheme cname implicitly as that is the only attribute is mentioned with.
Find all customers having a loan from the SFU branch, and the the cities in which they live:
In English, we might read this as ``the set of all (cname,ccity) tuples for which cname is a borrower at the SFU
branch, and ccity is the city of cname''.
Tuple variable ensures that the customer is a borrower at the SFU branch.
Tuple variable is restricted to pertain to the same customer as , and also ensures that ccity is the city of the
customer.
The logical connectives (AND) and (OR) are allowed, as well as (negation).
2. Find all customers who have both a loan and an account at the SFU branch.
3. Find customers who have an account, but not a loan at the SFU branch.
4. Find all customers who have an account at all branches located in Brooklyn. (We used division in
relational algebra.)
For this example we will use implication, denoted by a pointing finger in the text, but by here.
In English: the set of all cname tuples such that for all tuples in the branch relation, if the value of on attribute
bcity is Brooklyn, then the customer has an account at the branch whose name appears in the bname attribute of
Formal Definitions
Example Queries
1. Find branch name, loan number, customer name and amount for loans of over $1200.
15
2. Find all customers who have a loan for an amount > than $1200.
3. Find all customers having a loan from the SFU branch, and the city in which they live.
4. Find all customers having a loan, an account or both at the SFU branch.
5. Find all customers who have an account at all branches located in Brooklyn.
If you find this example difficult to understand, try rewriting this expression using implication, as in the tuple
relational calculus example. Here's my attempt:
I've used two letter variable names to get away from the problem of having to remember what stands for.
1. Up until now, we have looked at extracting information from the database. We also need to add, remove and
change information. Modifications are expressed using the assignment operator.
Deletion
1. Deletion is expressed in much the same way as a query. Instead of displaying, the selected tuples are removed
from the database. We can only delete whole tuples.
In relational algebra, a deletion is of the form
2. Delete all loans with loan numbers between 1300 and 1500.
Insertions
1. To insert data into a relation, we either specify a tuple, or write a query whose result is the set of tuples to be
inserted. Attribute values for inserted tuples must be members of the attribute's domain.
2. An insertion is expressed by
2. To provide all loan customers in the SFU branch with a $200 savings account.
16
Updating
1. Updating allows us to change some values in a tuple without necessarily changing all.
We use the update operator, , with the form
Simple Queries
1. For example, to find all customers having an account at the SFU branch:
3. To find all customers having an account at both the SFU and the MetroTown branch:
17
5. Find all customers having an account at the same branch as Jones:
3. Find the name of all customers having an account at the SFU branch, but no loan from that branch.
Queries involving negation can be expressed by putting a sign under the relation name beside an example
row:
1. When it is difficult or impossible to express all constraints on the domain variables within the skeleton tables,
the condition box may be used.
2. To add the constraint that we are only interested in customers other than Jones to the above query, we include
the condition box:
3. To find all account numbers with balances between $1,300 and $1,500:
18
4. Logical expressions and and or may appear in the condition box.
5. To find all account numbers where the balance is between $1,300 and $2,000, but is not $1,500:
6. An unconventional use of the or construct allows comparison with several constant values:
1. If the result of a query includes attributes from several relation schemes, we need a way of displaying the result
in a single table.
2. We can declare a temporary result relation including the attributes to be displayed. We put the print command
only in that table.
3. To find the customer names and cities and account numbers for all customers having an account at the SFU
branch:
1. The order in which tuples are displayed can be controlled by adding the command AO. (ascending order) or
DO. (descending order) to the print command:
2. To sort first by name, and then by balance for those with multiple accounts:
Aggregate Operations
1. QBE includes the aggregate operators AVG, MAX, MIN, SUM and CNT. As QBE eliminates duplicates by
default, they must have ALL. appended to them.
19
2. To find the total balance of all accounts belonging to Jones:
3. All aggregate operators must have ALL. appended, so to override the ALL.\ we must add UNQ. (unique).
(NOTE: a number of examples in the text incorrectly show UNQ. replacing ALL.)
4. To compute functions on groups, we use the G. operator. To find the average balance at each branch:
5. To find the average balances at only branches where the average is more than $1,200, we add the condition
box:
6. To find all customers who have an account at all branches located in Burnaby, we can do:
1. We simply use D. instead of the P. operator. Whole tuples may be deleted, or only some columns.
2. Delete all of Smith's account records:
4. Delete all loans with loan numbers between 1300 and 1500:
20
5. Delete all accounts at branches located in Burnaby:
Insertion
Updates
1. We can update individual attributes with the U. operator. Fields left blank are not changed.
2. To update the assets of the SFU branch to $10,000,000:
21