Database Management System
Unit 3 : Interactive SQL and Performance
Tuning
Presented By :
Mrs. Samidha Chavan
Lecturer -Department of Information Tech.
Vidyalankar Polytechnic, Wadala (Mumbai)
3.1 SQL
• Data types
• DDL
• DML
• DCL
• TCL
Structured Query Language
Data types in SQL:
CHAR(size)
VARCHAR(size)/VARCHAR2(SIZE)
Numeric/NUMBER(P,S)- Integer, Float, Decimal etc
DATE
For Example :
Percentage NUMBER(5,2) ;
It can store max value 999.99
PL/SQL data types
• This data type stores the LOB data in the
binary file format up to the maximum size
BLOB of 128 TB.
• it can store the unstructured data such as
multimedia objects, images, etc.
• CLOB data type stores the LOB data into
CLOB and NCLOB the character set, whereas NCLOB stores
the data in the native character set.
• BFILE are the data types that stored the
BFILE unstructured binary format data outside the
database as an operating-system file.
Structured Query Language
Components of SQL:
DDL
Page
6
Data Definition Language
Data Definition Language:
• DDL commands modify the actual structure of a database,
rather than the database’s contents.
• DDL Commands includes:
1. create Student
2. alter
3. drop
4. truncate
5. desc/describe
6. rename
Data Definition Language
CREATE:
It is used to create a new table in the database.
Syntax :
CREATE TABLE TABLE_NAME (
COLUMN1 DATATYPE,
COLUMN2 DATATYPE,
COLUMN3 DATATYPE,
....
);
Data Definition Language
Syntax : Example:
CREATE TABLE TABLE_NAME ( CREATE TABLE EMPLOYEE(
COLUMN1 DATATYPE, NAME VARCHAR2(100),
COLUMN2 DATATYPE, EMAIL VARCHAR2(50),
COLUMN3 DATATYPE,
.... AGE NUMBER(3)
); );
Data Definition Language
ALTER:
• It is used to alter the structure of the database.
• It is used to add new column in a table
• It is used to drop a column from table
• It is used to modify column datatype
• It is used to set primary key of the table
NAME(VARCHAR2(100)) EMAIL(VARCHAR2(50)) AGE(NUMBER(3))
EMPLOYEE
Data Definition Language
To add a new column in the table
Syntax : Example:
ALTER TABLE TABLE_NAME ALTER TABLE EMPLOYEE
ADD COLUMN_NAME ADD CITY VARCHAR2(50);
DATATYPE;
EMPLOYEE
NAME(VARCHAR2(100)) EMAIL(VARCHAR2(50)) AGE(NUMBER(3)) CITY(VARCHAR2(50))
Data Definition Language
To modify column in the table
Syntax : Example:
ALTER TABLE TABLE_NAME
MODIFY ALTER TABLE EMPLOYEE
COLUMN_NAME MODIFY
NEW_DATATYPE; CITY VARCHAR2(80);
Modified Structure of EMPLOYEES TABLE
NAME(VARCHAR2(100)) EMAIL(VARCHAR2(50)) AGE(NUMBER(3)) CITY(VARCHAR2(80))
Data Definition Language
DROP:
It is used to delete both the structure and record stored
in the table.
Syntax :
DROP TABLE TABLE_NAME ;
Example:
DROP TABLE EMPLOYEE;
Data Definition Language
TRUNCATE:
It is used to delete all the rows from the table and free
the space containing the table.
Syntax :
TRUNCATE TABLE table_name;
Example:
TRUNCATE TABLE EMPLOYEE;
Rename
• Rename an object existing in the database
Syntax :
RENAME old-table-Name TO new-Table-Name
Example :
RENAME department TO dept;
Page
15
Describe
• Displays the column definitions for the
specified table.
Syntax :
DESC Object_Name
Example :
DESC dept;
Page
16
DML
Page
17
Data Manipulation Language
Data Manipulation Language:
• DML commands are used for managing data within tables.
• DML Commands includes:
1. insert
2. update
3. Delete
4. Select
Data Manipulation Language
Insert command:
• The INSERT INTO statement is used to insert new records in a
table.
Syntax:
INSERT INTO table_name VALUES (value1, value2, value3, ...);
Example:
INSERT INTO Persons VALUES(111, ‘Mark’, 26);
INSERT INTO Persons VALUES(222, ‘Steve’, 32);
Working with RDBMS
Insert values in Table :
• Insert command is used for inserting values in a table.
• It is DML Command .
Ways to insert values in a table :
Syntax1: syntax for insert command without defining attributes
Insert into <Table_name> values (value1,value2,…..);
Syntax2: syntax for insert command with defining attributes
Insert into <Table_name>(col1,col2,…) values (value1,value2,…..);
Syntax3: To insert values for selected attributes in a table.
Insert into <Table_name>(col1,col2) values (value1,value2);
Syntax4: To insert more than one row.
Insert into <Table_name> values(&attribute1, ‘&attribute2’,…..&attribute n);
Working with RDBMS
Insert values in Table :
Example: Consider table Student
Rollno Name Marks Address
1 Sachin 70 Dadar
2 Amit 80 Kurla
Example1: Insert into Student values(3,’Sita’,40,’Dadar’);
Example2: Insert into Student(Rollno,Name,Marks,Address) values(4,’Savita’,50, ‘Parel ’ );
Example3: Insert into Student(Name,Marks) values (‘Ram’,60);
Example4: Insert into Student values (&Rollno,’&Name’,&Marks,’&Address’);
Data Manipulation Language
update command:
• The UPDATE statement is used to modify the existing records in a
table.
Syntax:
UPDATE table_name
SET column1 = value1, column2 = value2, ...
WHERE condition
Example:
UPDATE Persons
SET age = 28
WHERE ID=111;
Data Manipulation Language
delete command:
• The DELETE statement is used to delete existing records
in a table.
Syntax:
DELETE FROM table_name WHERE condition;
Example:
DELETE FROM Persons WHERE ID=111;
Data Manipulation Language
Select command:
• The SELECT statement is used to Display table with
records
• Syntax:
SELECT * FROM table_name;
OR
SELECT column1,column2.. FROM Table_name;
Example:
SELECT * FROM Persons;
DCL
Page
25
Data Control Language
Grant command:
• This command is used to give permission to user
• Syntax:
GRANT privilege_name
ON object_name
TO {user_name |PUBLIC |role_name}
[WITH GRANT OPTION];
Example:
GRANT SELECT, INSERT, DELETE ON Emp TO user1;
Data Control Language
With Grant option :
• When you grant an access privilege to a user, you
can also give the user the authority to grant the
same privilege to another user.
• For Example :
Grant select on emp to user1 with grant option;
User1 can now use the GRANT statement to issue the SELECT
privilege on the emp table to other users.
Data Control Language
Revoke command:
• Syntax: This command is used to take back permissions from a
user.
• Syntax :
REVOKE privilege_name
ON object_name
FROM {user_name |PUBLIC |role_name};
Example:
REVOKE INSERT ON emp FROM user1;
TCL
Page
29
Transaction Control Language
Transaction Control Language:
• TCL commands can only use with DML commands like INSERT,
DELETE and UPDATE only.
• This command is used to manage the changes made by DML
statements.
• TCL Commands includes:
1. COMMIT
2. SAVEPOINT
3. ROLLBACK
Transaction Control Language
COMMIT COMMAND
• COMMIT command saves all the work done.
• It ends the current transaction and makes permanent changes
during the transaction.
• Syntax:
commit;
Transaction Control Language
SAVEPOINT COMMAND
• SAVEPOINT command is used for saving all the current point
in the processing of a transaction.
• It is used to temporarily save a transaction, so that you can
rollback to that point whenever necessary.
Syntax:
SAVEPOINT <savepoint_name>
Example:
SAVEPOINT no_update;
Transaction Control Language
ROLLBACK COMMAND
• ROLLBACK command restores database to original since the
last COMMIT.
• It is used to restores the database to last committed state.
Syntax:
ROLLBACK TO SAVEPOINT <savepoint_name>;
Example:
ROLLBACK TO SAVEPOINT no_update;
Transaction Control Language
Transaction Control Language
Transaction Control Language
Transaction Control Language
3.3 Operators
1. Relational Operators
2. Arithmetic Operators
3. Logical Operators
4. Set Operators
Page
38
Operators
Arithmetic Operators
Assume:
a=10 and b=20
Operator Description Example
Adds values on either side of
+ (Addition) a + b will give 30
the operator.
Subtracts right hand operand
- (Subtraction) from left hand operand. a - b will give -10
* Multiplies values on either
a * b will give 200
(Multiplication) side of the operator.
Divides left hand operand by
/ (Division) b / a will give 2
right hand operand.
Logical Operators
Comparison Operators
Operator Description Example
Checks if the values of two operands are equal or not, if
= yes then condition becomes true. (a = b) is not true.
Checks if the values of two operands are equal or not, if
!= values are not equal then condition becomes true. (a != b) is true.
Checks if the values of two operands are equal or not, if
<> values are not equal then condition becomes true. (a <> b) is true.
Checks if the value of left operand is greater than the
> value of right operand, if yes then condition becomes (a > b) is not true.
true.
Checks if the value of left operand is less than the value
< of right operand, if yes then condition becomes true. (a < b) is true.
Comparison Operators
Operator Description Example
Checks if the value of left operand is greater
>= than or equal to the value of right operand, if (a >= b) is not true.
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 (a <= b) is true.
condition becomes true.
Checks if the value of left operand is not less
!< than the value of right operand, if yes then (a !< b) is false.
condition becomes true.
Checks if the value of left operand is not greater
!> than the value of right operand, if yes then (a !> b) is true.
condition becomes true.
Set Operators
Set operators:
• They combine the results of two component queries into a
single result.
• Queries containing set operators are called as compound
queries.
• Set operators in SQL are represented with following special
keywords as:
Union
Union all
intersection
minus.
Set Operators
Set Operators
Page
46
Set Operators
Consider data from two tables emp and employee.
Union:
• The Union of two or more sets contains all elements, which
are present in either or both. Union works as or.
• select ename from emp union select ename from
ename
employee;
ename a
ename
union d b
a
c = d
b
f c
f
Set Operators
Consider data from two tables emp and employee.
Union all:
• The Union of 2 or more sets contains all elements, which are
present in both, including duplicates.
• E.g. select ename from emp union all select ename from ename
employee; a
ename f
ename
Union all d b
a
c = d
f
f c
b
f
Set Operators
Consider data from two tables emp and employee.
Intersection:
• The intersection of two sets includes elements which are
present in both.
• E.g. select ename from emp intersect select ename from
employee;
ename
ename ename
INTERSECT d
a
c = f
f
f
b
Set Operators
Consider data from two tables emp and employee.
Minus:
• The minus of two sets includes elements from set1 minus
elements of set2.
• E.g. select ename from emp minus select ename from
employee;
ename
ename Ename
MINUS d
a
c = a
f b
f
b
Range Searching Operator
Between operator: The BETWEEN operator is used to search for
values that are within a set of values, given the minimum value
and the maximum value inclusive of both the limits.
Eg:
select * from emp where salary between 40000 and 50000;
This will results in rows from emp table where salary falls in the
range of 40000 to 50000
Pattern Matching Operator
Like operator :
• The LIKE operator is used to compare a value to similar values
using wildcard operators.
• It uses two wild characters :
‘%’ represents all characters of the pattern
‘_’ represents one single character from pattern.
Pattern Matching Operator
Eg :
Select ename from emp where ename like ‘S%’;
• This will return all employee names starting with ‘S’.
Select ename from emp where ename like ‘_a%’;
• This will return all employee names whose second character is
‘a’.
3.4 Functions
• Numeric Functions
• Date and Time Functions
• String Functions
• Aggregate Functions
String Functions
String Functions
String Functions
String Functions
Functions
Numeric Functions/Arithmetic Function
Functions
Arithmetic Functions
Date and Time Functions
Functions
Functions
SELECT CURRENT_DATE FROM dual ;
SELECT ADD_MONTHS( DATE '2021-02-15', 1 )FROM dual;
Functions
SELECT TO_CHAR(SYSDATE, 'MM-DD-YYYY HH24:MI:SS') FROM dual;
SELECT MONTHS_BETWEEN( DATE '2017-07-01', DATE '2017-01-01' )
MONTH_DIFFFROM DUAL;
Functions
SELECT NEXT_DAY( DATE '2000-01-01', 'SUNDAY' )FROM dual;
The following statement returns the first day of the current month.
SELECT TRUNC( SYSDATE, 'MM' ) result FROM dual;
Aggregate Functions
Aggregate Functions
Aggregate
Aggregate Functions
Functions
select min(marks) from student;
select max(marks) from student;
Aggregate Functions
select avg(marks) from student;
select sum(marks) from student;
Aggregate Functions
select count(marks) from student;
select distinct(marks) from student;
3.2 Clauses and Join
• Where
• Group by
• Order by
• Having
• Types of Join
• Nested queries
Group by and having clause
GROUP BY clause in SQL is used 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 in the relation.
The HAVING clause is used in SQL because the WHERE keyword
could not be used with aggregate functions. The HAVING clause is
used with GROUP BY clause .We often use aggregate functions
with the GROUP BY and HAVING clauses of the SELECT
statement.
ORDER BY clause is used to display a selected set of fields from a
relation in an ordered approach (desc/asc) base on some field.
Example
The GROUP BY Statement in SQL is used to arrange
identical data into groups with the help of some functions.
We can use HAVING clause to place conditions to decide
which group will be the part of final result-set.
The ORDER BY statement in sql is used to sort the fetched
data in either ascending or descending according to one or
more columns.
•By default ORDER BY sorts the data in ascending order.
•We can use the keyword DESC to sort the data in descending
order and the keyword ASC to sort in ascending order.
The ORDER BY statement in sql is used to sort the fetched
data in either ascending or descending according to one or
more columns.
The ORDER BY statement in sql is used to sort the fetched
data in either ascending or descending according to one or
more columns.
Join
Join
A Join operation combines related tuples from different relations, if
and only if a given join condition is satisfied.
Explain types of join with example of each?(W-19)
Table 1 : Emp Table 2 : Dept
Left Right
1. INNER JOIN
• The INNER JOIN displays records that have similar values in
both tables.
• INNER JOIN is also referred to as an EQUIJOIN.
Example :
SELECT Emp.empno,Emp.ename,Emp.deptno,Dept.dno,Dept.dname
FROM Emp
INNER JOIN Dept
ON emp.deptno=dept.dno;
2. LEFT OUTER JOIN
A LEFT JOIN returns all rows from the left table and the matched
rows from the right table.
Example :
SELECT Emp.empno,Emp.ename,Emp.deptno,Dept.dno,Dept.dname
FROM Emp
LEFT OUTER JOIN Dept
ON emp.deptno=dept.dno;
3. RIGHT OUTER JOIN
It returns all the rows from the right table (table2) and the matched
rows from the left table (table1).
Example :
SELECT Emp.empno,Emp.ename,Emp.deptno,Dept.dno,Dept.dname
FROM Emp
RIGHT OUTER JOIN Dept
ON emp.deptno=dept.dno;
4.FULL OUTER JOIN
It returns all rows from both tables being joined, regardless of
whether there is a match between the columns being joined.
Example :
SELECT Emp.empno,Emp.ename,Emp.deptno,Dept.dno,Dept.dname
FROM Emp
FULL OUTER JOIN Dept
ON emp.deptno=dept.dno;
3.5 Views, Sequences, Indexes
Q1. Explain View ?
View –
• It logically represents subsets of data from one or more tables.
• It is virtual table which is derived from one or more table .
EMPLOYEES table
Advantages of
Views
To restrict To make complex
data access queries easy
To provide To present
data different views of
independence the same data
Creating a View
You embed a subquery in the CREATE VIEW statement:
Creating a View: Example
Retrieving Data from a View
Updating a View
Modify the EMPVU80 view by using a CREATE OR REPLACE VIEW clause.
Add an alias for each column name:
CREATE OR REPLACE VIEW empvu80
(id_number, name, sal, department_id)
AS
SELECT employee_id, first_name || ' ' || last_name, salary, department_id
FROM employees WHERE department_id = 80;
Column aliases in the CREATE OR REPLACE VIEW clause are listed in the
same order as the columns in the subquery.
Removing a View
You can remove a view without losing data because a view is
based on underlying tables in the database.
• Syntax:
• Example:
Q1. Explain View and write syntax for view creation?
View –
• It logically represents subsets of data from one or more tables.
• It is virtual table which is derived from one or more table .
Advantages of View –
Security: It restrict access to data
Complexity: it makes complex queries easy
It provides Data Independence
It provides different views of same data.
Syntax –
CREATE VIEW name
AS SELECT column1, column2..... FROM table_name
WHERE [condition];
Example :
CREATE VIEW V1 AS SELECT * FROM student
WHERE marks >80;
Q2. Explain how to update and drop View ?
Updating View :
Syntax
UPDATE view_name
SET column1 = value1
WHERE [condition];
Example :
UPDATE V1
SET Marks=50
where Rollno=5;
Drop View :
Syntax
Drop view view_name;
Example :
Drop view V1;
What Is a Sequence?
Database object that generates numeric values
A sequence:
• Can automatically generate unique numbers
• Is a shareable object
• Can be used to create a primary key value
2 4 6
1 3 5
CREATE SEQUENCE Statement: Syntax
Define a sequence to generate sequential numbers automatically:
Creating a Sequence
Create a sequence named DEPT_DEPTID_SEQ to be used for the
primary key of the DEPARTMENTS table. Do not use the CYCLE
option.
Create Sequence seq1
Start with 1
Increment by 1
Minvalue 1
Maxvalue 20;
NEXTVAL and CURRVAL (attributes)
NEXTVAL returns the next available sequence value.
It returns a unique value every time it is referenced,
even for different users.
CURRVAL obtains the current sequence value.
NEXTVAL must be issued for that sequence before
CURRVAL contains a value.
Using a Sequence
Altering or Modifying a Sequence:
Change the increment value, maximum value, minimum value, cycle
option or cache option:
Example:
Dropping or removing a sequence
To remove a sequence, use the DROP statement:
Concept of Index
• Is a schema object
• Can be used by the database server to speed up the
retrieval
of rows by using a pointer
• Can reduce disk input/output (I/O) by using a rapid path
access method to locate data quickly
• Improves the performance of data retrieval queries
How Are Indexes Created?
• Automatically: A unique index is created automatically when
you define a PRIMARY KEY or UNIQUE constraint in a table
definition.
• Manually: Users can create nonunique indexes on columns to
speed up access to the rows.
• Types of Index: 1. Simple Index
2. Composite Index
3. Unique Index
Creating an Index
• Create an index on one or more columns:
• E.g. Improve the speed of query access to the LAST_NAME
column in the EMPLOYEES table:
CREATE INDEX emp_last_name_idx
ON employees(last_name);
Simple Index
• An index created on single column of a table is called a
Simple Index.
Syntax:
Example: Improve the speed of query access to the
LAST_NAME column in the EMPLOYEES table:
CREATE INDEX emp_last_name_idx
ON employees(last_name);
Composite Index
• An index created on more than one columns of a table is called a
Composite Index.
Syntax:
Example: Improve the
speed of query access to
the Emp_id and CREATE INDEX empid_last_name_idx
LAST_NAME column in ON employees(Emp_id, last_name);
the EMPLOYEES table:
Unique Index
• 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: Improve the speed of query access and restrict duplication of
values on the email_id column in the EMPLOYEES table:
Removing an Index
• To drop an index, you must be the owner of the index or have the
DROP ANY INDEX privilege.
• It does not affect contents of the table
• Remove an index from the data dictionary by using the DROP
INDEX command:
Syntax:
Example: Drop dept index created on Departments_info table:
Nested Query
• Nested query is a query that is placed within another query.
• Output of the inner query is used by the outer query.
• A nested query has two SELECT statements: one for the inner query and
another for the outer query.
Page
110
Thank You
Mrs. Samidha Chavan
Department of Information Technology (NBA Accredited)
Vidyalankar Polytechnic
Vidyalankar College Marg, Wadala(E), Mumbai 400 037
E-mail:
[email protected] 111