0% found this document useful (0 votes)
3 views58 pages

Final Student Style Lab Manual

The document is a lab manual for a Database Management System (DBMS) course, detailing various SQL commands and their implementations. It covers Data Definition Language (DDL) and Data Manipulation Language (DML) commands, including creating, altering, and deleting tables, as well as inserting, updating, and deleting records. Additionally, it includes practical assignments and explanations of SQL data types and commands for managing databases.

Uploaded by

kumarsumair857
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views58 pages

Final Student Style Lab Manual

The document is a lab manual for a Database Management System (DBMS) course, detailing various SQL commands and their implementations. It covers Data Definition Language (DDL) and Data Manipulation Language (DML) commands, including creating, altering, and deleting tables, as well as inserting, updating, and deleting records. Additionally, it includes practical assignments and explanations of SQL data types and commands for managing databases.

Uploaded by

kumarsumair857
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 58

NAME: NAJEEBULLAH FATHER NAME:

SAMIULLAH
DEPARTMENT: BSAI (EVENING) SUBJECT: DBMS
LAB MANUAL ID= BAI-
24F-647

SUBJECT INDEX:

S.No Name of the Experiment Page No

Implementation of DDL commands of SQL with suitable examples

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

Implementation of different types of Joins

5.  Inner Join
 Outer Join
 Natural Join etc..
Study and Implementation of

6.  Group By & having clause


 Order by clause
 Indexing
Study & Implementation of

7.  Sub queries
 Views
8 Study & Implementation of different types of constraints.

Study & Implementation of Database Backup & Recovery commands.


9
Study & Implementation of Rollback, Commit, Save point.

 Creating Database /Table Space

10  Managing Users: Create User, Delete User


 Managing roles:-Grant, Revoke.

11 Study & Implementation of PL/SQL.

12 Study & Implementation of SQL Triggers.


Experiment No: 1
Title: Practical implementation and learning of DDL commands of Structured Query Language (SQL) along
with real-life applicable examples
 Creating a new table
 Making changes to an existing table
 Deleting a table completely
Learning
Objective:
 To get a better understanding of the different issues involved in the design and Practical
implementation and learning of a database system
 To get a better understanding of and use Data Definition Language (DDL) to write query for a
database
Backgroun
d Concept: Oracle has many tools such as Structured Query Language (SQL) * PLUS, Oracle Forms, Oracle Report
Writer, Oracle Graphics etc.
 Structured Query Language (SQL) * PLUS: The Structured Query Language (SQL) * PLUS tool is
made up of two distinct parts. These are
 Interactive Structured Query Language (SQL): Interactive Structured Query
Language (SQL) is designed for create, access and manipulate data structures like
tables and indexes.
 PL/Structured Query Language (SQL): PL/Structured Query Language (SQL)
can be commonly applied to developed programs for different applications.
 Oracle Forms: This tool allows you to create a data entry screen along with the suitable menu
objects. Thus it is the oracle forms tool that handles data gathering and data validation in a
commercial application.
 Report Writer: Report writer allows programmers to prepare innovative reports using data
from the oracle structures like tables, views etc. It is the report writer tool that handles the
reporting section of commercial application.
 Oracle Graphics: Some of the data can be better represented in the form of pictures. The
oracle graphics tool allows programmers to prepare graphs using data from oracle structures
like tables, views etc.
Structured Query Language (SQL) (Structured Query Language):
Structured Query Language is a designed for managing in relational database management
systems (RDBMS), and originally based upon . Its scope includes data query and Modify data using,
creation and modification, and data access control.
Structured Query Language (SQL) was one of the first languages for 's and became the most
widely used language for relational databases.
 IBM developed Structured Query Language (SQL) in mid of 1970’s.
 Oracle incorporated in the year 1979.
 Structured Query Language (SQL) used by IBM/DB2 and DS Database Systems.
 Structured Query Language (SQL) adopted as standard language for RDBS by ASNI in 1989.

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.

 Expressions, which can produce either values or consisting of and


