Bilal DBMS Unit-2 Part

You might also like

Download as pdf or txt
Download as pdf or txt
You are on page 1of 104

DATA BASE

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

✓Syntax of a basic SQL query, ✓Querying relational data,


03 04
✓Integrity constraints over relations ✓SQL operators and SET operations

✓GROUP BY, ORDER BY and HAVING ✓Aggregate operators


05 06
Clause ✓Joins, nested queries, null values,

✓ Views, PL/SQL basics for writing ✓Connecting to oracle database


07 08
triggers, , cursors, stored procedures using Python
SQL
✓ SQL stands for Structure Query Language.

✓ It is standard language for relational database system.

✓ 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

String Numeric Date and Time Others


Data Types
i . String Datatype:

S NO Data Type Description

It is used to store character data within the predefined length. It can be


1 CHAR(size)
stored up to 2000 byte’s. Space padded.
2 VARCHAR2(size) It is used to store variable length string data. It can be stored up to 4000 byte.

It is the same as VARCHAR2(size). The main difference is that VARCHAR is


3 VARCHAR(size)
ANSI Standard and VARCHAR2 is Oracle standard.
It is used to store Variable-length binary strings, Maximum size of 2000
4 RAW
bytes.
ii . Numeric Datatype: 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:

S NO Data Type Description

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

commands such as INSERT, DELETE and UPDATE.


DDL Commands
DDL Commands
Rules to create the table:
✓Oracle reserved words cannot be used.
✓Underscore, numerals, letters are allowed but not blank space.
✓Maximum length for the table name is 30 characters.
✓Two different tables should not have same name.
✓We should specify a unique column name.
✓We should specify proper data type along with width.
✓We can include “not null” condition when needed. By default it is ‘null’.
DDL Commands
i. Create command:
✓Create command is used to create a table in the database.
✓To define the table, you should define the name of the table and also define its column and its data type.
✓An Oracle NOT NULL constraint specifies that a column cannot contain NULL values.

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

✓The following SQL adds an “EMAIL” column to the “EMPLOYEE “table

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;

✓In the above example SQL deletes the table “EMPLOYEE”


✓Dropping a table results in loss of all information stored in the table.
DDL Commands
iv. TRUNCATE command:
✓This is used to remove all records from a table, including all spaces allocated for the records are
removed.

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

✓Let's take an example

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

✓Other way is to give null while passing the values


DML Commands
ii. UPDATE COMMAND:
✓ To modify column or group of columns

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;

✓To retrieve specific columns from a table

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.

✓ It can appear only after the ‘from’ clause.

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

✓SQL> select 10+ 20 from dual;


✓SQL> select 10 * 20 from dual;
✓SQL> select 10 / 5 from dual;
✓SQL> select 12 -5 from dual;
i. SQL Arithmetic Operators
Addition (+):
✓ It is used to perform addition operation on data items.

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.

Select emp_id, emp_name, salary, salary*100 as “salary*100” from emp;

Division (/):
The division function is used to integer division

Select emp_id, emp_name, salary, salary/100 as “salary*100” from emp;


ii. Relational Operators
✓ We can compare two values using comparison operators in SQL. These operators return either 1
(means true) or 0 (means false).
ii. Relational Operators
✓ Consider the CUSTOMERS table having the following records.
✓ SQL> SELECT * FROM CUSTOMERS;
ii. Relational
Operators

1. Greater Than Operator:


SQL> SELECT * FROM CUSTOMERS WHERE SALARY > 5000;

2. Equal to Operator:
SQL> SELECT * FROM CUSTOMERS WHERE SALARY = 2000;
ii. Relational
Operators

3. Not Equal to Operator:

SQL> SELECT * FROM CUSTOMERS WHERE SALARY <> 2000;

4. Greater Than or Equal to Operator:

SQL> SELECT * FROM CUSTOMERS WHERE SALARY >= 6500;


iii.Logical Operators

