Professional Documents
Culture Documents
Bilal DBMS Unit-2 Part
Bilal DBMS Unit-2 Part
Bilal DBMS Unit-2 Part
DB
MANAGEMENT
UNIT-2 M
Presented By
S Mohammad Bilal
SYSTEM Assistant professor
Department I.T
VCE
UNIT-2
01 ✓SQL, SQL Data types 02 ✓DDL, DML, DCL and TCL commands
✓ It is used for storing and managing data in relational database management system.
✓ It enables a user to create, read, update and delete relational databases and tables.
✓ All the RDBMS like MYSQL, Oracle, MA access and SQL Server use SQL as their standard database language.
✓ SQL allows users to Query the database in a number of ways using statements like common English.
SQL- RULES:
✓SQL is not a case sensitive.
✓Generally, keywords are represented in UPPERCASE.
✓ Using the SQL statements, you can perform most of the actions in a database.
✓Statements of SQL are dependent on text lines.
✓ We can use a single SQL statement on one or multiple text line.
SQL Data Types
✓SQL data type is used to define the values that a column can contain.
✓Every column is required to have a name and data type in the database table.
Oracle
Data Types
S
Data Type Description Memory Example
NO
NUMBER(7,2) is a
NUMBER(P, S)/
It contains precision p and scale s. TheA NUMBER valuenumber that has 5 digits
DECIMAL(P,S)/
1 precision p can range from 1 to 38, andrequires from 1 to before the decimal and
NUMERIC(P,S)/
the scale s can range from -84 to 127. 22 bytes. 2 digits after the
DEC(P,S)
decimal.
Data Types
iii. Date And Time Datatypes:
It is used to store a valid date-time format with a fixed length. Its range varies
1 DATE
from January 1, 4712 BC to December 31, 9999 AD.
2 TIMESTAMP It is used to store the valid date in YYYY-MM-DD with time hh:mm:ss format.
SQL Table
✓SQL table is a collection of data which is organized in terms of rows and columns.
✓ In DBMS, the table is known as relation and row as a tuple
✓Let’s see an example of the “EMPLOYEE “table
✓In the above table, “EMPLOYEE” is the table name, “EMP_ID, “EMP_NAME”, “CITY”,” PHONE-NO” are the
column names.
✓The combination of data of multiple columns forms a row
Types SQL Commands
• RENAME
Types SQL Commands
✓SQL commands are categorized into five types:
i. Data Definition Language (DDL) : It is used to creating , deleting and altering a table.
ii. Data Manipulation Language (DML) : It is used to update, store and retrieve data from tables.
iii. Data Query Language(DQL) :It is used to fetch the data from the database.
iv. Data Control Language (DCL) : It is used to control the access of database created using DDL ,DML.
v. Transaction Control Language(TCL) :It is used to control the actions done by other non-auto-committed
Syntax
Create table <table name > (column_name1 datatype(size), Column_name2 datatype(size), ……………..);
DDL Commands
ii. Alter Command:
✓The alter command adds, delete or modifies columns in a table.
✓It also adds and deletes various constraints in a table.
Syntax
alter table <table name> add/modify (column data type(size));
Example
SQL> alter table emp modify(job varchar2(20));
SQL> DESC employee;
DDL Commands
i. Create command:
Example
SQL> create table employee (empno number(4) not null, ename varchar2(10) not null, job varchar2(9) not null,mgr
number(4), hiredate date, sal number(7,2), comm number(7,2), deptno number(2) );
Describe Command :
✓This command is used to describe the structure of table
Syntax
desc <tablename>;
✓If you create the table successfully, you can verify the table by looking at the message by the sql server else you can
use DESC command.
SQL > DESC employee;
DDL Commands
iii. Drop command:
✓The drop table command deletes a table in the data base.
Syntax Example
Drop table table_name; Drop table employee;
Syntax Example
Truncate table table_name; Truncate table employee;
✓Truncate is normally ultra-fast and its ideal for deleting data from a temporary table.
✓Truncate preserves the structure of the table for future use, unlike drop table where the table is deleted
with its full structure.
✓Table or Database deletion using DROP statement cannot be rolled back.
DDL Commands
v. Rename command:
✓This is used to rename an object existing in the database.
✓Syntax may vary in different databases.
Syntax Example
Rename old_tablename to new_tablename; SQL> Rename test1 to test2;
Renaming a column:
✓it is introduced by oracle 9i
Syntax
alter table table_name rename column old_columnname to new_columnname;
Example
SQL> alter table test2 rename column empno to empid;
DML Commands
✓DML stands for Data Manipulation Language.
✓Data Manipulation Commands are used to manipulate data to the database.
✓Some of the data manipulation commands are:
i. Insert
ii. Update
iii. Delete
DML Commands
✓DML stands for Data Manipulation Language.
✓Data Manipulation Commands are used to manipulate data to the database.
✓Some of the data manipulation commands are:
i. Insert
ii. Update
iii. Delete
DML Commands
1. Insert command:
✓SQL insert statement is a sql query. It is used to insert a single multiple records in a table.
Syntax
Insert into table_name values (value 1, value 2, value 3);
Example
Insert Into Emp Values(501, ”RAM”, ”Manager”, 1990-06-01, 92000, 37, ”Hyderabad”);
DML Commands
✓Inserting more than one record using a single insert command
Syntax
SQL> Insert into Table_name Values(&col_name1, &col_name2……………………….. &col_name_n);
Example
SQL> insert into Emp Values(&eid, '&ename’ , ’&designation’ , ’&DOB’ , &esal , &eage , ’&eaddress’ );
Enter value for eid : 23
Enter value for ename : aaa
Enter value for designation : Manager
Enter value for DOB : 12-dec-89
Enter value for esal : 50000
Enter value for eage : 38
Enter value for eaddress :Hyderabad
old 1: insert into Emp values(&eid,'&ename’, &designation’ , ’&DOB’ , &esal , &eage , ’&eaddress’
new 1: insert into Emp values(23,'aaa','Manager','12-dec-89',50000,38,'Hyderabad')
1 row created.
DML Commands
✓Skipping the fields while inserting
Syntax
SQL> insert into <tablename>(coln names to which data to be inserted) values (list of values);
Syntax
update <tablename> set field = values where condition;
Example
SQL>update Emp set Designation=‘Sr Manager' where eid=03;
1 row updated.
DML Commands
ii. UPDATE COMMAND: Syntax
UPDATE TABLE_NAME
SET COLUMN_VALUE
= CASE COLUMN_NAME
WHEN 'COLUMN_NAME1' THEN COLUMN_VALUE1
WHEN 'COLUMN_NAME2' THEN COLUMN_VALUE2
ELSE COLUMN_VALUE
END
WHERE BAND_NAME IN('COLUMN_NAME1', 'COLUMN_NAME2');
Example
UPDATE BANDS
SET PERFORMING_COST
= CASE BAND_NAME
WHEN 'METALLICA' THEN 90000
WHEN 'BTS' THEN 200000
ELSE PERFORMING_COST
END
WHERE BAND_NAME IN('METALLICA', 'BTS');
DML Commands
iii. DELETE COMMAND:
✓ The command is used to delete the rows in a table.
Syntax
Delete from <table_name> where conditions;
Example
SQL> delete from emp where empno=7369;
DQL Commands
SELECT COMMAND:
✓ It is used to retrieve all rows from a table
Syntax Example
SQL>Select * from table name; SQL>Select * from Emp;
Syntax Example
SQL>Select column_name1, …..,column_namen from table name; SQL> select ename, sal,eage from Emp;
DQL Commands
SELECT COMMAND with DISTINCT KEYWORD :
✓ It Elimination of duplicates from the select clause
✓ It prevents retrieving the duplicated values.
Syntax
SQL>Select DISTINCT col1, col2 from table name;
Example
SQL>select distinct etype from Emp;
DQL Commands
SELECT COMMAND with ‘where’ clause :
✓ To select specific rows from a table we include ‘where’ clause in the select command.
Syntax
Select column_name1, …..,column_name from table name where condition;
Example
SQL> select ename, designation from Emp where Designation= 'manager';
SQL operators
✓ The operators are symbols (and keywords) that are used to perform operations with values.
✓ These operators are used with SQL clauses such as: SELECT, WHERE, ON etc.
✓ The operators in SQL can be categorized as:
i. Arithmetic operators
ii. Comparison operators
iii. Logical operators
i. SQL Arithmetic Operators
Example: select emp id, emp_name, salary, salary+100 as “salary +100” from emp;
Subtraction (-):
✓ It is used to perform subtraction on the data items.
Example: select emp id, emp_name, salary, salary-100 as “salary -100” from emp;
i. SQL Arithmetic Operators
Multiplication (*):
It is used to perform multiplication of data items.
Division (/):
The division function is used to integer division
2. Equal to Operator:
SQL> SELECT * FROM CUSTOMERS WHERE SALARY = 2000;
ii. Relational
Operators
Syntax
SELECT * FROM table_Name WHERE condition1 AND cond-2 ....... AND cond-N;
Example
SQL> SELECT * FROM CUSTOMERS WHERE AGE >= 25 AND SALARY >= 6500;
iii.Logical Operators
ii . OR Operator:
✓ OR operator is useful for comparing data with more than one condition, and it will return records when either of
the conditions is TRUE.
✓ It is also known as the conjunctive operator and is used with the WHERE clause.
Syntax
SELECT * FROM table_Name WHERE condition1 OR condition2 ……..OR cond-n);
Example
SQL> SELECT * FROM CUSTOMERS WHERE AGE >= 25 OR SALARY >= 6500;
iii.Logical Operators
iii. NOT Operator:
✓ The NOT operator in SQL shows the record from the table if the condition evaluates to false. It is always used with
the WHERE clause.
Syntax
SELECT * FROM table_Name WHERE NOT condition;
Example
SQL> SELECT * FROM CUSTOMERS WHERE NOT SALARY>=6500;
iii.Logical Operators
Syntax
SELECT * FROM table_Name WHERE column_name LIKE pattern;
Example
SQL> SELECT * FROM CUSTOMERS WHERE NAME LIKE 'Ko%';
iii.Logical Operators
v. IN Operator:
✓ The IN operator in SQL allows database users to specify two or more values
Syntax minimizes the requirement of multiple OR conditions.
✓ This
SELECT * FROM table_Name WHERE column_name INoperator returns those rows whose values match with any value of the
(list_of_values);
Example
SQL> SELECT * FROM CUSTOMERS WHERE AGE IN ( 25, 27 );
iii.Logical Operators
vi. BETWEEN:
✓ The BETWEEN operator in SQL shows the record within the range mentioned in the SQL query.
✓ This operator operates on the numbers, characters, and date/time operands.
Syntax
SELECT * FROM table_Name WHERE column_name BETWEEN value1 and value2;
Example
SQL> SELECT * FROM CUSTOMERS WHERE AGE BETWEEN 25 AND 27;
iii.Logical Operators
vii. ALL Operator:
✓ In SQL, ALL operator is a logical operator that compares a single value with a single-column set of values
returned by a subquery.
Syntax
WHERE column_name comparison_operator ALL (subquery)
Example
SQL> SELECT * FROM CUSTOMERS WHERE AGE > ALL
(SELECT AGE FROM CUSTOMERS WHERE SALARY > 6500);
iii.Logical Operators
viii. ANY:
✓ In SQL, ANY operator is a logical operator that compares a value with a set of values returned by a subquery.
✓ The ANY operator must be preceded by a comparison operator >, >=, <, <=, =, <> and followed by a subquery.
Syntax
SELECT col-1, col-2 ...., col-N FROM table_Name WHERE column_name comparison_operator ANY (subquery);
Example
SQL> SELECT * FROM CUSTOMERS WHERE AGE > ANY (SELECT AGE FROM CUSTOMERS WHERE SALARY > 6500);
iii.Logical Operators
ix. EXISTS Operator:
✓ In SQL, the EXISTS operator is useful to show the results if the subquery returns data.
✓ Generally, we will use EXISTS operator in the WHERE clause to check whether the subquery has return values or
not.
Syntax
SELECT * FROM tablename WHERE EXISTS(Subquery)
Example
SQL> SELECT AGE FROM CUSTOMERS WHERE EXISTS (SELECT AGE FROM CUSTOMERS WHERE SALARY > 6500);
Aggregate Functions
✓ Aggregate Functions take a collection of values as input and returns a single value.
i. Count ()
ii. Sum ()
iii. Avg ()
iv. Max ()
v. Min ()
Aggregate Functions
i.Count ():
✓ This function returns number of rows returned by a query.
Syntax
Select count(column_name) From table_name Where condition;
Example
ii.Sum (): SQL> Select count (manager_id) from employees;
It will add/ sum all the column values in the query.
Syntax
Select sum(column_name) From table_name Where condition;
Example
SQL> Select sum(salary) from employees;
Aggregate Functions
iii.Avg ():
✓ Avg function used to calculate average values of the set of rows.
Syntax
Select avg(column_name) From table_name Where condition;
Example
SQL> Select avg(salary) from employees;
iv.Max ():
✓ This function is used to find maximum value from the set of values.
Syntax
Select max(column_name) From table_name Where condition;
Example
SQL> Select max(salary) from employees;
Aggregate Functions
v.Min ():
This function is used to find minimum value from the set of values.
Syntax
Select min(column_name) From table_name Where condition;
Example
SQL> Select min(salary) from employees;
SQL built in functions
✓ Various SQL built-in functions are:
i. Numeric functions
ii. string functions
iii. Date functions
i.SQL Numeric Functions
1. ABS ():
✓ It returns the absolute value of a number.
EXAMPLE: select ABS (-243.5) from dual; OUTPUT: 243.5
2. COS ():
✓ It returns the cosine of a number.
EXAMPLE: select COS (2) from dual; OUTPUT: -0.41614683654714241
3. SIN ():
✓ It returns the sine of a number.
EXAMPLE: select SIN (2) from dual; OUTPUT: 0.90929742682568171
4. CEIL ():
✓ It returns the smallest integer value that is a greater than or equal to a number.
EXAMPLE: select CEIL (25.77) from dual; OUTPUT: 26
i.SQL Numeric Functions
5.FLOOR ():
✓ It returns the largest integer value that is a less than or equal to a number.
EXAMPLE: select FLOOR (25.75) from dual; OUTPUT: 25
6. TRUNCATE ():
✓ This does not work for SQL server. It returns the truncated to 2 places right of the decimal point.
EXAMPLE: select TRUNCATE (7.53635, 2) from dual; OUTPUT: 7.53
7. MOD ():
✓ It returns the remainder when two numbers are divided.
EXAMPLE: select MOD (55,2) from dual; OUTPUT: 1
8. ROUND ():
✓ This function rounds the given value to given number of digits of precision.
EXAMPLE: select ROUND (14.5262,2) from dual; OUTPUT: 14.53
i.SQL Numeric Functions
9. POWER ():
✓ This function gives the value of m raised to the power of n.
EXAMPLE: select POWER (4,9) from dual; OUTPUT: 262144
1.CONCAT ():
✓ This function is used to add two words (or) strings.
EXAMPLE: select concat(‘DB’ ,’MS’) From dual; OUTPUT: DBMS
2.LOWER ():
✓ This function is used to convert the given string into lowercase.
EXAMPLE: select lower (‘DATABASE’) from dual; OUTPUT: database
3.UPPER ():
✓ This function is used to convert the lowercase string into uppercase.
EXAMPLE: select upper (‘database’) from dual; OUTPUT: DATABASE
ii.SQL String Functions
4.LPAD ():
✓ This function is used to make the given string of the given size by adding the given symbol.
EXAMPLE: select lpad (‘system’, 8, ‘@’) from dual; OUTPUT: @@system
5.RPAD ():
✓ This function is used to make the given string as long as the given size by adding the given symbol
on the right.
EXAMPLE : select rpad (‘system’,8,’@’) from dual; OUTPUT: system@@
6.LTRIM ():
✓ This function is used to cut the given substring from the original string.
EXAMPLE : select ltrim (‘database’, ‘data ‘) from dual OUTPUT: base
ii.SQL String Functions
7.RTRIM ():
✓ This function is used to cut the given substring from the original string.
EXAMPLE: select rtrim (‘database’, ‘base’) from dual; OUTPUT: data
8. INITCAP ():
✓ This function returns the string with first letter of each word starts with uppercase.
EXAMPLE: Select INITCAP (‘data base’) from dual; OUTPUT: Data Base
9. LENGTH ():
✓ This function returns the length of the given string.
EXAMPLE: select LENGTH (‘SQL’) from dual; OUTPUT: 3
10.SUBSTR ():
✓ This function returns a portion of a string beginning at the character position.
EXAMPLE: select SUBSTR (‘MY WORLD IS AMAZING’,12,3) from dual; OUTPUT: AM
ii.SQL Date Functions
In oracle by default data format is DD-MM-YY
1.sysdate/current_date:
✓ It returns current date of the system in oracle data format.
✓ Ex: Select sysdate from dual; Output: 05-DEC-2021
✓ Ex: Select current_date from dual; Output: 05-DEC-2021
2. next_day( ):
✓ It retuns next occurance day from the specified date based on 2nd peramter.
✓ syntax: next_day(date,'day')
✓ EX: Select next_day(SYSDATE,‟MONDAY‟) from dual; Output: 07-DEC-21
3.last_day( ):
✓ It retuns last date of the specified month. syntax: last_day(date)
✓ EX: Select last_day (sysdate) from dual; Output: 31-DEC-21
ii.SQL Date Functions
4.months_between( ):
✓ It is used to find no of months between two given dates.
✓ This function always retuns number data type,i.e., it retuns no of months between two specified date
✓ syntax: months_between(data1,data2)
✓ EX: Select months_between(‟16-APRIL-2021‟,‟16-AUGUST-2021) from dual; Output: 4
5.add_months( ):
✓ It is used to add or replace no of months from the specified data.
✓ Syntax: add_months(date,number) {+ve or -ve}
✓ EX: Select add_months(sysdate,3) from dual; Output: 05-MAR-22
ii.SQL Date Functions
ii. to_char():
✓ This function converts DATE or an INTERVAL value to a character string in a specified format.
✓ EX: Select to_char (sysdate,‟DD MM YYYY‟) from dual; Output: 05 12 2021.
✓ Ex: select to_char(sysdate,'DD/MM/YY') from dual; Output:22/12/21
✓ Ex: select to_char(sysdate,'day') from dual; Output: wednesday
✓ Ex: select to_char(sysdate,'dd') from dual; Output:22
✓ Ex: select to_char(sysdate,'ddth') from dual; Output:22nd
✓ Ex: select to_char(sysdate,'ddspth') from dual; Output: twenty-second
✓ Ex: select to_char(sysdate,'hh:mi:ss') from dual; Output:08:01:45
✓ Ex: select to_char(sysdate,'hh24:mi:ss') from dual; Output:20:02:36
SQL SET Operations
✓ The SQL Set operation is used to combine the two or more SQL SELECT statements.
Example
ID NAME
1 Ram
SELECT * FROM First 2 Dilip
UNION 3 Sohel
SELECT * FROM Second; 4 Mahi
5 Hemanth
SQL SET Operations
2. Union All:
✓ Union All operation is equal to the Union operation. It returns the set without removing duplication and sorting
the data. First Second
ID NAME ID NAME
Syntax
1 Ram 3 Sohel
SELECT column_name FROM table1 2 Dilip 4 Mahi
UNION ALL 3 Sohel 5 Hemanth
SELECT column_name FROM table2;
ID NAME
Example 1 Ram
SELECT * FROM First 2 Dilip
UNION ALL 3 Sohel
3 Sohel
SELECT * FROM Second;
4 Mahi
5 Hemanth
SQL SET Operations
3. Intersect:
✓ It is used to combine two SELECT statements. The Intersect operation returns the common rows from both
the SELECT statements.
First Second
Syntax
ID NAME ID NAME
SELECT column_name FROM table1
1 Ram 3 Sohel
INTERSECT 2 Dilip 4 Mahi
SELECT column_name FROM table2; 3 Sohel 5 Hemanth
Example
SELECT * FROM First
INTERSECT ID NAME
SELECT * FROM Second;
3 Sohel
SQL SET Operations
the rows which are present in the first table but absent in the second table.
and data arranged in ascending order by default. First Second
Syntax
ID NAME ID NAME
SELECT column_name FROM table1
1 Ram 3 Sohel
MINUS
2 Dilip 4 Mahi
SELECT column_name FROM table2;
3 Sohel 5 Hemanth
Example
SELECT * FROM First
ID NAME
MINUS
1 Ram
SELECT * FROM Second;
2 Dilip
SQL GROUP BY clause
✓ The GROUP BY clause is used in SQL queries to organize data that have the same attribute
values.
✓ Usually, we use it with the SELECT statement..
✓ It uses aggregate functions like SUM, AVG, MIN, MAX, and COUNT to produce summary reports
from the database.
✓ It returns only one result per group of data.
✓ GROUP BY Clause always follows the WHERE Clause.
✓ GROUP BY Clause always precedes the ORDER BY Clause
✓ It uses the split-apply-combine strategy for data analysis.
i. In the split phase, It divides the groups with its values.
ii. In the apply phase, It applies the aggregate function and generates a single value.
iii. In the combine phase, It combines the groups with single values into a single value.
SQL GROUP BY clause
SQL GROUP BY clause
Syntax
SELECT column_name,
function(column_name)
FROM table_name
GROUP BY column_name;
Example
SELECT country, COUNT(*) AS
number
FROM Customers
GROUP BY country;
SQL GROUP BY clause
Let's try to find the total amount for each customer who has placed an order.
Example
SELECT customer_id,
SUM(amount) AS total
FROM Orders
GROUP BY customer_id;
SQL GROUP BY clause
Example
SELECT DeptID,avg(Salary)
FROM Employee
GROUP BY DeptID;
SQL ORDER BY clause
✓ The ORDER BY clause in SQL will help us to sort the records based on the specific column of a table.
✓ This means that all the values stored in the column on which we are applying ORDER BY clause will
be sorted, and the corresponding column values will be displayed in the sequence .
✓ Using the ORDER BY clause, we can sort the records in ascending or descending order as per our
requirement.
✓ The records will be sorted in ascending order whenever the ASC keyword is used with ORDER by
clause. DESC keyword will sort the records in descending order.
✓ If no keyword is specified after the column based on which we have to sort the records, in that case,
the sorting will be done by default in the ascending order.
SQL ORDER BY clause
Syntax
Example
SELECT
SELECT *
ColumnName1,...,ColumnNameN
FROM Customers
FROM TableName
ORDER BY first_name;
ORDER BY ColumnName ASC;
SQL ORDER BY clause
Example
SELECT *
FROM Customers
ORDER BY age ASC;
SQL Having clause
✓ HAVING clause is used to apply a filter on the result of GROUP BY based on the specified condition.
✓ It is used if we need to filter the result set based on aggregate functions such as MIN() and MAX(),
SUM() and AVG() and COUNT().
✓ It was included in SQL as the WHERE keyword failed when we use it with aggregate expressions.
✓ If you wish to filter a group, the HAVING clause comes into action.
Note:
✓ Having clause is generally used after GROUP BY.
✓ In the query, ORDER BY is to be placed after the HAVING clause, if any.
✓ Having clause is only used with the SELECT clause.
✓ Having clause is used to filter data according to the conditions provided.
SQL Having clause
Syntax
SELECT column1,
function_name(column2)
FROM table_name
GROUP BY column1, column2
HAVING condition ;
Example
SELECT NAME, SUM(SALARY) FROM
Employee
GROUP BY NAME
HAVING SUM(SALARY)>=50000;
It is always executed with the GROUP BY clause. It can be executed without the GROUP BY clause.
It can include SQL aggregate functions in a query. We cannot use the SQL aggregate function with WHERE
clause.
It can only use SELECT statement with HAVING clause we can easily use WHERE clause with UPDATE, DELETE,
for filtering the records. and SELECT statements.
It is used after the GROUP BY clause. It is always used before the GROUP BY clause.
We can implements this SQL clause in column We can implements this SQL clause in row operations.
operations.
It is a post-filter. It is a pre-filter.
It is used to filter groups. It is used to filter the single record of the table.
SQL Transaction Control Language
Commit Command :
✓ The Commit command is the transactional command used to save changes made by a transaction to
the database.
✓ The COMMIT command will save all changes to the database since the last Commit or Rollback
command.
✓ Frequent commits in the case of transaction involving large amount of data is recommended. But too
many commits can affect performance.
Syntax:
commit;
Input: Output:
SQL>commit; Commit complete;
SQL Transaction Control Language
Rollback Command:
✓ Rollback command is the transactional control command to undo the transactions that have not already
been committed to the database.
✓ The Rollback command can be issued to undo the changes since the last Commit or Rollback.
Syntax-1 : Syntax-2 :
Rollback; Rollback to Savepoint text_identifier;
Input: Output:
SQL>rollback; Rollback complete;
SQL Transaction Control Language
Savepoint Command:
This command is used to save the data at a particular point temporarily, so that whenever needed can be rollback to that
particular point.
Syntax:
Savepoint text _identifier;
Input:
update employees set salary = 95000 where last_name = 'smith';
savepoint justsmith;
update employees set salary = 1000000;
savepoint everyone;
select sum(salary) from employees;
rollback to savepoint justsmith;
commit;
SQL Joins
✓ A SQL JOIN is an Operation , used to retrieve data from multiple tables.
✓ SQL Join clause is used to combine records from two or more tables in a database.
✓ Joins are 2 types:
i. ANSI format join
ii. Non-Ansi Format join
✓ The LEFT OUTER JOIN retrieves all the records from the left
id name oid amount id
1 John 1 200 10
table and matching rows from the right table. 2 Robert 2 500 3
✓ It will return NULL when no matching record is found in the 3 David 3 300 6
right side table. it is also known as LEFT JOIN. 4 John 4 800 5
5 Betty 5 150 8
Syntax
Example OUTPUT
SELECT column_lists id name amount
SELECT C.id, C.name, O.amount 1 John
FROM table1 2 Robert
FROM Customers as C 3 David 500
LEFT JOIN table2 4 John
LEFT JOIN Orders as O
ON table1.column = 5 Betty 800
ON C.id = O.id;
table2.column;
SQL Joins
iii.RIGHT OUTER JOIN: Orders
Customer
✓ The RIGHT OUTER JOIN retrieves all the records from the id name oid amount id
right-hand table and matched rows from the left-hand 1 John 1 200 10
table.
2 Robert 2 500 3
3 David 3 300 6
✓ It will return NULL when no matching record is found in the 4 John 4 800 5
left-hand table. it is also known as RIGHT JOIN. 5 Betty 5 150 8
Example
Syntax
SELECT C.id, C.name,
SELECT column_lists
O.amount
FROM table1
FROM Customers as C
FULL JOIN table2
FULL JOIN Orders as O
ON table1.column = table2.column;
ON C.id = O.id;
SQL Joins
v. CROSS JOIN:
Customer Orders
✓ The CARTESIAN JOIN or CROSS JOIN returns the cartesian id name oid amount id
product of the sets of records from the two or more joined 1 John 1 200 10
tables. 2 Robert 2 500 3
3 David 3 300 6
✓ Thus, it equates to an inner join where the join-condition
4 John 4 800 5
always evaluates to True or where the join condition is 5 Betty 5 150 8
absent from the statement.
Syntax Example
SELECT column_lists SELECT C.id, C.name, O.amount
FROM table1 FROM Customers as C
CROSS JOIN table2 ; CROSS JOIN Orders as O;
SQL Joins
i. Equi join:
✓ Equi Joins in SQL joins multiple tables on the basis of an equality condition.
Customer Orders
id name oid amount id
Syntax 1 John
1 200 10
SELECT * FROM TableName1, TableName2 2 Robert 2 500 3
3 David 3 300 6
WHERE TableName1.ColumnName = TableName2.ColumnName;
4 John 4 800 5
5 Betty 5 150 8
Example
SELECT C.id, C.name, O.amount
FROM Customers as C , Orders as O
where C.id = O.id;
SQL Joins
ii. Non-Equi join:
✓ It joins the table on the basis of conditions other than the equality conditions, such as <>, >, <, etc.
Syntax
SELECT * FROM TableName1, TableName2
WHERE TableName1.columnName [> | < | >= | <= | BETWEEN... ] table_name2.column;
Customer Orders
Example id name oid amount id
SELECT C.id, C.name, O.amount 1 John
1 200 10
2 Robert
FROM Customers as C, Orders as O 2 500 3
3 David 3 300 6
Where C.id >O.id; 4 John 4 800 5
5 Betty 5 150 8
SQL Joins
iii. Self join:
✓ The SELF JOIN is used to join a table to itself. This means that each row in a table is joined to itself and every
other row in that table.
✓ However, referencing the same table more than once within a single query will result in an error. To avoid this, SQL
SELF JOIN aliases are used.
Syntax
SELECT a.column_name, b.column_name...
FROM table1 a, table1 b
WHERE a.common_field = b.common_field;
SQL Joins
Emp Emp
ENO ENAME JOB MGRNO ENO ENAME JOB MGRNO
1 Raj Clerk 4 1 Raj Clerk 4
2 Venkat Salesman 3 2 Venkat Salesman 3
3 Srinu Accountant 4 3 Srinu Accountant 4
4 Dilip Manager 4 Dilip Manager
5 Hemanth Asst manager 4 5 Hemanth Asst manager 4
Example
OUTPUT
SELECT e.ename as Empname, m.ename as Mgrname Empname Mgrname
Raj Dilip
From emp e,emp m
Venkat Srinu
Where e.mgrno=m.eno; Srinu Dilip
Hemanth Dilip
SQL Views
✓ A view in SQL is a logical subset of data from one or more tables. It is used to restrict data access.
✓ Data abstraction is usually required after a table is created and populated with data.
✓ Some tables might require restricted access to prevent all users from accessing all columns of a table, for data
security reasons.
✓ Such type of issue can be solved by creating several tables with appropriate columns and assigning specific
users to each such table, as required. That process provides good data security but gives redundant data in the
database.
✓ To reduce redundant data to the minimum possible, Oracle provides Virtual tables which are Views.
View Definition :
✓ A View is a virtual table based on the result returned by a SELECT query.
✓ Basic purpose of a view is restricting access to specific column/rows from a table thus allowing different
users to see only certain rows or columns of a table.
SQL Views
Composition Of View:-
✓ A view is composed of rows and columns, very similar to table.
✓ The fields in a view are fields from one or more tables in the database.
✓ WHERE clauses and JOIN statements can be applied to a view in the same manner as they are applied to a
table.
View storage:-
✓ Oracle does not store the view data. It recreates the data, using the view’s SELECT statement, every time a
user queries a view.
✓ A view is stored only as a definition in Oracle’s system catalog.
✓ When a reference is made to a view, its definition is scanned, the base table is opened and the view is created
on top of the base table.
✓ This reduces redundant data on the HDD to a very large extent.
SQL Views
Advantages Of View:-
i. Security: Each user can be given permission to access only a set of views that contain specific data.
ii. Query simplicity: A view can drawn from several different tables and present it as a single table turning
multiple table queries into single table queries against the view.
iii. Data Integrity: If data is accessed and entered through a view, the DBMS can automatically check the data
to ensure that it meets specified integrity constraints.
Types of Views :-
✓ Simple Views
✓ Complex Views
SQL Views
Simple Views:
✓ A view based on single table is called simple view.
✓ Views can also be used for manipulating the data that is available in the base tables[i.e. the user can perform
the Insert, Update and Delete operations through view].
✓ Views on which data manipulation can be done are called Updateable Views.
✓ If an Insert, Update or Delete SQL statement is fired on a view, modifications to data in the view are passed to
the underlying base table.
✓ For a view to be updatable, it should meet the following criteria:
✓ Views defined from Single table.
✓ If the user wants to INSERT records with the help of a view, then the PRIMARY KEY column(s) and all the
NOT NULL columns must be included in the view.
SQL Views
Syntax
CREATE VIEW <View Name>
Example
AS
SQL>CREATE VIEW emp_v
SELECT<ColumnName1>,<ColumnName2>..
AS
FROM <TableName>
SELECT empno,ename,sal FROM emp ;
[WHERE <COND>]
[WITH CHECK OPTION]
SQL Views
Inserting record through View:
SQL>INSERT INTO emp_v VALUES(1,’A’,5000,200) ;
❖ privileges: Privileges here refers to the INSERT,DELETE,SELECT,UPDATE, EXECUTE, ALTER, ALL, reference
privilege(reference privilege permits a user/role to declare foreign keys while creating relations) and all
options provided by SQL.
❖ user/roles: Roles are the users to whom the privileges are granted or revoked.
Data Control Language(DCL)
//Gives access to SELECT and INSERT in the database to Ravi
Example
//Gives all privilege access to Ram
GRANT SELECT, INSERT
ON Employee_details
Example
TO Ravi;
GRANT ALL PRIVILEGES
ON Customer_Details
//Gives all privilege access to anybody working with the database TO Ram;
Example
GRANT ALL
ON product_stock
TO PUBLIC;
Data Control Language(DCL)
//Retains access from Ravi to SELECT and INSERT
//Retains all access from Ram
Example
REVOKE SELECT, INSERT
ON Employee_details
FROM Ravi;
Example
REVOKE ALL PRIVILEGES
ON Customer_Details
// Retains access from anybody using the database
FROM Ram;
Example
REVOKE ALL
ON product_stock
FROM PUBLIC;
‘U’ T
K H
N A