of data.

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

 Queries which retrieve data based on specific criteria.

 Statements which may have a persistent effect on schemas and data, or which may control

transactions, program flow, connections, sessions, or diagnostics.


 Structured Query Language (SQL) statements also include the (";") statement terminator. Though not
Required on every platform, it is defined as a standard part of the Structured Query Language (SQL) grammar.
 is generally ignored in Structured Query Language (SQL) statements and queries, making it
Easier to format Structured Query Language (SQL) code for readability.
There are five types of Structured Query Language (SQL) statements. They are:
1. Data Definition Language (DDL) (DDL)
2. Data Manipulation Language (DML) (DML)
3. DATA RETRIEVAL LANGUAGE (DRL)
4. TRANSATIONAL CONTROL LANGUAGE (TCL)
5. DATA CONTROL LANGUAGE (DCL)
1. Data Definition Language (DDL) (DDL): The Data Definition Language (DDL) (DDL) is
commonly applied to create and destroy databases and database objects. These commands will
primarily be used by database administrators during the setup and removal phases of a database
project. Let's take a look at the structure and usage of four basic DDL commands:
1. CREATE 2. ALTER 3. DROP 4. Give a new name to the
existing object

1. CREATE:
(a) Creating a new table: This is commonly applied to create a new relation (table)

General SQL Format: Creating a new table


<relation_name/table_name > (field_1 data_type (size),
field_2 data_type (size),
...)
Illustration:
Structured Query Language (SQL)> Creating a new table Student (sno NUMBER (3), sname CHAR (10),
class CHAR (5));
2. ALTER:
(a) Making changes to an existing table ...ADD...: This is commonly applied to add some
extra fields into existing relation.
General SQL Format: Making changes to an existing table relation_name ADD (new field_1
data_type (size), new field_2 data_type (size)...);
Illustration: Structured Query Language (SQL)>Making changes to an existing table STD ADD (Address CHAR
(10));
(b) Making changes to an existing table...MODIFY...: This is commonly applied to change
the width as well as data type of fields of existing relations.

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;

Illustration: Structured Query Language (SQL)>Deleting a table completely STD;

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)

2. Add a new column; HIREDATE to the existing relation.


3. Change the data type of JOB_ID from char to varchar2.
4. Change the name of column/field Emp_no to E_no.
5. Modify the column width of the job field of emp table
Creating a new table EMPLOYEE

( Emp_no INT unique primary

identifier, E_name VARCHAR (100),

E_address VARCHAR (255),

E_ph_no VARCHAR (15), Dept_no

INT,

Dept_name VARCHAR (100),

Job_id CHAR (10),

Salary DECIMAL (10, 2)

);

Making changes to an existing table

EMPLOYEE ADD COLUMN

HIREDATE DATE;

Making changes to an existing table

EMPLOYEE MODIFY COLUMN Job_id VARCHAR

(50);

Making changes to an existing table EMPLOYEE

CHANGE COLUMN Emp_no E_no INT; Making changes to

an existing table EMPLOYEE

MODIFY COLUMN Job_id VARCHAR (20); DESCRIBE

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;

Illustration: Structured Query Language (SQL)>Remove records using FROM STD;


b) Remove records using -FROM-WHERE: This is commonly applied to Remove records using a selected
record from a relation.
General SQL Format: Structured Query Language (SQL)>Remove records using FROM
relation_name WHERE condition;
Illustration: Structured Query Language (SQL)>Remove records using FROM student WHERE
sno = 2;
5. TRUNCATE: This command will remove the data permanently. But structure will not be
removed.
Difference between Truncate & Remove records using:-
 By using truncate command data will be removed permanently & will not get back where as
by using Remove records using command data will be removed temporally & get back by
using roll back command.
 By using Remove records using command data will be removed based on the condition
whereas by using truncate command there is no condition.
 Truncate is a DDL command & Remove records using is a DML command.
General SQL Format: TRUNCATE TABLE <Table name>