Operator Description SQL> SELECT * FROM CUSTOMERS;


The AND operator in SQL is used to compare data with more than one
AND condition. If all the conditions return TRUE, then only it will display records.
The OR operator in SQL compares data with more than one condition. If
OR either of the condition is TRUE, it will return data.
The ALL operator in SQL returns true when the value matches all values in a
ALL single column. It’s like AND operator; it will compare the value against all
values in a column.
The Any operator in SQL returns true when the value matches any value in a
ANY single column set of values. It’s like an OR operator, and it will compare the
value against any value in the column.
The LIKE operator in SQL searches for a character string with the specified
LIKE
pattern using wildcards in a column.
The IN operator in SQL is used to search for a specified value that matches
IN
any value in the set of multiple values.
BETWEEN The BETWEEN operator in SQL is used to get values within a range.
The EXISTS operator in SQL is used to show the result if the subquery returns
EXISTS
data.
The NOT operator in SQL is a negate operator, which means it will show data
NOT
for the opposite of conditions that we mentioned in the SQL statement.
iii.Logical Operators
i. AND Operator:
✓ In SQL, AND operator is used to compare data with more than one condition, and it will return records only when
all the defined conditions are TRUE.
✓ It is also known as the conjunctive operator and is used with the WHERE clause.

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

iv. LIKE Operator:


✓ The LIKE operator in SQL shows those records from the table which match with the given pattern specified in the
sub-query.
✓ This operator is used in the WHERE clause with the following three statements:
✓ SELECT statement
✓ UPDATE statement
✓ DELETE statement

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

10. SQRT ():


✓ This function gives the square root of the given value n.
EXAMPLE: Select SQRT (576) from dual; OUTPUT: 24

11. LEAST ():


✓ This function returns least integer from given set of integers.
EXAMPLE: select LEAST (1,9,2,4,6,8,22) from dual; OUTPUT: 1

12. GREATEST ():


✓ This function returns greatest integer from given set of integers.
EXAMPLE: select GREATEST (1,9,2,4,6,8,22) from dual; OUTPUT: 22
ii.SQL String Functions

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

Date Conversion Function:


1.to_date():
✓ This function converts date which is in the character string to a date value.
✓ It is used to convert date string into oracle data type[oracle data format]
✓ EX: Select to_date (‟01 jan 2017‟,‟DD MM YYYY‟) from dual; Output: 01-JAN-17.
✓ Ex: select to_date('20/june/04') from dual; Output:20-JUN-04
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.

✓ Types of Set Operation


i. Union
ii. Union All
iii. Intersect
iv. Minus
SQL SET Operations
1. Union:
✓ The SQL Union operation is used to combine the result of two or more SQL SELECT queries.
✓ In the union operation, all the number of datatype and columns must be same in both the tables on which
UNION operation is being applied.
✓ The union operation eliminates the duplicate rows from its resultset.
First Second

Syntax ID NAME ID NAME


SELECT column_name FROM table1 1 Ram 3 Sohel
UNION 2 Dilip 4 Mahi

SELECT column_name FROM table2;


3 Sohel 5 Hemanth

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 ;

Write the SQL command to counts the number of rows by grouping


them by country and returns the result if their count is greater than 1.
Example
SELECT COUNT(customer_id), country
FROM Customers
GROUP BY country
HAVING COUNT(customer_id) > 1;
SQL Having clause

Example
SELECT NAME, SUM(SALARY) FROM
Employee
GROUP BY NAME
HAVING SUM(SALARY)>=50000;

Write the SQL command to find whose sum of salary is more


than or equal to 50000.
SQL Having Vs Where clause
HAVING WHERE
It is used into fetch the data/values from the groups It is used to fetch the data/values from the tables according to
according to the given condition. the given condition.

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

ANSI Format Join


