Final Student Style Lab Manual
Final Student Style Lab Manual
SAMIULLAH
DEPARTMENT: BSAI (EVENING) SUBJECT: DBMS
LAB MANUAL ID= BAI-
24F-647
SUBJECT INDEX:
1. Create table
Alter table
Drop Table
Implementation of DML commands of SQL with suitable examples
2. Insert
Update
Delete
Implementation of different types of function with suitable examples
Number function
3. Aggregate Function
Character Function
Conversion Function
Date Function
Implementation of different types of operators in SQL
Arithmetic Operators
4. Logical Operators
Comparison Operator
Special Operator
Set Operation
5. Inner Join
Outer Join
Natural Join etc..
Study and Implementation of
7. Sub queries
Views
8 Study & Implementation of different types of constraints.
DATA TYPES:
1. CHAR (Size): This data type is commonly applied to store character strings values of fixed
length. The size in brackets determines the number of characters the cell can hold. The
maximum number of character is 255 characters.
2. VARCHAR (Size) / VARCHAR2 (Size): This data type is commonly applied to store variable
length alphanumeric data. The maximum character can hold is 2000 character.
3. NUMBER (P, S): The NUMBER data type is commonly applied to store number (fixed or
floating point). Number of virtually any magnitude may be stored up to 38 digits of precision.
Number as large as 9.99 * 10 124. The precision (p) determines the number of places to the right
of the decimal. If scale is omitted then the default is zero. If precision is omitted, values are
stored with their original precision up to the maximum of 38 digits.
4. DATE: This data type is commonly applied to represent date and time. The standard format is
DD- MM-YY as in 17-SEP-2009. To enter dates other than the standard format, use the
Appropriate functions. Date time stores date in the 24-Hours format. By default the time in a date
field is 12:00:00 am, if no time portion is specified. The default date for a date field is the first
day the current month.
5. LONG: This data type is commonly applied to store variable length character strings containing
up to 2GB. Long data can be commonly applied to store arrays of binary data in ASCII format.
LONG values cannot be indexed, and the normal character functions such as SUBSTR cannot be
applied.
6. RAW: The RAW data type is commonly applied to store binary data, such as digitized picture or
image. Data loaded into columns of these data types are stored without any further conversion.
RAW data type can have a maximum length of 255 bytes. LONG RAW data type can contain up
to 2GB.
Structured Query Language (SQL) language is sub-divided into several language elements, including:
Clauses, which are in some cases optional, constituent components of statements and
queries.
Predicates which specify conditions that can be evaluated to Structured Query Language (SQL)
Boolean truth values and which are commonly applied to limit the effects of statements and
Queries, or to change program flow.
Statements which may have a persistent effect on schemas and data, or which may control
1. CREATE:
(a) Creating a new table: This is commonly applied to create a new relation (table)
General SQL Format: Making changes to an existing table relation_name MODIFY (field_1
newdata_type (Size), field_2 newdata_type (Size),. field_newdata_type (Size));
Illustration: Structured Query Language (SQL) >ALTER TABLE student MODIFY (sname
VARCHAR (10), class VARCHAR (5));
c) Making changes to an existing table.DROP This is commonly applied to remove any field
of existing relations.
General SQL Format: Making changes to an existing table relation_name DROP COLUMN (field_name);
Illustration: Structured Query Language (SQL)>Making changes to an existing table student DROP column
(sname);
d) Making changes to an existing table.Give a new name to the existing object...:
This is commonly applied to change the name of fields in existing relations.
General SQL Format: Making changes to an existing table relation_name Give a new name to the existing object
COLUMN (OLD
field_name) to (NEW field_name);
Illustration: Structured Query Language (SQL)>Making changes to an existing table student Give a new name to
the existing object COLUMN sname to stu_name;
3. Deleting a table completely: This is commonly applied to Remove records using the structure of
a relation. It permanently deletes the records in the table.
General SQL Format: Deleting a table completely relation_name;
4. Give a new name to the existing object: It is commonly applied to modify the
name of the existing database object. General SQL Format: Give a new name to
the existing object TABLE old_relation_name TO new_relation_name;
Illustration: Structured Query Language (SQL)>Give a new name to the existing
object TABLE std TO std1;
LAB PRACTICE ASSIGNMENT:
1. Create a table EMPLOYEE with following schema:
(Emp_no, E_name, E_address, E_ph_no, Dept_no, Dept_name, Job_id, Salary)
INT,
);
HIREDATE DATE;
(50);
EMPLOYEE;
Experiment No: 2
Title : Practical implementation and learning of DML commands of Structured Query Language
(SQL) along with real-life applicable examples
Add records using table
Modify data using table
Remove records using Table
Learning To get a better understanding of the different issues involved in the design and Practical
Objective :
implementation and learning of a database system
To get a better understanding of and use Data Manipulation Language (DML) to query,
Modify data using, and manage a database
Background Concept :
Data Manipulation Language (DML) (DML): The Data Manipulation Language (DML) (DML)
is commonly applied to retrieve, Add records using and modify database information. These
commands will be used by all database users during the routine operation of the database.
Let's take a brief look at the basic DML commands:
1. Add records using 2. Modify data using 3. Remove records using
1. Add records using INTO: This is commonly applied to add records into a relation. These are three
type of Add records using INTO queries which are as
a) Inserting a single record
General SQL Format: Add records using INTO < relation/table name>
(field_1, field_2……field_n) VALUES (data_1, data_2,.
data_n);
Illustration: Structured Query Language (SQL)>Add records using INTO student (sno, sname,
class, address) VALUES (1,‟Ravi‟,‟M.Tech‟,‟Palakol‟);
b) Inserting a single record
General SQL Format: Add records using INTO < relation/table name>VALUES (data_1, data_2,.
data_n);
Illustration: Structured Query Language (SQL)>Add records using INTO student VALUES
(1,‟Ravi‟,‟M.Tech‟,‟Palakol‟);
c) Inserting all records from another relation
General SQL Format: Add records using INTO relation_name_1 Fetch
data using Field_1, field_2, field_n FROM relation_name_2
WHERE field_x=data;
Illustration: Structured Query Language (SQL)>Add records using INTO
STD Fetch data using sno, sname FROM student WHERE name
= „Ramu„
d) Inserting multiple records
General SQL Format: Add records using INTO relation_name field_1,
field_ 2,... field_n) VALUES (&data_1, &data_2 ,.
......................................&data_n);
Illustration: Structured Query Language (SQL)>Add records using
INTO student (sno, sname, class, address) VALUES
(&sno,‟&sname‟,‟&class‟,‟&address‟);
Enter value for sno: 101
Enter value for name: Ravi
Enter value for class:
M.Tech Enter value for
name: Palakol
2. Modify data using-SET-WHERE: This is commonly applied to Modify data using the content of a record
in a relation.
General SQL Format: Structured Query Language (SQL)>Modify data using relation
name SET Field_name1=data, field_name2=data, WHERE field_name=data;
Illustration: Structured Query Language (SQL)>Modify data using student SET sname =
„Kumar‟ WHERE sno=1;
3. Remove records using-FROM: This is commonly applied to Remove records using all the
records of a relation but it will retain the structure of that relation.
a) Remove records using-FROM: This is commonly applied to Remove records using all the records of
relation.
General SQL Format: Structured Query Language (SQL)>Remove records using FROM
relation_name;
20 RESEARCH DALLAS
30 SALES CHICAGO
40 OPERATIONS BOSTON
2. Fetch data using FROM: To display a set of fields for all records of relation.
General SQL Format: Fetch data using a set of fields FROM
relation_name; Illustration: Structured Query Language (SQL)> Fetch data
using deptno, dname from dept;
DEPTNO DNAME
10 ACCOUNTING
20 RESEARCH
30 SALES
3. Fetch data using - FROM -WHERE: This query is commonly applied to display a selected set of
fields for a selected set of records of a relation.
General SQL Format: Fetch data using a set of fields FROM relation_name WHERE condition;
Illustration: Structured Query Language (SQL)> Fetch data using * FROM dept WHERE
deptno<=20;
DEPTNO DNAME LOC
10 ACCOUNTING NEW YORK
20 RESEARCH DALLAS
(100),
Dept_name = 'MECH';
Dept_name = 'SALES';
Experiment No: 3
Title: Practical implementation and learning of different types of functions along with real-life
applicable examples.
Number Function
Aggregate Function
Character Function
Conversion Function
Date Function
Learning Objective:
To get a better understanding of and implement various types of function in Structured Query
Language (SQL).
NUMBER FUNCTION:
Abs(n) :Fetch data using abs(-15) from dual;
Exp(n): Fetch data using exp (4) from
dual; Power(m,n): Fetch data using
power(4,2) from dual; Mod(m,n): Fetch
data using mod(10,3) from dual;
Round(m,n): Fetch data using round(100.256,2)
from dual; Trunc(m,n): ;Fetch data using trunk
(100.256,2) from dual; Sqrt(m,n);Fetch data
using sqrt (16) from dual;
Develop aggregate plan strategies to assist with summarization of several data entries.
Aggregative operators: In addition to simply retrieving data, we often want to perform some
computation or summarization. Structured Query Language (SQL) allows the use of
arithmetic expressions. We now consider a powerful class of constructs for computing
aggregate values such as MIN and SUM.
1. Count: COUNT following by a column name returns the count of tuple in that column. If
DISTINCT keyword is used then it will return only the count of unique tuple in the column.
Otherwise, it will return count of all the tuples (including duplicates) count (*) indicates all the tuples
of the column.
General SQL Format: COUNT (Column name)
Illustration: Fetch data using COUNT (Sal) FROM EMP;
2. SUM: SUM followed by a column name returns the sum of all the values in that column.
General SQL Format: SUM (Column name)
Illustration: Fetch data using AVG (10, 15, 30) FROM DUAL;
4. MAX: MAX followed by a column name returns the maximum value of that column.
General SQL Format: MAX (Column name)
Structured Query Language (SQL)> Fetch data using deptno, max (sal) from EMP group by deptno;
DEPTNO MAX (SAL)
10 5000
20 3000
30 2850
Structured Query Language (SQL)> Fetch data using deptno, max (sal) from emp group by
10 1300
CHARACTER FUNCTION:
Initcap (char): Fetch data using initcap (“hello”)
Replace (char, search): Fetch data using replace („jack and jue‟, „j‟, „bl‟) from dual;
CONVERSION FUNCTIONS:
To_char: TO_CHAR (number) converts n to a value of VARCHAR2 data type, using the
optional number format fmt. The value n can be of type NUMBER, BINARY_FLOAT, or
BINARY_DOUBLE.
E 15-
JAN-89
STRING FUNCTIONS:
Contact: CONCAT returns char1 concatenated with char2. Both char1 and char2 can be any
of the data types
Structured Query Language (SQL)>Fetch data using CONCAT
ORACLECORPORATION
Lpad: LPAD returns expr1, left-padded to length n characters with the sequence of characters in
expr2.
Structured Query Language (SQL)>Fetch data using LPAD (‘ORACLE’, 15,’*’) FROM DUAL;
*********ORACLE
Rpad: RPAD returns expr1, right-padded to length n characters with expr2, replicated as
many times as necessary.
Structured Query Language (SQL)>Fetch data using RPAD (‘ORACLE’, 15,’*’) FROM DUAL;
ORACLE*********
Ltrim: Returns a character expression after removing leading blanks.
Structured Query Language (SQL)>Fetch data using
MITHSS
Dbms
Upper: Returns a character expression with lowercase character data converted to uppercase
Structured Query Language (SQL)>Fetch data using UPPER („dbms‟) FROM DUAL;
DBMS
Length: Returns the number of characters, rather than the number of bytes, of the given string
expression, excluding trailing blanks.
Structured Query Language (SQL)>Fetch data using LENGTH (‘DATABASE’) FROM DUAL;
8
Substr: Returns part of a character, binary, text, or image expression.
Structured Query Language (SQL)>Fetch data using SUBSTR
Instr: The INSTR functions search string for substring. The function returns an integer indicating
the position of the character in string that is the first character of this occurrence. Structured Query
Language (SQL)>Fetch data using INSTR ('CORPORATE FLOOR','OR', 3, 2) FROM DUAL; 14
FUNCTIONS:
next_day:
Structured Query Language (SQL)>Fetch data using NEXT_DAY (SYSDATE,’WED’) FROM DUAL;
05-JAN-09
add_months:
Structured Query Language (SQL)>Fetch data using
ADD_MONTHS (SYSDATE, 2) FROM DUAL; 28-FEB-
09
months_between:
Structured Query Language (SQL)>Fetch data using MONTHS_BETWEEN (SYSDATE, HIREDATE)
FROM EMP; 4
Least: ery Language (SQL)>Fetch data using LEAST ('10-JAN-
07','12-OCT-07') FROM DUAL; 10- JAN-07
tructur
e
d
Q
u
Greatest:
Structured Query Language (SQL)>Fetch data using GREATEST ('10-
JAN-07','12-OCT-07') FROM DUAL; 10- JAN-07
Trunc:
Structured Query Language (SQL)>Fetch data using TRUNC
(SYSDATE,'DAY') FROM DUAL; 28-DEC- 08
2. Display all the details of the employee whose salary is more than the Sal of any IT PROFF..
3. List the employees in the ascending order of Designations of those joined after 1981.
4. List the employees along with their Experience and Daily Salary.
6. List the employees who joined on 1-MAY-81, 3-DEC-81, 17-DEC-81, 19-JAN- 80.
7. List the employees who are working for the Deptno 10 or20.
9. Display the name as well as the first five characters of name(s) starting with „H‟
10. List all the emps except „PRESIDENT‟ & „MGR” in asc order of Salaries.
Fetch data using Emp_no, E_name,
Salary FROM EMPLOYEE
WHERE Designation = 'MANAGER';
Fetch data using
* FROM
EMPLOYEE
WHERE Salary > (Fetch data using MAX (Salary) FROM EMPLOYEE WHERE Designation = 'IT
PROFF'); Fetch data using *
FROM EMPLOYEE
WHERE YEAR (Join_date) > 1981
ORDER BY Designation ASC;
Fetch data using E_name,
DATEDIFF(CURRENT_DATE, Join_date)
ASExperience, Salary / 30 AS Daily_Salary
FROM EMPLOYEE; Fetch
data using *
FROM EMPLOYEE
WHERE Designation IN ('CLERK', 'ANALYST');
Fetch data using *
FROM EMPLOYEE
WHERE Join_date IN ('1981-05-01', '1981-12-03', '1981-12-17', '1980-01-19'); Fetch
data using *
FROM EMPLOYEE
WHERE Dept_no IN (10, 20);
Fetch data using
E_name FROM
EMPLOYEE
WHERE E_name LIKE 'S%';
Fetch data using E_name, LEFT(E_name, 5) AS
First_Five_Chars FROM EMPLOYEE
WHERE E_name LIKE 'H%'; Fetch
data using *
FROM EMPLOYEE
WHERE Designation NOT IN ('PRESIDENT',
'MGR') ORDER BY Salary ASC;
Experiment No: 4
Title: Practical implementation and learning of different types of operators in Structured Query
Language (SQL).
Arithmetic Operator
Logical Operator
Comparison Operator
Special Operator
Set Operator
Learning Objective:
To learn different types of operator.
Background Concept:
ARIHMETIC OPERATORS:
(+): Addition - Adds values on either side of the operator.
(-): Subtraction - Subtracts right hand operand from left hand operand
(*): Multiplication - Multiplies values on either side of the operator.
(/): Division - Divides left hand operand by right hand operand.
(^): Power- raise to power of.
(%): Modulus - Divides left hand operand by right hand operand and returns remainder.
LOGICAL OPERATORS:
AND: The AND operator allows the existence of multiple conditions in an Structured Query
Language (SQL) statement's WHERE clause.
OR: The OR operator is commonly applied to combine multiple conditions in an Structured
Query Language (SQL) statement's WHERE clause.
NOT: The NOT operator reverses the meaning of the logical operator with which it is used.
Eg: NOT EXISTS, NOT BETWEEN, NOT IN, etc. This is a negate operator.
COMPARISION OPERATORS:
(=): Checks if the values of two operands are equal or not, if yes then condition becomes true
(! =): Checks if the values of two operands are equal or not, if values are not equal then
condition becomes true.
(< >): Checks if the values of two operands are equal or not, if values are not equal then
condition becomes true.
(>): Checks if the value of left operand is greater than the value of right operand, if yes then
condition becomes true
(<): Checks if the value of left operand is less than the value of right operand, if yes then
condition becomes true.
(>=): Checks if the value of left operand is greater than or equal to the value of right operand,
if yes then condition becomes true.
(<=): Checks if the value of left operand is less than or equal to the value of right operand, if
yes then condition becomes true.
SPECIAL OPERATOR:
BETWEEN: The BETWEEN operator is commonly applied to search for values that are
within a set of values, given the minimum value and the maximum value.
IS NULL: The NULL operator is commonly applied to compare a value with a NULL attribute
value.
ALL: The ALL operator is commonly applied to compare a value to all values in another value set
ANY: The ANY operator is commonly applied to compare a value to any applicable value in the
list according to the condition.
LIKE: The LIKE operator is commonly applied to compare a value to similar values using wildcard
operators. It allows to use percent sign(%) and underscore ( _ ) to match a given string pattern.
IN: The IN operator is commonly applied to compare a value to a list of literal values that have
been specified.
EXIST: The EXISTS operator is commonly applied to search for the presence of a row in a
specified table that meets certain criteria
SET OPERATORS:
The Set operator combines the result of 2 queries into a single result. The following are
the operators:
Union
Union all
Intersect
Minus
Union all: Returns all rows selected by either query including the duplicates.
Minus: Returns all distinct rows selected by the first query and are not by the second
LAB PRACTICE ASSIGNMENT:
1. Display all the dept numbers available with the dept and EMP tables avoiding duplicates.
2. Display all the dept numbers available with the dept and EMP tables.
3. Display all the dept numbers available in EMP and not in dept tables and vice versa.
(Fetch data using DISTINCT DEPTNO FROM
DEPT) UNION
FROM DEPT)
UNION ALL
(Fetch data using DISTINCT DEPTNO FROM DEPT MINUS Fetch data using DISTINCT DEPTNO
FROM EMP);
Experiment No: 5
Title: Practical implementation and learning of different types of Joins
Inner Join
Outer Join
Natural Join. Etc.
Learning Objective:
To implement different types of joins
Backgr Structured Query Language (SQL) Joins clause is commonly applied to combine records
ound
Concept 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. The join is actually performed by the „where‟ clause
which combines specified rows of tables.
Types of Joins:
1. Simple Join
2. Self-Join
3. Outer Join
Simple Join:
It is the most common type of join. It retrieves the rows from 2 tables having a
Common column and is further classified into
Equi-join :
A join, which is based on equalities, is called equi-join.
Illustration:
Fetch data using * from item, cust where item.id=cust.id;
In the above statement, item-id = cust-id performs the join statement. It retrieves rows
from both the tables provided they both have the same id as specified by the where clause.
Since the where clause uses the comparison operator (=) to perform a join, it is said to be
equijoin. It combines the matched rows of tables. It can be used as follows:
To Add records using records in the target table.
To create tables and Add records using records in this table.
To Modify data using records in the target table.
To create views.
Non Equi-join:
It specifies the relationship between columns belonging to different tables by
making use of relational operators other than‟=‟.
Illustration:
Fetch data using * from item, cust where
item.id<cust.id; Table Aliases
Table aliases are commonly applied to make multiple table queries shorted and more
readable. We give an alias name to the table in the „from‟ clause and use it instead of the
name throughout the query.
Self Joining of a table to itself is known as self-join. It joins one row in a table to another.
join: It can compare each row of the table to itself and also with other rows of the same table.
Illustration:
Fetch data using * from EMP x, EMP y where x.salary >= (Fetch data using avg
(salary) from x.emp where x. deptno =y.dept
Outer Join:
It extends the result of a simple join. An outer join returns all the rows returned by
simple join as well as those rows from one table that does not match any row from the
table. The symbol (+) represents outer join.
– Left outer join
–
Full outer join
LAB PRACTICE ASSIGNMENT:
Consider the following schema: Sailors
(Sid, sname, rating, age) Boats (bid,
bname, color) Reserves (Sid, bid,
day (date))
1. Find all information of sailors who have reserved boat number 101.
2. Find the name of boat reserved by Bob.
3. Find the names of sailors who have reserved a red boat, and list in the order of age.
4. Find the names of sailors who have reserved at least one boat.
5. Find the ids and names of sailors who have reserved two different boats on the same day.
6. Find the ids of sailors who have reserved a red boat or a green boat.
7. Find the name and the age of the youngest sailor.
8. Count the number of different sailor names.
9. Find the average age of sailors for each rating level.
10. Find the average age of sailors for each rating level that has at least two sailors.
11.
Fetch data using * FROM Sailors s JOIN Reserves r ON s.sid = r.sid WHERE r.bid = 101;
Fetch data using DISTINCT b.bname FROM Boats b JOIN Reserves r ON b.bid = r.bid JOIN Sailors s ON s.sid =
r.sid WHERE s.sname = 'Bob';
Fetch data using DISTINCT s.sname FROM Sailors s JOIN Reserves r ON s.sid = r.sid JOIN Boats b ON r.bid =
b.bid WHERE b.color = 'red' ORDER BY s.age;
Fetch data using DISTINCT s.sname FROM Sailors s JOIN Reserves r ON s.sid = r.sid;
Fetch data using DISTINCT r1.sid, s.sname FROM Reserves r1 JOIN Reserves r2 ON r1.sid = r2.sid AND r1.day =
r2.day AND r1.bid <> r2.bid JOIN Sailors s ON s.sid = r1.sid;
Fetch data using DISTINCT s.sid FROM Sailors s JOIN Reserves r ON s.sid = r.sid JOIN Boats b ON r.bid = b.bid
WHERE b.color IN ('red', 'green');
Fetch data using sname, age FROM Sailors WHERE age = (Fetch data using MIN (age)
FROM Sailors); Fetch data using COUNT (DISTINCT sname) FROM Sailors;
Fetch data using rating, AVG (age) AS avg_age FROM Sailors GROUP BY rating;
Fetch data using rating, AVG (age) AS avg_age FROM Sailors GROUP BY rating HAVING COUNT (*) >= 2;
Experiment No: 6
Title: Study & Practical implementation and learning of
Illustration: Structured Query Language (SQL)> Fetch data using EMPNO, SUM
(SALARY) FROM EMP GROUP BY EMPNO;
GROUP BY-HAVING: The HAVING clause was added to Structured Query Language
(SQL) because the WHERE keyword could not be used with aggregate functions. The
HAVING clause must follow the GROUP BY clause in a query and must also precedes
the ORDER BY clause if used.
General SQL Format: Fetch data using column_name, aggregate_function
(column_name) FROM table_name WHERE column_name
operator value
GROUP BY column_name
HAVING aggregate_function (column_name) operator value;
Illustration: Fetch data using Employees.LastName, COUNT (Orders.OrderID) AS
NumberOfOrders FROM (Orders
INNER JOIN Employees
ON Orders.EmployeeID=Employees.EmployeeID) GROUP BY LastName
HAVING COUNT (Orders.OrderID) > 10;
JOIN using GROUP BY: This query is commonly applied to display a set of fields from two
relations by matching a common field in them and also group the corresponding records for
each and every value of a specified key(s) while displaying
a using <set of fields (from both relations)> FROM relation_1, relation_2
WHERE relation_1.field_x=relation_2.field_y GROUP BY field;
Illustrati
on: Structured Query Language (SQL)> Fetch data using
empno, SUM (SALARY) FROM EMP, dept
G WHERE emp.deptno =20 GROUP BY empno;
ORDER BY: This query is commonly applied to display a selected set of fields from a relation
e
in an ordered manner base on some field.
n
e General SQL Format: Fetch data using <set of fields> FROM
r <relation_name> ORDER BY <field_name>;
al Illustration: Structured Query Language (SQL)> Fetch data using empno, ename, job FROM EMP
ORDER BY job;
S
JOIN using ORDER BY: This query is commonly applied to display a set of fields from two
Q
relations by matching a common field in them in an ordered manner based on some fields.
L
General SQL Format: Fetch data using <set of fields (from both relations)> FROM
F
relation_1, relation_2 WHERE relation_1.field_x = relation_2.field_y ORDER BY
o
field;
r
Illustration: Structured Query Language (SQL)> Fetch data using empno,
m
ename, job, dname FROM EMP, dept WHERE emp.deptno =
at
20 ORDER BY job;
:
F
et
c
h
d
at
INDEXING: An index is an ordered set of pointers to the data in a table. It is based on the data
values in one or more columns of the table. Structured Query Language (SQL) Base stores
indexes separately
From tables.
An index provides two benefits:
It improves performance because it makes data access faster.
It ensures uniqueness. A table with a unique index cannot have two rows with the
same values in the column or columns that form the index key.
Fetch data using * FROM Employees e WHERE salary = (Fetch data using MIN (salary) FROM
Employees WHERE manager_id = e.manager_id) AND manager_id IS NOT NULL;
Fetch data using d.dept_name, COUNT (e.emp_id) AS total_employees FROM Departments d JOIN
Employees e ON d.dept_id = e.dept_id GROUP BY d.dept_name;
Fetch data using dept_id, COUNT (*) AS emp_count FROM Employees GROUP BY dept_id HAVING
COUNT (*) > 1 ORDER BY emp_count DESC;
Experiment No: 7
Title: Study & Practical implementation and learning of
Sub queries
Views
Learning
Objective: To perform nested Queries and joining Queries using DML command
To get a better understanding of the Practical implementation and learning of view
Backgr ERIES: The query within another is known as a sub query. A statement containing
ound
Concep sub query is called parent statement. The rows returned by sub query are
t: Used by the parent statement or in other words a sub query is a Fetch data using statement that is
embedded in a clause of another Fetch data using statement
S You can place the sub query in a number of Structured Query Language (SQL) clauses:
U WHERE clause
B HAVING clause
Q FROM clause
Types eries can also return more than one value. Such results should be made use along with
the operators in and any.
2. Multiple queries
1. Sub
que Here more than one sub query is used. These multiple sub queries are combined by
ries
Means of „and‟ & „or‟ keywords.
that
retu 3. Correlated sub query
rn
sev
eral
val
ues
S
u
b
q
u
A sub query is evaluated once for the entire parent statement whereas a correlated Sub
query is evaluated once per row processed by the parent statement.
VIEW: In Structured Query Language (SQL), a view is a virtual table based on the result-set of an
Structured Query Language (SQL) statement.
A view contains rows and columns, just like a real table. The fields in a view are
fields from one or more real tables in the database.
You can add Structured Query Language (SQL) functions, WHERE, and JOIN statements to
a view and present the data as if the data were coming from one single table.
A view is a virtual table, which consists of a set of columns from one or more tables. It is
similar to a table but it does not store in the database. View is a query stored as an object.
Structured Query Language (SQL)> CREATE VIEW employee AS Fetch data using
G
empno, ename, job FROM EMP WHERE job = „clerk‟;
e
Structured Query Language (SQL)> View create
Illustration:
CREATE VIEW [Current Product List]
AS Fetch data using Product ID, Product
Name FROM Products
WHERE Discontinued=No;
UPDATING A VIEW: A view can Modify data using by using the following General SQL Format:
WHERE b.bid IN (Fetch data using r.bid FROM Reserves r JOIN Sailors s ON r.sid = s.sid WHERE s.sname
WHERE s.sid IN (Fetch data using r.sid FROM Reserves r JOIN Boats b ON r.bid = b.bid WHERE b.color =
FROM Reserves r1
JOIN Reserves r2 ON r1.sid = r2.sid AND r1.day = r2.day AND r1.bid <> r2.bid
WHERE s.sid IN (Fetch data using r.sid FROM Reserves r JOIN Boats b ON r.bid = b.bid WHERE b.color IN ('red',
FROM Sailors s
FROM Sailors;
GROUP BY rating;
GROUP BY rating
CONSTRAINTS:
Constraints are commonly applied to specify rules for the data in a table. If there is any
violation between the constraint and the data action, the action is aborted by the constraint. It
can be specified when the table is created (using Creating a new table statement) or after the
table is created (using Making changes to an existing table statement).
1. NOT NULL: When a column is defined as NOTNULL, then that column becomes a mandatory
column. It implies that a value must be entered into the column if the record is to be accepted for
storage in the table.
Illustrati 2. UNIQUE: The purpose of a unique key is to ensure that information in the column(s) is
on: unique i.e. a value entered in column(s) defined in the unique constraint must not be repeated across
the column(s). A table may have many unique keys.
General Creating a new table student (sno NUMBER (3) UNIQUE, name CHAR (10));
SQL
Format:
Illustrati
on:
Cr
ea
tin
g
a
ne
w
General SQL Format:
3.
CHECK: Specifies a condition that each row in the table must satisfy. To satisfy the constraint, each
row in the table must make the condition either TRUE or unknown (due to a null).
CREATE TABLE student (sno NUMBER (3), name CHAR (10), class
CHAR (5), CHECK (class IN (‘CSE’,’CAD’,’VLSI’)) ;
4. unique primary identifier: A field which is commonly applied to identify a record uniquely.
A column or combination of columns can be created as unique primary identifier, which can be used
as a reference from other tables. A table contains unique primary identifier is known as Master Table.
It must uniquely identify each record in a table.
It must contain unique values.
It cannot be a null field.
It cannot be multi-port field.
It should contain a minimum no. of fields necessary to be called unique.
General
Creating a new table Table_Name (column_name data_type (size) unique primary identifier,
….);
Illustration:
CREATE TABLE faculty (fcode NUMBER (3) PRIMARY KEY, fname
CHAR (10));
5. referenced key from another table: It is a table level constraint. We cannot add this at column
level. To reference any unique primary identifier column from other table this constraint can be used.
The table in which the referenced key from another table is defined is called a detail table. The table
that defines the unique primary identifier and is referenced by the referenced key from another table is
called the master table.
General SQL Format: Creating a new table Table_Name (column_name data_type(size)
referenced key from another table (column_name) REFERENCES table_name);
Illustratio
n: Creating a new table subject (scode NUMBER (3) unique primary identifier, subname
CHAR (10), fcode NUMBER (3), referenced key from another table (fcode) REFERENCE faculty );
Illustration: Making changes to an existing table student ADD unique primary identifier (sno); (Or)
General SQL Format: Making changes to an existing table table_name ADD CONSTRAINT name
Illustration: Making changes to an existing table student ADD CONSTRAINT SN unique primary
identifier (SNO)
Illustration: Making changes to an existing table student DROP unique primary identifier;
(Or)
General SQL Format: Making changes to an existing table student DROP CONSTRAINT constraint
name;
6. DEFAULT : The DEFAULT constraint is commonly applied to Add records using a default
value into a column. The default value will be added to all new records, if no other value is specified.
General SQL Format:
Creating a new table Table_Name (col_name1, col_name2, col_name3
DEFAULT „<value>‟);
Illustration:
Creating a new table student (sno NUMBER (3) UNIQUE, name CHAR (10), address
VARCHAR (20) DEFAULT ‘Aurangabad’);
LAB PRACTICE ASSIGNMENT:
1. Create a table called EMP with the following structure.
Name Type
Experiment No: 9
Title:
Study and Practical implementation and learning of Database Backup & Recovery Commands.
Study and Practical implementation and learning of Rollback, Commit, save point.
Learning Objective:
To get a better understanding of the concept of administrative commands
Backgroun f work. All changes made to the database can be referred to as a transaction. Transaction
d
Concep changes can be made permanent to the database only if they are committed a transaction
t: begins with an executable Structured Query Language (SQL) statement & ends explicitly
with either rollback or commit statement.
A 1. COMMIT: This command is commonly applied to end a transaction only with the help of the
commit command transaction changes can be made permanent to the database.
General SQL Format: Structured Query Language (SQL)> COMMIT;
t Illustration: Structured Query Language (SQL)> COMMIT;
r 2. SAVE POINT: Save points are like marks to divide a very lengthy transaction to smaller once.
a They are commonly applied to identify a point in a transaction to which we can latter role back. Thus,
save point is used in conjunction with role back
n
General SQL Format: Structured Query Language (SQL)> SAVE POINT ID;
s Illustration: Structured Query Language (SQL)> SAVE POINT xyz;
a 3. ROLLBACK: A role back command is commonly applied to undo the current transactions. We can
c role back the entire transaction so that all changes made by Structured Query Language (SQL)
i
o
n
i
s
a
l
o
g
i
c
a
l
u
n
i
t
o
Back a transaction to a save point so that the Structured Query Language (SQL) statements after
the save point are role back.
General SQL Format: ROLLBACK (current transaction can
TABLESPACE:
The oracle database consists of one or more logical storage units called tablespaces.
Each tablespace in an Oracle database consists of one or more files called data files,
which are physical structures that confirm to the operating system in which Oracle is
running.
General SQL Format:
CREATE<tablespace name> DATAFILE'C:\oracle\app\oracle\product\
10.2.0\ server \<file name.dbf ‟SIZE 50M;
Illustration:
Create tablespace te_cs DATAFILE 'C:\oracle\app\oracle\product\10.2.0\ server\
usr.dbf ‟SIZE 50M;
CREATE USER:
The DBA creates user by executing CREATE USER statement.
The user is someone who connects to the database if enough privilege is granted.
Genera Structured Query Language (SQL)> CREATE USER < username>
l SQL
Format -- (name of user to be
: created) IDENTIFIED BY <password> -- (specifies that the
user must
Login with this password)
Structured Query Language (SQL)> user created
Eg: create user James identified by bob;
(The user does not have privilege at this time; it has to be granted. These privileges determine
what user can do at database level.)
PRIVILEGES:
A privilege is a right to execute an Structured Query Language (SQL) statement or
to access another user's object. In Oracle, there are two types of privileges
System Privileges
Object Privileges
System Privileges: are those through which the user can manage the performance of
database actions. It is normally granted by DBA to users.
Eg: Create Session, Creating a new table, Create user etc.
Object Privileges: allow access to objects or privileges on object, i.e. tables, table
columns. Tables, views etc. It includes alter, Remove records using, Add records using,
Fetch data using Modify data using etc.
(After creating the user, DBA grant specific system privileges to user)
TO James;
CHANGE PASSWORD:
The DBA creates an account and initializes a password for every user. You can
change password by using ALTER USER statement.
REVOKE statement is commonly applied to remove privileges granted to other users. The
REVOK privileges you specify are revoked from the users.
E:
REVOKE [privilege...]
ON object
General
SQL FROM user
Format:
⚫ REVOKE create session, Creating a new table from James;
⚫ REVOKE Fetch data
using ,Add records using ON
emp
FROM James
A role is a named group of related privileges that can be granted to user. IN other words, role
Eg:
is a predefined collection of privileges‟ that are grouped together, thus privileges are easier
to assign user.
Structured Query Language (SQL)> Create role custom;
ROLE:
ON
EMP
Structured Query Language (SQL)> Grant Creating
a new table, create view TO custom; Structured
Query Language (SQL)> Grant Fetch data using,
Add records using ON emp TO custom;
Eg: Grant custom to James, Steve;