Illustration TRUNCATE TABLE student;


 To Retrieve data from one or more tables.
1. Fetch data using FROM: To display all fields for all
records. General SQL Format : Fetch data using *
FROM relation_name; Illustration : Structured Query
Language (SQL)> Fetch data using * from dept;
DEPTNO DNAME LOC
10 ACCOUNTING NEW YORK

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

LAB PRACTICE ASSIGNMENT:


Create a table EMPLOYEE with following schema:
(Emp_no, E_name, E_address, E_ph_no, Dept_no, Dept_name, Job_id, Salary)
Write Structured Query Language (SQL) queries for following question:
1. Add records using aleast 5 rows in the table.
2. Display all the information of EMP table.
3. Display the record of each employee who works in department D10.
4. Modify data using the city of Emp_no-12 with current city as Nagpur.
5. Display the details of Employee who works in department MECH.
6. Remove records using the email_id of employee James.
7. Display the complete record of employees working in SALES Department.
Creating a new table EMPLOYEE

( Emp_no INT unique primary

identifier, E_name VARCHAR

(100),

E_address VARCHAR (255),

E_ph_no VARCHAR (15),

Dept_no VARCHAR (10),

Dept_name VARCHAR (100),

Job_id VARCHAR (20),

Salary DECIMAL (10, 2));


Add records using INTO EMPLOYEE (Emp_no, E_name, E_address, E_ph_no,
Dept_no,
Dept_name, Job_id, Salary) VALUES

(10, 'Alice', 'Mumbai', '9876543210', 'D10', 'HR', 'HR01', 50000.00),

(11, 'Bob', 'Delhi', '9123456780', 'D20', 'SALES', 'SL01', 60000.00),

(12, 'Charlie', 'Pune', '9988776655', 'D10', 'MECH', 'ME01', 55000.00),

(13, 'James', 'Chennai', '9090909090', 'D30', 'SALES', 'SL02', 58000.00),

(14, 'David', 'Hyderabad', '9001234567', 'D40', 'FINANCE', 'FN01', 62000.00);

Fetch data using * FROM EMPLOYEE;

Fetch data using * FROM EMPLOYEE WHERE Dept_no = 'D10';

Modify data using EMPLOYEE SET E_address = 'Nagpur' WHERE

Emp_no = 12; Fetch data using * FROM EMPLOYEE WHERE

Dept_name = 'MECH';

Modify data using EMPLOYEE SET E_ph_no = NULL WHERE

E_name = 'James'; Fetch data using * FROM EMPLOYEE WHERE

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 SUM (Sal) From EMP;


3. AVG: AVG followed by a column name returns the average value of that column values.
General SQL Format: AVG (n1, n2...)

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)

Illustration: Fetch data using MAX (Sal) FROM EMP;

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

deptno having max (sal)<3000; DEPTNO MAX (SAL)


30 2850
5. MIN: MIN followed by column name returns the minimum value of that column.
General SQL Format: MIN (Column name)

Illustration: Fetch data using MIN (Sal) FROM EMP;


Structured Query Language (SQL)>Fetch data using deptno, min (sal) from EMP group by deptno

having min (sal)>1000; DEPTNO MIN (SAL)

10 1300
CHARACTER FUNCTION:
Initcap (char): Fetch data using initcap (“hello”)

from dual; lower (char): Fetch data using lower

(„HELLO‟) from dual; upper (char): Fetch data

using upper („hello‟) from dual;

ltrim (char, [set]): Fetch data using ltrim („cseit‟,

„cse‟) from dual; rtrim (char,[set]): Fetch data using

rtrim („cseit‟, „it‟) from dual;

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.

Structured Query Language

(SQL)>Fetch data using to_char

(65,'RN') from dual; LXV

To number: TO_NUMBER converts expr to a value of NUMBER data type.

Structured Query Language (SQL)>Fetch data


