Unit - 3 - K - Interactive - SQL and Performance - Tuning
Unit - 3 - K - Interactive - SQL and Performance - Tuning
DATA TYPES
1. NUMERIC DATA TYPES
INT or INTEGER
SMALLINT
NUMBER
This includes changes to the structure of the table like creation of the table, altering
table, deleting structure of the table(i.e. drop)
All DDL commands are auto committed that means it saves all the changes
permanently.
e.g. List of DDL commands
1. Create
2. Alter
3. Describe
4. Drop
5. Truncate
6.Rename
1) CREATE
This command is used to create the table or define the structure of the table.
2) DESCRIBE or DESC
Used to describe the structure of the table
Syntax:
desc tablename;
OR
Describe tablename;
e.g:
desc student;
desc Emplyee;
4)TRUNCATE
This command is used to delete all data/records or rows .
After using this command only all records/data deleted ,the structure of the table
remains same. i.e the table structure remains as it is.
After truncate the space will frees, we can reenter the data.
Syntax
5) RENAME
This command is used to rename the name of table. That is we can give new name
to table.
Syntax:
Rename old_table_name to new_table_name;
3)ALTER
Syntaxes:
syntax:
syntax:
alter table table_name drop column column_name;
Syntax:
Alter table table_name add primary key(column_name);
in above example we have added or set the primary key for column rollno.
Syntax:
alter table table_name drop primary key;
Sytax:
alter table table_name modify column_name datatype(size);
Syntax:
Alter table table_name rename column old_column_name to
new_column_name;
6) DROP
This command is used to delete the structure of table. That is the whole table
structure is deleted with data permanently i.e. table does not exists.
Syntax:
in above example the structure of the emp table is deleted .it will does not exist
after using this command.
ii) Update:
this command is used to update the column values which are inserted already. This
command is used to update or modify single or multiple rows of the table.
Syntax:
update table_name set column_name=value where condition;
Example:
update student set name=’pravin’ where rollno=3;
in above ex name of rollno 3 is updated to pravin instead of raj.
iii) DELETE
Detele command is used to delete single or multiple records from table.You can delete
specific rows using where condition/clause.When all rows deleted structure of the
table remains same
Syntaxes:
above example deletes all rows/records/details from table student but table structure
remains same.
4) select
SYNTAX:
1)To display all records/rows with all column values.
d)for applying more than one conditions we can use logical operators i.e
AND,OR,NOT with select command
example:
1) select name, maks from student where rollno< 3 and name= ‘pravin’;
2) select rollno,name, dob from student where rollno< 4 or name= ‘rupali’;
3) select rollno, name where rollno not like 5;
GRANT
Grant command is used to provide access or privileges on the database objects to the
users.
Syntax
GRANT privilege_name ON object_name TO user_name ;
Example:
1) GRANT insert, update ON student TO pravin ;
2) Grant select,delete, create table on student to ajay;
3) Grant insert,delete on emp to priya;
2. REVOKE
Revoke command removes/denies user access rights or privileges from the user on the
database objects.
Once you have granted privileges, you may to remove some or all of these privileges.
Revoke means taking authorization back from user.
The revoke command is used to denied grant given on the object.
Syntax
Example
REVOKE insert, update ON emp FROM pravin ;
Example:
1) Revoke all on emp from riya;
1)commit
Commit command is used to end the transaction permanently and also make the effect
permanent to the database. That is it save the transaction/ changes permanently.
Syntax:
Commit;
Example: commit;
Or
2)savepoint
savepoint command is used to temporarily save transaction so that you can rollback to
that point whenever required
Syntax:
Savepoint savepoint_name;
3) Rollback:
This command restores the database to last committed state/ transaction.It is also used
with savepoint command to jump to a savepoint in an ongoing transaction.
Syntax:
ROLLBACK;
Example: rollback;
OR
ROLLBACK WORK;
OR
ROLLBACK TO SAVEPOINT_NAME;
Example:
Rollback to savepoint s1;
3.2 Clauses & Join:- Different types of clauses - Where, Group by ,Order
by, Having. Joins: Types of Joins, Nested queries.
1)Where Clause
Where clause is used with DML commands like update, delete, select except insert.
The condition in where is made up with operand(column) operator value (e.g :
salary>=20000)
Sou.Venutai Chavan Polytechnic, Pune Page 14
Ms.S.A.Kshirsagar DMS Notes SYCM-3-K
2)GROUP BY:
The group by clause used in a select statement to collect data across multiple
records and group by one or more columns.
It is used to divide the multiple rows/records in a table into groups by single or many
columns.
Aggregate functions are used to group multiple columns with one command.
Group by clause displays multiple records grouped together by one column.
Syntax:
ename Count(eno)
A 2
B 2
C 1
D 1
3)display maximum, minimum salary ,sum and number of employees with name
/for each name/ for every name.
O/p
ename Max(sal) Min(sal) Sum(sal) Count(eno)
A 5000 4000 9000 2
B 6000 3000 9000 2
C 9000 9000 9000 1
D 10000 10000 10000 1
3)Having clause
It can be used in a select statement to display the records.
It is like a where clause, except that it involves a summary value, rather than a column
value. i.e it uses aggregate function.
The having clause operates after the summation has been done.
Syntax :
Select col1,col2,….,col n aggregate_function (expression) From table_name Where
condition Group by column_name Having condition 1,condition2;
e.g: Select deptno, sum(sal) from employee group by deptno having sum(sal)>10000;
deptno sum(sal)
22 12000
ename avg(sal)
c 9000
d 10000
4)Order by clause:
This clause is used for getting the result in particular order i.e. by descending or
ascending order.
By default the order is ascending.
To sort the records in a descending order, you can use the DESC keyword and
for ascending ASC
The order by keyword is used to sort the result set by one or more columns.
.
Syntax:
SELECT column_name1,column_name2,…column_name_n
FROM table_name
ORDER BY column_name ASC|DESC;
Example:
SELECT * FROM employee ORDER BY deptno ASC ;
or
o/p:
Eno Ename Deptno Sal
1 A 11 5000
2 B 22 3000
3 C 22 9000
4 A 33 4000
5 B 33 6000
6 D 44 10000
O/P:
Eno Ename Deptno sal
6 D 44 10000
3 C 22 9000
5 B 33 6000
1 A 11 5000
4 A 33 4000
2 B 22 3000
SQL JOINS:
Consider the relations/ tables,
Student Result
Syntax :
SELECT column_name_list
from table_name1
INNER JOIN
table_name2
on table_name1.column_name = table_name2.column_name;
Example:
SELECT * from student inner join result on student.rollno = result.rollno;
1. Left outer join (also known as left join): this join returns all the rows/records from
left table combine with the matching rows of the right table. If no value matching in
the right table it returns NULL values.
syntax :
SELECT column_name_list from table_name1 LEFT OUTER JOIN table_name2 on
table_name1.columnname = table-name2.column-name;
Example:
2. Right outer join (also known as right join): this join returns all the rows from
right table are combined with the matching rows of left table .If no value matching in
the left table, it returns null value.
Syntax:
SELECT column-name-list from tablename1 RIGHT OUTER JOIN table-name2 on
tablename1.column-name = table-name2.column-name;
Example:
SELECT * FROM student right OUTER JOIN result ON student.rollno=result.rollno;
o/p:
Rollno Name address Rollno Percentage
1 Priya Pune 1 90
4 Raju Baner 4 85
NULL NULL NULL 3 88
NULL NULL NULL 9 75
3. The full outer join keyword returns all records when there is a match in either left
(table1) or right (table2) table records. Those values are not matching it will returns
null value.
Syntax:
SELECT column_name list from table_name1 full outer join table_name2 on
table1.column_name =table2.column_name;
Example:
A subquery or inner query or nested query is a query within another query and
embedded within the where clause.
The statement containing subquery is called as parent statement.
Subwueries can be used with select ,insert,update and delete statementsalong with the
operators lke =,>,<,>=,<=,IN,BETWEEN etc
Types: 1) single row subquery,(=,<,>,<=,>=)
2)multiple row subquery (IN,ANY,ALL).
SYNTAX:
Select column_name_list From table_name where expression operator (select
column_name_list from table_name where condition);
Example:
Select * from employee where sal=(select max(sal) from employee);
o/p: consider employee table
Rules:
1)subqueries enclosed within parenthesis
2)A subquery can have only one column in select clause.And multiple columns in the
main/parent query.
3)order by clause not used in subquery.it can be used in main query.
4)in subquery use multiple rows IN operator.
5)BETWEEN not used in subquery.
o/p:250
2)CEIL(a):
Returns the smallest integer greater than or equal to passed number.
Eg:select ceil(48.876) from dual;
o/p:49
3)floor(a):
4)exp(a):
It returns exponential value .
Select exp(5) from dual;
o/p:148.4131
5)LN(a):
This function returns natural logarithm of value ‘a’.
e.g:selectln(1000) from dual;
o/p:6.9077
6)log(a,b):
Log function returns logarithm of b to the base a
e.g: select log(100,10) from dual;
o/p: 0.5
7)mod(a,b)
returns the reminder of the division a/b
e.g: select mod(5,2) from dual;
o/p:1
8)power(a,b) :
returns the value of power a to b
select power(2,3) from dual;
o/p :8
9)SIGN(a):
This function shows the negative or positive number.
It returns 1 if a>0
And it returns -1 if a<0
Returns 0 if a=0
e.g select sign(-22) from dual;
o/p: -1
e.g: select sign(12) from dual;
o/p: 1
10)SIN(a):
It returns the sine of angle of a
e. g: select sin(90) from dual;
o/p: 0.89399
11)SQRT(a) :
it returns the square root of value a.
e.g: select sqrt(15) from dual;
o/p: 4
12)Round(a,b):
7) Sysdate
It returns system date.
e.g select sysdate from dual;
String functions:
Aggregate functions:
Aggregate functions are functions where the values of multiple rows are grouped
together to form a single value
1)avg(expression):
this function computes average of column.
e.g:select avg(salary) from employee;
o/p:6166.67
2)count(expression):
Counts the records/rows defined by the expression.
e.g: select count(eno) from employee;
o/p: 6
3)min(expression):
This function returns the minimum value of column.
e.g: select min(salary) from employee;
o/p:3000
4)max(expression):
This function returns the maximum value of column.
e.g: select max(salary) from employee;
o/p:10000
5)sum(expression)
Sou.Venutai Chavan Polytechnic, Pune Page 27
Ms.S.A.Kshirsagar DMS Notes SYCM-3-K
SQL OPERATORS:
SQL operators are used to operate on value or numbers.
The SQL operators are as follows:
1) Relational,
2) Arithmetic,
3) Logical,
4) Set operators.
Arithmetic Operators:
List and explain any 4 arithmetic operators in SQL with example.
+ (addition)
- (subtraction)
* (multiplication
/ (division)
mod(a,b)
Addition
Addition is performed using the plus (+) symbol.
Example
SELECT SALARY + 20000 As “total_sal” FROM EMP;
O/p
total_sal
55000
40000
45000
355000
80000
Meaning:
The SALARY column is added with the 20000 for each row of data .
Subtraction
Subtraction is performed using the minus (-) symbol.
e.g
SELECT SALARY –5000 As “decremented_sal” FROM EMP;
O/P
decremented_sal
30000
15000
20000
Sou.Venutai Chavan Polytechnic, Pune Page 29
Ms.S.A.Kshirsagar DMS Notes SYCM-3-K
10000
55000
Meaning:
The SALARY column is substracted by 5000 for each row of data
Multiplication
Multiplication is performed by using the asterisk (*) symbol.
Example:
SELECT SALARY * 10 FROM EMP;
Salary*10
350000
200000
250000
150000
600000
Meaning:
The SALARY column is multiplied by 10
Division
Division is performed through the use of the ‘/’ symbol.
e.g
SELECT SALARY / 10 FROM EMP;
o/p
Salary/10
3500
2000
2500
1500
6000
Meaning:
The SALARY column is divided by 10
Logical Operators:
It is used with specific or combination of conditions.
There are 3 logical operators
AND –used when all the conditions must be true.
OR -used when one of the condition is to be true.
NOT – it uses negation
Examples:
Select * from emp where salary > 20000 and salary < 40000;
Select * from emp where address=’pune’ or address= ‘kolhapur’;
Select empname, salary, address from employee where address not like ‘pune’;
Sou.Venutai Chavan Polytechnic, Pune Page 30
Ms.S.A.Kshirsagar DMS Notes SYCM-3-K
F)SET OPERATORS:
When we want to combine the result of twoqueries then the special type of operators
are used known as set operators.
Used to join queries and retrieve theh number of rows.
Set operators are as follows:
Union
Union all
Intersect
Minus
Consider the tables,
Employee Department
Union
It select/combines values of same attribute from different table with avoiding duplicate
values.
Union operator selects different values of same attribute from different related tables.
e.g: select empid from employee union select empid from department;
output: empid
1
2
3
4
8
10
11
12
Union all
It selects/combines all values of same attribute from different related tables without
avoiding duplicate values.
i.e. Union all operator combines all records from both the queries without avoiding
duplicate values.
Select empid from employee union all select empid from department;
output: empid
1
2
3
4
8
10
1
2
8
10
11
12
Intersect
It selects similar values of same attribute from different related tables.
e.g. select empid from employee intersect select empid from department;
Output: empid
1
2
8
10
Minus
It performs the subtraction. i.e. values present in first table and not in second table are
displayed.
e.g. select empid from employee minus select empid from department;
Output: empid
3
4
e.g. select empid from department minus select empid from employee;
Output:
empid
11
12
Example:
select * from emp where salary in(35000,60000,17000);
NOT IN:
Syntax: x not in (y,z)
This operator tests that operand x does not match any elements of list provided
Example: select * from emp where salry not in (35000,60000,17000);
BETWEEN:
Syntax: x between y and z
Tests that operand x is greater than or equal to operand y and less than or equal to
operand z.
It is used numeric and date datatype.
Example.
Select * from emp where salary between 20000 and 35000;
Meaning: it will display details of employees whose salary between 20000 and 35000.
Meaning: it will display details of employees whose salary between 15000 and
25000.
like:
like operator is used for pattern matching operator.
This is used with NOT logical operator i.e Not like
Example:
Select empno, deptname from employee where deptname like ‘p%’;
Meaning: It displays empid , deptname whose deptname start from p i.e p on first
location.
Display empno,deptname whose employee does not contain ‘a’ at 2nd location.
Ans: select empno,deptname from employee where deptname not like ‘_a%’;
Display empno,deptname whose deptname contain ‘d’ at start and ‘n’ at end
location.
Ans: select empno,deptname from employee where deptname like ‘d%n’;
o/p- empno deptname
3 design
Display empno whose deptname ended with ‘s’.
Ans: select empno from department where deptname like ‘_%s’;
o/p no rows are selected
Def: A view is a logical extract of a physical relation i.e. it is derived from any base
relation.
OR
View: Views are virtual relations mainly used for security purpose, and can be
provided on request by a particular user.
create view.
Create view command used to create view .
Syntax
2) create view as empdetails with ename ,deptno,and salary of employee table whose
salary more than 6000.
Update view:
Update view command is used to update view.
i.e it is used to update data/ rows/record of the view. Same changes will reflect in
base table also.
Syntax:
Update view_name set column_name=value where condition;
Example:1)
Update v1 set salary=salary+1000 where empno=3;
DROP VIEW
Drop view command is used to drop/delete the view permanently.
It Drops the specified view . base table will not drop.it remains as it is.
Syntax:
Example:
OR
CREATE VIEW EMPVIEW AS SELECT * FROM EMPLOYEE WHERE SALARY
>
20000;
4) insert view:-
To insect records/data in view use the command insert.
Syntax:
insert into viewname Values (valuel, value 2, --valuen);
OR
insert into viewname. (coll, con,…coln) values (value1, value2, ….,valuen);
Example:
OR
To delete specific record of view:
delete from Viewname where condition;
Sou.Venutai Chavan Polytechnic, Pune Page 38
Ms.S.A.Kshirsagar DMS Notes SYCM-3-K
Examples:
1. delete from v1;
2. delete from emp_details where ename = 'raj';
select view:-
display list /rows/records of a view.
syntax:
select * from viewname;
OR
select * from viewname where condition;
OR
select coll, col2, from viewname where condition;
Example:
select * from v1;
select * from v1 where eno = 2
select ename, deptno from emp_details where deptno= 5;
Advantages of Views:
1. Views restrict access to the data because the view can display selective columns
from the table.
2. Views can be used to make simple queries to retrieve the results of complicated
queries. For example, views can be used to query information from multiple
tables without the user knowing how to write a join statement.
3. Views provide data independence for adhoc users and application programs.
One view can be used to retrieve data from several tables.
4. Views provide groups of users to access to data according to their particular
criteria. Thus implements security and authorization.
Sequences:
Oracle provides an object called as a Sequence that can generate numeric values.
The value generated can have maximum of 38 digits.
These numbers can be ascending or descending order.
Provide intervals between numbers
Sequence creates a series of values which are computer generated and which can
be
inserted into a table.
Use:
1. It saves a time by reducing application code.
2. It is used to generate unique sequential integers.
3. It is used to create an auto number fields.
4. Sequence can be use for many tables/relations
Operations on sequence:
1) Create sequence :
where,
Example :
create sequence seq_1increment by 1 start with 1 minivalue 1 maxvalue 999 cycle;
Syntax:
Insert into table_name values(sequence_name.nextval,value2,value3,…value_n);
in above example, automatically Insert values for rollno field sequentially in student
by using sequence seq_1 as:
Rollno name
1 riya
2 rohit
Example:
Select seq_1.currval from student;
Alter sequence
A sequence can be altered using alter sequence command. A sequence once created
can be altered. By using this we can alter/change minimum_value, maximum_value
i.e value of MINVALUE, MAXVALUE varables. This is achieved by using the
ALTER SEQUENCE statement.
SYNTAX:
Example:
alter sequence seq_1 maxvalue 75;
Drop/Delete Sequence
The DROP SEQUENCE command is used to remove the sequence from database.
Syntax:
Q.create sequence
Index:
Definition: An index is a schema object that can speed up the retrieval of rows by
using pointer.
Indexes are used to speed up searches/queries.
An index provides direct and fast access to rows in a table.
Indexes are created explicitly Or automatically.
Types of index:
a) Simple Index
b) Composite Index
c) Unique Index.
A) SIMPLE INDEX:
An index which is is created on only one/ single column of a table is called as simple
index.
Syntax:
Example:
CREATE INDEX index1 on employee (empno);
b) Composite Index:
An index which is created on two or more columns of a table is called composite index
Syntax :
Example:
CREATE INDEX index2 on employee (ename,salary);
c) Unique Indexes:
An index which is created on column which contains unique values(i.e column does
not contain duplicate values) is called as unique index.
Sou.Venutai Chavan Polytechnic, Pune Page 44
Ms.S.A.Kshirsagar DMS Notes SYCM-3-K
Unique indexes are used not only for performance, but also for data integrity. A unique
index does not allow any duplicate values to be inserted into the table.
Syntax :
Example:
CREATE UNIQUE INDEX index3 on employee (eno);
Create unique index index4 on student(rollno);
Alter index:
Syntax:
Alter index old_index_name rename to new_index_name;
Example:
alter index index1 rename to index9;
Drop Index:
By using drop index, Indexes can be deleted permanently
Syntax:
Drop index index_name;
Example:
Drop index index9;
Synonyms:
Synonym is another name given to the table, view, sequence, stored procedure,
function or packages for the user’s convenience to use it.
Create Synonyms:
Syntax:
Create synonym synonym_name for object_name;
Example:
Create synonym emp for employee;
Drop Synonyms:
Syntax:
Drop synonym synonym_name;
Example: Drop synonym emp;
ASSIGNMENT NO 3A
PREVIOUS MSBTE QUESTIONS
Question Exam Mark
s
Explain DCL commands with syntax and example.
List DCL commands. S-19 2M
1 List DCL commands S-19 2M
Describe Grant and Revoke commands with example. S-23 4M
Explain TCL Commands with syntax and example.
2 Explain savepoint and rollback command with example. S-23 4M
Describe commit and rollback with syntax and example. W-18 4M
Explain commit and rollback with syntax and example. W-23 4M
3 Explain any four aggregate functions with example.
Enlist four aggregate functions. W-18 2M
Explain any four aggregate functions with example. S-19 4M
Explain any four aggregate function with example. S-23 4M
State the use of Avg function with example. (S-22) 2M
4 List date and time functions with example.
List date and time functions. S-24 2M
5 Explain string functions with example.
List any four string functions in SQL. W-19 2M
Explain any four string functions with example. W-18 4M
Explain any four string functions. S-22 4M
Explain any four string functions with example. S-23 4M
List any four string functions in SQL. W-23 2M
6 Enlist arithmetic and logical SQL operators with example.
Enlist arithmetic and logical SQL operators. W-22 2M
7 Explain Set operators with example.
Explain set operators with example. S-24 4M
Explain any four set operators in SQL with example. W-19 4M
Explain set operators with example. W-18 4M
8 List the SQL operations and explain range searching operation S-19 4M
‘between’ and pattern matching operator ‘like’ with example.
9 Define View. Write and explain syntax to create , update and
drop view commands with example. State view purpose.
Write query using group by and having clause (use students S-24 4M
database) W-22 4M
State the use of group by and order by clauses.
16 Define Synonym. Explain how to create and drop synonym
with syntax and example.
Write and explain syntax for creating and dropping synonyms S-24 4M
with example S-19 2M
Write syntax for creating synonyms with example.
17 Write and Explain the syntax for creating, Altering and W-22 6M
dropping the sequence.
18 Explain subquery/nested query concept with example. S-23 2M
19 List any four data types in SQL. S-22 2M
ASSIGNMENT 3B(TUTORIAL)
Sr. Question Exam Marks
No
Consider the table Student (name, marks, dept, age, place, S-19 6M
phone, birthdate) Write SQL query for following :
(i) To list students having place as ‘Pune’ or ‘Jalgaon’.
(ii) To list students having same department (dept) as
1 that of ‘Rachana’.
(iii) To change marks of ‘Rahul’ from 81 to 96.
(iv) To list student name and marks from ‘Computer’
dept.
(v) To list student name who have marks less than 40.
(vi) To list students who are not from ‘Mumbai’.
(i) Write a command to create table student (RNo., S-19 6M
2 name, marks, dept.) with proper datatype and RNo
as primary key.
(ii) Write a command to create and drop sequence.
Write a command to create table student (rollno, Stud_name, W-19 6M
branch, class, DOB, City, Contact_no) and write down
queries for following :
(i) Insert one row into the table
3 (ii) Save the data
(iii) Insert second row into the table
(iv) Undo the insertion of second row
(v) Create save point S1 .
(vi) Insert one row into the table.
Sou.Venutai Chavan Polytechnic, Pune Page 49
Ms.S.A.Kshirsagar DMS Notes SYCM-3-K
ii) Use a seq_1 to insert the values into table Student (ID
Number (10), Name char (20));
iii) Change the seq_ 1 max value 20 to 50. iv) Drop the
sequence
Consider the schema Customer (Cust-id, Cust_name, W-22 6M
Cust_addr, Cust_city)
9 i) Create a view on Customer (Cust_id, Cust_name)
where Cust_city is ‘Pune’
ii) Create a sequence on Cust_id
i) Create table Student (S_id, S_name, S_addr, S_marks) S-22 6M
with proper data type and size.
10 ii) Insert row (5, ‘ABC’, ‘RRRRR’, 79) into student table.
iii) Update marks of student 85 where S_id is 5
Consider the following table employee (Emp_id, Emp_name, S-22 6M
Emp_age)
i) Display details of employees whose age is less than 30.
ii) Display details of employees whose age is in between
the range 30 to 60.
11 iii) Display total number of employee whose age is 60.
iv) Display names of employees whose name starts with 'S'.
v) Display details of employees whose name end with 'd'.
vi) Display details of employees whose age is greater than 50
and whose name contain 'e'
Consider following schema” S-24 6M
Book-master (bookid, bookname, author, no_of_copies,
price)
write down SQL queries for following:
12 i) Write a command to create Book_master table.
ii) Increase the price of all books by 20%
iii) Display all books whose price ranges from 500 to 800.
iv) Display all books with details whose name start with ‘D’
v) Dsipaly all books whose number of copies are less than 10.
vi) Display all books whose price is above 700.
13 Create simple and composite index. Write command to drop S-24 6M
index.
i) Write a query to create table emp-details (Emp_ID, name, S-24 6M
dept) with proper data types and Emp_ID as primary key and
14 name as NOT NULL constrain.
ii) Perform all DML command on above created table.
Write SQL queries for following :– W-22 4M
Sou.Venutai Chavan Polytechnic, Pune Page 51
Ms.S.A.Kshirsagar DMS Notes SYCM-3-K