✓ It uses ON keyword to join the tables. Non-ANSI Format Join
✓ These are 3 types:
✓ It uses WHERE keyword to join the
1. Inner Join
tables.
2. Outer Join ✓ These are 3 types:
Left Join/Left Outer Join
1. Equi Join
Right Join/Right Outer Join
2. Non-equi Join
Full Join/Full Outer Join
3. Self Join
3. Cross Join Or Cartesian Join
SQL Joins
i. INNER JOIN:
✓ It returns all rows if there is a match in tables. Customer Orders
✓ Based on equality condition we are retriving data from id name oid amount id
multiple tables, here joining conditional columns must 1 John
1 200 10
2 Robert 2 500 3
belongs to same datatype. 3 David 3 300 6
4 John 4 800 5
5 Betty 5 150 8

Syntax Example OUTPUT


SELECT columns
SELECT C.id, C.name, O.amount id name amount
FROM table1 3 David 500
FROM Customers as C
INNER JOIN table2 5 Betty 800
INNER JOIN Orders as O
ON condition1 ;
ON C.id = O.id;
SQL Joins
ii. LEFT OUTER JOIN: Customer Orders

✓ 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

Syntax Example OUTPUT


id name amount
SELECT column_lists SELECT C.id, C.name, O.amount
3 David 500
FROM table1 FROM Customers as C 5 Betty 800
RIGHT JOIN table2 RIGHT JOIN Orders as O 200
ON table1.column = table2.column; ON C.id = O.id;
300
150
SQL Joins
iv. FULL OUTER JOIN: Customer Orders
✓ The FULL OUTER JOIN in SQL Server returns a result that id name oid amount id
1 John
includes all rows from both tables. 1 200 10
2 Robert 2 500 3
✓ The columns of the right-hand table return NULL when no 3 David 3 300 6
matching records are found in the left-hand table. 4 John 4 800 5
✓ And if no matching records are found in the right-hand table, the 5 Betty 5 150 8

left-hand table column returns NULL.

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

Updating record throught view :


✓ A view can be updated under certain conditions:
✓ The SELECT clause may not contain the keyword DISTINCT / summary functions / set functions / set
operators/ ORDER BY clause/ FROM clause may not contain multiple tables/WHERE clause may not contain
subqueries/not contain GROUP BY or HAVING.
✓ All NOT NULL columns from the base table must be included in the view in order for the INSERT query to
function.
✓ So if a view satisfies all the above-mentioned rules then you can update a view.
EX: SQL>UPDATE emp_v SET sal=2000 WHERE empno=1;
SQL Views
Deleting record throught view :
SQL>DELETE FROM emp_v WHERE empno=1;

With Check Option :


✓ If VIEW created with WITH CHECK OPTION then any DML operation through that view violates where
condition then that DML operation returns error.
Example :
SQL>CREATE VIEW V2 AS SELECT empno,ename,sal,deptno FROM emp WHERE deptno=10 WITH CHECK OPTION ;

✓ Then insert the record into emp table through view V2


SQL>INSERT INTO V2 VALUES(2323,’RAJU’,4000,20) ;
✓ The above INSERT returns error because DML operation violating WHERE clause.
Data Control Language(DCL)
✓ DCL commands are used to grant and take back authority from any database user.
✓ some commands that come under DCL:
i. Grant
ii. Revoke
GRANT:
✓ It is used to grant(give access to) security privileges to specific users of the database.
✓ It is mostly used to restrict user access to INSERT, DELETE, SELECT, UPDATE, EXECUTE, ALTER or to provide
privileges to user's data.
REVOKE:
✓ It is used to take back permissions from the user that was granted via the GRANT command.
✓ It is mostly used to withdrawing the permission that was authorized to carry out specific tasks.
Data Control Language(DCL)
Syntax Syntax

GRANT <privileges> ON <object name> REVOKE <privileges> ON <object name>

TO <user/roles> FROM <user/roles>

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

❖ object_name: Object could be anything amongst table, view or functions.

❖ 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

You might also like