using to number ('1234.64') from Dual; 1234.64
To_date:TO_DATE converts char of CHAR, VARCHAR2, NCHAR, or
NVARCHAR2 data type to a value of DATE data type.
Structured Query Language (SQL)>Fetch data using TO_DATE ('January 15, 1989, 11:00 A.M.') FROM
DUAL;
TO_DAT

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

(‘ORACLE’,’CORPORATION’) FROM DUAL;

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

LTRIM (‘SSMITHSS’,’S’) FROM DUAL;

MITHSS

Rtrim: Returns a character string after truncating all trailing blanks


Structured Query Language (SQL)>Fetch data using RTRIM
(„SSMITHSS‟, ‟S‟) FROM DUAL;
SSMITH
Lower: Returns a character expression after converting uppercase character data to lowercase.
Structured Query Language (SQL)>Fetch data using LOWER (‘DBMS’) FROM DUAL;

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

(‘ABCDEFGHIJ’3, 4) FROM DUAL; CDEF

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:

Sysdate: Structured Query Language (SQL)>Fetch


data using SYSDATE FROM
DATE
DUAL; 29- DEC-08

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

last_day: Structured Query Language (SQL)>Fetch data using


LAST_DAY (SYSDATE) FROM DUAL; 31-DEC-
08

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

Round: Structured Query Language (SQL)>Fetch data using ROUND


(SYSDATE,'DAY') FROM DUAL; 28-DEC- 08
Structured Query Language (SQL)> Fetch data using
to_char: to_char (sysdate, "dd\mm\yy") from dual;
24-mar-05.

to_date: Structured Query Language (SQL)> Fetch data using


to date (sysdate, "dd\mm\yy") from dual; 24-
mar-o5.

LAB PRACTICE ASSIGNMENT:


Create a table EMPLOYEE with following schema:
(Emp_no, E_name, E_address, E_ph_no, Dept_no, Dept_name, Job_id, Designation, Salary)
Write Structured Query Language (SQL) statements for the following query.
1. List the E_no, E_name, and Salary of all employees working for MANAGER.

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.

5. List the employees who are either „CLERK‟ or „ANALYST‟.

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.

8. List the Enames those are starting with „S‟.

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: Returns all distinct rows selected by both the queries

Union all: Returns all rows selected by either query including the duplicates.

Intersect: Returns rows selected that are common to both queries.

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

(Fetch data using DISTINCT DEPTNO

FROM EMP); (Fetch data using DEPTNO

FROM DEPT)

UNION ALL

(Fetch data using DEPTNO FROM EMP);


(Fetch data using DISTINCT DEPTNO FROM EMP MINUS Fetch data using DISTINCT

DEPTNO FROM DEPT) UNION

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

T General SQL Format:

h Fetch data using column 1, column 2, and column

e 3... FROM table_name1, table_name2


WHERE table_name1.column name = table_name2.columnnam

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

– Right 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

 Group by & Having Clause


 Order by Clause
 Indexing
Learning Objective:
To learn the concept of group functions
Background Concept:
 GROUP BY: This query is commonly applied to group to all the records in a relation together for
each and every value of a specific key(s) and then display them for a selected set of fields the
relation.
General SQL Format: Fetch data using <set of fields>
FROM <relation_name> GROUP BY
<field_name>;

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.

General SQL Format:


CREATE INDEX <index_name> on <table_name> (attrib1, attrib 2….attrib n);
Illustration:
CREATE INDEX id1 on EMP (empno, dept_no);
LAB PRACTICE ASSIGNMENT:
Create a relation and implement the following queries.
1. Display total salary spent for each job category.
2. Display lowest paid employee details under each manager.
3. Display number of employees working in each department and their department name.
4. Display the details of employees sorting the salary in increasing order.
5. Show the record of employee earning salary greater than 16000 in each department.
6. Write queries to implement and practice the above clause.
Fetch data using job, SUM (salary) AS total_salary FROM Employees GROUP BY job;

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 * FROM Employees ORDER BY

salary ASC; Fetch data using * FROM Employees

WHERE salary > 16000;

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

U  OPERATORS (IN.ANY, ALL, <,>,>=, <= Etc ..

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.

neral SQL Format: CREATE VIEW <view_name> AS


Fetch data using <set of fields> FROM relation_name

Illustrati WHERE (Condition)


on:

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:

General SQL Format: CREATE OR REPLACE VIEW


view_name AS Fetch data using column_name(s)
FROM table_name
WHERE condition
DROPPING A VIEW: A view can deleted with the DROP VIEW command.
General SQL Format: DROP VIEW <view_name>;
LAB PRACTICE ASSIGNMENT:
Consider the following schema: Sailors
(Sid, sname, rating, age) Boats (bid,
bname, color) Reserves (Sid, bid,
day (date))
Write sub query statement for the following queries.
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.

Fetch data using * FROM Sailors

WHERE Sid IN (Fetch data using Sid FROM Reserves WHERE

bid = 101); Fetch data using b.bname FROM Boats b

WHERE b.bid IN (Fetch data using r.bid FROM Reserves r JOIN Sailors s ON r.sid = s.sid WHERE s.sname

= 'Bob'); Fetch data using s.sname FROM Sailors s

WHERE s.sid IN (Fetch data using r.sid FROM Reserves r JOIN Boats b ON r.bid = b.bid WHERE b.color =

'red') ORDER BY s.age;

Fetch data using s.sname FROM Sailors s

WHERE s.sid IN (Fetch data using r.sid FROM Reserves

r); Fetch data using 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 s.sid FROM Sailors s

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',

'green')); Fetch data using s.sname, s.age

FROM Sailors s

WHERE s.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 (Sid) >= 2;


Experiment No: 8
Title: • Study & Practical implementation and learning of different types of constraints
Learning Objective:
 To practice and implement constraints
Background Concept:

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.

General table Table_Name (column_name data_type (size) NOT NULL,);


SQL
Format:
Creating a new table student (sno NUMBER (3) NOT NULL, name CHAR (10));

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.

Creating a new table Table_Name (column_name data_type (size) UNIQUE, ….);

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

Creating a new table Table_Name (column_name data_type (size) CHECK (logical


expression), ….);

Illustrati SQL Format:


on:

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 );

Defining integrity constraints in the Making changes to an existing table command:


General SQL Format: Making changes to an existing table Table_Name ADD unique primary
identifier (column_name);

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

unique primary identifier (colname)

Illustration: Making changes to an existing table student ADD CONSTRAINT SN unique primary
identifier (SNO)

Dropping integrity constraints in the Making changes to an existing table command:


General SQL Format: Making changes to an existing table Table_Name DROP constraint name;

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;

Illustration: Making changes to an existing table student DROP CONSTRAINT SN;

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

EMPNO NUMBER (6)

ENAME VARCHAR2 (20)

JOB VARCHAR2 (10)


DEPTNO NUMBER (3)

SAL NUMBER (7, 2)

Allow NULL for all columns except ename and job.


2. Add constraints to check, while entering the empno value (i.e.) empno > 100.
3. Define the field DEPTNO as unique.
4. Create a unique primary identifier constraint for the table (EMPNO).
5. Write queries to implement and practice constraints.

Creating a new table EMP


( EMPNO NUMBER (6) NOT
NULL,
ENAME VARCHAR2 (20) NOT
NULL, JOB VARCHAR2 (10) NOT
NULL, DEPTNO NUMBER (3),
SAL NUMBER (7, 2),
CONSTRAINT PK_EMP unique primary
identifier (EMPNO),
CONSTRAINT CHK_EMPNO CHECK (EMPNO >
100), CONSTRAINT UNIQUE_DEPTNO UNIQUE
(DEPTNO)
);
Making changes to an existing table EMP
ADD CONSTRAINT CHK_EMPNO CHECK (EMPNO > 100);
Making changes to an existing table EMP
ADD CONSTRAINT UNIQUE_DEPTNO UNIQUE
(DEPTNO); Making changes to an existing table EMP
ADD CONSTRAINT PK_EMP unique primary identifier
(EMPNO); Add records using INTO EMP (EMPNO,
ENAME, JOB, DEPTNO, SAL) VALUES (50, 'John',
'Manager', 10, 5000);
Add records using INTO EMP (EMPNO, ENAME, JOB,
DEPTNO, SAL) VALUES (101, 'Alice', 'Clerk', 10, 3000);
Add records using INTO EMP (EMPNO, ENAME, JOB,
DEPTNO, SAL) VALUES (102, 'Bob', 'Developer', 20, 4000);
Modify data using
EMP SET
EMPNO = 90
WHERE ENAME =
'Alice'; Modify data using
EMP
SET DEPTNO = 10
WHERE ENAME =
'Bob';

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)

t statements are undo (or) role

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

be role back) ROLLBACK to save point ID;

Illustration: Structured Query Language (SQL)> ROLLBACK;


Structured Query Language (SQL)> ROLLBACK TO SAVE POINT xyz;
LAB PRACTICE ASSIGNMENT:
1. Write a query to implement the save point.
2. Write a query to implement the rollback.
3. Write a query to implement the commit.
Add records using INTO EMP (EMPNO, ENAME, JOB, DEPTNO, SAL) VALUES (201, 'Ali',
'Clerk', 30, 3000); SAVEPOINT sp1;
Add records using INTO EMP (EMPNO, ENAME, JOB, DEPTNO, SAL) VALUES (202, 'Ahmed',
'Manager', 40, 7000); ROLLBACK TO sp1;
COMMIT;
Experiment No: 10
Title: Creating Database/ Table Space
 Managing Users: - Create User, Remove records using User
 Managing Passwords
 Managing roles: - Grant , Revoke
Learning Objective:
 To get a better understanding of the concept of administrative command
Backgr DATABASE is collection of coherent data.
ound
Concep To create database we have:
t: General SQL Format: CREATE DATABASE
<database_name> Illustration: CREATE
DATABASE my_d

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)

GRAN privileges to other user.


T:

Structured Query Language (SQL)> GRANT privile ge [ privilege…. …]


General
SQL TO USER;
Format:
Structured Query Language (SQL)> Grant succeeded
Eg: Grant creates session, Creating a new table, and create view to James;
The Object privileges vary from object to object. An owner has all privilege or specific privileges
DBA
on object.
uses the
GRAN Structured Query Language (SQL)>
T
GRANT object_priv [(column)]
stateme
nt to ON object
allocate
system
TO user;
Structured Query Language (SQL)>GRANT Fetch data
using, Add records using ON EMP TO James;
Structured Query Language (SQL)>GRANT Fetch data
using, Modify data using (e_name, e_address)

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.

General Alter USER <some user name>


SQL IDENTIFIED BY<New
Format:
password>

Eg: ALTER USER James


IDENTIFIED BY sam

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;

LAB PRACTICE ASSIGNMENT:


1. Create user and implement the following commands on relation (EMP and Dept).
2. Develop a query to grant all privileges of employees table into departments table.
3. Develop a query to grant some privileges of employees table into departments table.
4. Develop a query to revoke all privileges of employees table from departments table.
5. Develop a query to revoke some privileges of employees table from departments table.

CREATE USER DEPT IDENTIFIED BY


dept123;

GRANT CONNECT, RESOURCE TO DEPT;

Creating a new table EMP (emp_id NUMBER


unique primary identifier, emp_name
VARCHAR2 (100), salary NUMBER);

Creating a new table DEPT_TABLE (dept_id


NUMBER unique primary identifier,
dept_name VARCHAR2 (100));

GRANT ALL ON EMP TO DEPT;

GRANT Fetch data using, Add records using


ON EMP TO DEPT;

REVOKE ALL ON EMP FROM DEPT;

REVOKE Add records using ON EMP FROM


DEPT;

You might also like