Download as ppt, pdf, or txt
Download as ppt, pdf, or txt
You are on page 1of 66

SQL Query Writing Training

SQL Query Writing Training

SPAN Confidential and Copyright


Database

Database is a collection of data that is treated as


Database – Definition

a unit. The purpose of a database is to store and


retrieve related information.

SPAN Confidential and Copyright


Difference in DBMS and RDBMS
• Tables are not related. • Tables are related.
• Only one user can
access the same • Many users
database at the same simultaneously access
DBMS Vs RDBMS

time. the same database.


• Not very secure • Very secure.
• Does not support large • Supports large volume
volume of data. of data.

Ex: FoxPro & Earlier Ex: Oracle, MS SQL


versions of Ms Access Server, DB2

SPAN Confidential and Copyright


Normalization

It's the process of efficiently organizing data in a database.


Normalization

There are two goals of the normalization process:


• Eliminate redundant data (for example, storing the same data
in more than one table)
• Ensure data dependencies make sense (only storing related
data in a table).

SPAN Confidential and Copyright


0 NF

CUSTOMER_ORDER
(CustName, OrderNo, ProdNo, ProdDesc, Qty, CustAddress, DateOrdered)
Normalization

1 NF

CUSTOMER
(CustName, CustAddress)

ORDER (CustName, OrderNo, ProdNo, ProdDesc, Qty, DateOrdered)

SPAN Confidential and Copyright


• Second normal form (2NF) further addresses the concept
of removing duplicative data:
– Meet all the requirements of the first normal form.
Normalization

– Every Non key column is fully dependent on key


column.
– Create relationships between these new tables and
their predecessors through the use of foreign keys.

SPAN Confidential and Copyright


1NF - remove multivalued dependencies

CUSTOMER (CustName, CustAddress)

ORDER (CustName, OrderNo, ProdNo, ProdDesc, Qty, DateOrdered)


Normalization

2NF - remove partial dependencies

CUSTOMER (CustName, CustAddress)

CUSTOMER ORDER (CustName, OrderNo)

ORDER (OrderNo, ProdNo, ProdDesc, Qty, DateOrdered)

SPAN Confidential and Copyright


• Third normal form (3NF) goes one large step further:
– Meet all the requirements of the second normal form.
– Every non key column mutually independent .There
Normalization

Shouldn’t be any transitive dependency.


– Remove columns that are not dependent upon the
primary key.

SPAN Confidential and Copyright


2NF - remove partial dependencies
CUSTOMER (CustName, CustAddress)
CUSTOMER ORDER (CustName, OrderNo)
ORDER (OrderNo, ProdNo, ProdDesc, Qty, DateOrdered)

3NF - remove transitive dependencies


Normalization

CUSTOMER (CustName, CustAddress)

CUSTOMER ORDER (CustName, OrderNo)

ORDER (OrderNo, ProdNo, Qty, DateOrdered)

PRODUCT (ProdNo, ProdDesc)


SPAN Confidential and Copyright
Normalize the following Data:

Student# Advisor Adv-Room Class1 Class2 Class3

1022 Jones 412 101-07 143-01 159-02


Normalization

4123 Smith 216 201-01 211-02 214-01

SPAN Confidential and Copyright


Database Objects
• Tables
• Views
• Indexes
Database Objects

• Constraints
• Procedures
• Functions
• Packages
• Triggers
SPAN Confidential and Copyright
Statements in Oracle
•SELECT Statement
Oracle SQL Statements

•DDL Statement

•DML Statement

•TCL Statement

SPAN Confidential and Copyright


Data Definition Language
Data Definition Language

1. Create
2. Alter
3. Drop
4. Truncate

SPAN Confidential and Copyright


Integrity Constraints
An integrity constraint is a declarative method of
defining a rule for a column of a table.

• NOT NULL constraints for the rules associated with


nulls in a column. Not Null constraints is not allowed
Integrity Constraints

at table level.
• UNIQUE key constraints for the rule associated with
unique column values
• PRIMARY KEY constraints for the rule associated
with primary identification values
• FOREIGN KEY constraints for the rules associated
with referential integrity.
• CHECK constraints for complex integrity rules

SPAN Confidential and Copyright


DDL
CREATE TABLE SQLTest1 (
No INT PRIMARY KEY ,
First_name VARCHAR2(100) NOT NULL ,
Last_name VARCHAR2(100) NOT NULL ,
Data Definition Language

Sal INT CHECK(sal >=10000)) ;

CREATE TABLE SQLTest2 ( No INT ,


First_name VARCHAR2(100) NOT NULL ,
Last_name VARCHAR2(100) NOT NULL ,
Sal int CHECK(Sal >=10000),
CONSTRAINT Pk_name PRIMARY KEY(Last_name,First_name) ) ;
SPAN Confidential and Copyright
DDL

CREATE TABLE SQLTest3 (


No INT PRIMARY KEY ,
Data Definition Language

First_name VARCHAR2(100) NOT NULL ,


Last_name VARCHAR2(100) NOT NULL ,
Deptno INT ,
Sal INT CHECK(Sal >=10000) ,
CONSTRAINT Fk_dept FOREIGN KEY (Deptno)
REFERENCES Dept(Deptno))

SPAN Confidential and Copyright


DDL
• To add new column DeptNo to Emp Table
ALTER TABLE SQLTest1
ADD Deptno INT;
• To Modify First_Name Column data length
Data Definition Language

ALTER TABLE SQLTest1


MODIFY First_name VARCHAR2(150);
• To drop the column Age from Emp_Test
ALTER TABLE Emp_Test DROP COLUMN Age

• To truncate the table data


TRUNCATE TABLE Emp;
SPAN Confidential and Copyright
Synonym

Synonyms provide both data independence and location


transparency.
Synonyms permit applications to function without
Synonym

modification regardless of which user owns the table or


view and regardless of which database holds the table or
view.

Create Synonym syn_emp For emp;

SPAN Confidential and Copyright


View

• A View is a logical table based on one or more tables or views.


• A view contains no data itself.

This statement will create a view with EmpNo , EName , Job ,


DeptNo columns.
View

CREATE VIEW vw_Emp AS

SELECT EmpNo , EName , Job , DeptNo FROM Emp ;

SPAN Confidential and Copyright


Structured Query Language(SQL)
Structured Query Language

SQL is a simple, powerful database access


language that is the standard language for
relational database management systems.

SPAN Confidential and Copyright


Query Processing

• Parsing the source code to locate any syntax errors


Query Processing

• Invoking the SQL optimizer to derive an execution plan

• Create and run an executable, based on the execution plan

• Fetching the results set from the database and return it to


the calling query.

SPAN Confidential and Copyright


Query Processing

Query
OPTIMIZER
Query Processing

Query Optimization
Parse Query rewrite
RBO / CBO

Query QEP
Result
Execution Generation

SPAN Confidential and Copyright


Select Statement

SELECT *|select-list
FROM table-name [, table-name]...
SELECT Statement

[WHERE search-condition]
[ORDER BY sort-spec [, sort-spec]...]
[GROUP BY column-name [, column-
name]...]
[HAVING having-condition]
SPAN Confidential and Copyright
Select Statement

Selection Projection
SELECT Statement

Table 1 Table 1

SPAN Confidential and Copyright


Operators
• Logical Operators – AND, OR, NOT

• Comparison Operators – Between, like,In,


Is Null, =, !=,<>, >,>=,<,<=
SQL Operators

• Like – Like is used for pattern search.


– "_" matches any single character
– "%" matches any string of zero or more characters
except null.

SPAN Confidential and Copyright


SET Operators

• UNION -- All rows selected by either


query.
• UNION ALL -- All rows selected by either
SQL Operators

query, including all duplicates.


• INTERSECT -- All distinct rows selected by both
queries.
• MINUS -- All distinct rows selected by the
first query but not the second.

SPAN Confidential and Copyright


Select Restrictions

• In WHERE clause aggregate(group) functions are not


allowed
SELECT Restrictions

• HAVING clause follows GROUP BY clause.

SPAN Confidential and Copyright


Queries
• To fetch all the columns from Emp table
SELECT * FROM Emp;
• To fetch specified columns from Emp Table
SELECT Ename, Empno, Sal FROM Emp;
• To fetch the Emp details who has salary greater than 1000
Queries

SELECT * FROM Emp WHERE Sal > 1000;


• To fetch the Emp details whose salary is between 1000
And 2000
SELECT * FROM Emp
WHERE Sal BETWEEN 1000 And 2000;

SPAN Confidential and Copyright


Queries
• SELECT * FROM Emp
WHERE Ename LIKE ‘_ONE%’;

Note: The wild character ‘%’ is used for multiple character


replacement.’_’ (underscore) can be used for single character
replacement.
Queries

• To Fetch the Emp details whose name is either ‘SMITH’ or


‘KING’
SELECT * FROM Emp
WHERE Ename IN (‘SMITH’,’KING’);

Note: String comparison in Oracle is case-sensitive.

SPAN Confidential and Copyright


Queries (Contd)

• To fetch the Emp details who has Commission as NULL


SELECT * FROM Emp
WHERE Comm IS NULL;
Queries - Contd

• To fetch the Emp details in ascending order


SELECT Ename FROM Emp
ORDER By Ename;

SPAN Confidential and Copyright


Using Column Aliases
SQL> SELECT ename AS name, sal salary
2 FROM emp;

NAME SALARY
------------- ---------
Queries - Contd

...

SQL> SELECT ename "Name",


2 sal*12 "Annual Salary"
3 FROM emp;

Name Annual Salary


------------- -------------
...
SPAN Confidential and Copyright
Aggregate Functions
• Sum • Avg
• Min • Count
• Max • StdDev
• To fetch total salary for all the employees.
Queries - Contd

SELECT SUM(Sal) FROM Emp;

• To fetch total salary for each department.


SELECT DeptNo ,SUM(Sal) FROM Emp
GROUP BY DeptNo;

SPAN Confidential and Copyright


Query relational tables – Group by
Example: List employee’s departments giving a count of employees in each.

select deptno 10 select deptno 10


from Emp 10 from Emp 20
order by deptno; 10 group by deptno; 30
20
20
20 Aggregate Function!
20
20 select deptno, count(*) 10 3
30 from Emp 20 5
30 group by deptno; 30 6
30
30 Select queries can contain functions and
30 calculations as well as attribute names in
30 the select condition!
SPAN Confidential and Copyright
Query relational tables – Group by
select deptno, sum(sal),
sum(sal)/count(*) 10 8750 2916.6667
from Emp 20 10875 2175
group by deptno; 30 9400 1566.6667

Example: List employee’s departments giving a count of employees in each,


provided that there are over four employees in the department.

The having clause is used in Group


select deptno, count(*) Selections in the same way that the
from Emp 20 5 where clause is used in standard
group by deptno 30 6 tuple selections.
having count(*) > 4;
SPAN Confidential and Copyright
Query relational tables – Group by
Combined Example: List, in reverse order of average department salary, the
total salary and average salary for each department that has employees, and
where the average salary of each department is over 2000
select deptno, sum(sal), sum(sal)/count(*)
from Emp
group by deptno 10 8750 2916.6667
having sum(sal)/count(*) > 2000 20 10875 2175
order by sum(sal)/count(*) desc;

The result of an SQL Select is, as shown, a new (unnamed) relation. The
attributes of this new relation are named on the basis of the select statement.
DEPTNO SUM(SAL) SUM(SAL)/COUNT(*)
10 8750 2916.6667
20 10875 2175
ALIAS:-
ALIAS select deptno, sum(sal) “Total Salary”, sum(sal)/count(*) “Avg Salary”
DEPTNO Total Salary Avg Salary
10 8750 SPAN Confidential
2916.6667
and Copyright
20 10875 2175
Aggregate Functions

• To fetch the departments having more than 20 employees


SELECT DeptNo , Count(*) FROM Emp
GROUP BY DeptNo
HAVING COUNT(*) > 20;
Queries - Contd

• SELECT AVG(Comm) FROM Emp;


Note: Avg , Count function will ignore NULLs.

SPAN Confidential and Copyright


SET Operators

• SELECT Deptno FROM Emp • SELECT Deptno FROM Emp


UNION INTERSECT
SELECT Deptno FROM Dept; SELECT Deptno FROM Dept;
Queries - Contd

• SELECT Deptno FROM Emp • SELECT Deptno FROM Emp


UNION ALL MINUS
SELECT Deptno FROM Dept; SELECT Deptno FROM Dept;

SPAN Confidential and Copyright


Joins
A join is a query that combines rows from two or more tables
• An equijoin is a join with a join condition containing an
equality operator. An equijoin combines rows that have
equivalent values for the specified columns.

SELECT e.Ename,
Joins

e.Sal,
e.Deptno,
d.Dname
FROM Emp e JOIN Dept d
ON e.Deptno =d.Deptno;

SPAN Confidential and Copyright


NATURAL JOIN
A NATURAL JOIN joins two tables based on the key
columns they have in common.

SELECT e.Ename,
e.Sal,
Natural Join

e.Deptno,
d.Dname
FROM Emp e NATURAL JOIN Dept d ;

SPAN Confidential and Copyright


Self Join
A self join is a join of a table to itself.

SELECT e.Empno,
e.Ename,
e.Sal,
Self Join

m.Ename
FROM Emp e
JOIN Emp m
ON e.Mgr = m.Empno;

SPAN Confidential and Copyright


Cartesian Product
Cartesian Product : Joining multiple tables with out
any join condition

SELECT e.Ename,
Cartesian Product

e.Sal,
e.Deptno,
d.Dname
FROM Emp e , Dept d

SPAN Confidential and Copyright


Outer Join

An outer join extends the result of a simple join. An


outer join returns all rows that satisfy the join
condition and those rows from one table for which
Outer Join

no rows from the other satisfy the join condition.

SPAN Confidential and Copyright


Outer Join
This query retrieves all rows in Emp table which is the left table even if
there is no match in Dept table.

SELECT e.Ename ,
e.Deptno ,
d.Dname
Outer Join

FROM Emp e
LEFT JOIN
Dept d
ON e.Deptno = d.Deptno;

SPAN Confidential and Copyright


Outer Join
This query retrieves all rows in Dept table which is the right table
even if there is no match in Emp table.

SELECT e.Ename ,
e.Deptno ,
d.Dname
Outer Join

FROM Emp e
RIGHT JOIN
Dept d
ON e.Deptno = d.Deptno

SPAN Confidential and Copyright


Outer Join
This query retrieves all rows in Emp table which is the left table even if
there is no match in Dept table. It also retrieves all rows in Dept table
which is the right table even if there is no match in Emp table.

SELECT e.Ename ,
e.Deptno ,
d.Dname
Outer Join

FROM Emp e
FULL JOIN
Dept d
ON e.Deptno = d.Deptno

SPAN Confidential and Copyright


Anti Join
AntiJoin returns rows from the left side of the predicate for which there
are no corresponding rows on the right side of the predicate. That is, it
returns rows that fail to match (NOT IN) the subquery on the right side.
Ex: selects a list of employees who are not in a particular set of
departments:
SELECT *
Anti Join

FROM Employees
WHERE Department_id
NOT IN (SELECT Department_id
FROM Departments
WHERE Location_id = 1700);

SPAN Confidential and Copyright


Semi Join

Semi join returns rows that match an EXISTS


subquery without duplicating rows from the left side
of the predicate when multiple rows on the right side
satisfy the criteria of the sub query.
Semi Join

SELECT * FROM Dept


WHERE EXISTS (SELECT 1
FROM Emp
WHERE Dept.Deptno = Emp.Deptno);

SPAN Confidential and Copyright


Sub Query

A top-level SELECT statement is called a query, and a


query nested within another SQL statement is called a
subquery.
SELECT *
Sub Query

FROM Emp
WHERE Deptno IN (
SELECT Deptno
FROM Dept
);

SPAN Confidential and Copyright


Correlated Subquery

•A correlated subquery when the subquery references


Correlated Subquery

a column from a table referred to in the parent


statement.

A correlated subquery is evaluated once for each row


processed by the parent statement.

SPAN Confidential and Copyright


Correlated Subquery

SELECT Orderid, Customerid


Correlated Subquery

FROM Orders o
WHERE 20 < (SELECT Quantity
FROM Order_details od
WHERE o.Orderid = od.Orderid
AND od.Productid = 23)

SPAN Confidential and Copyright


Correlated Subquery
Correlated Subquery

SPAN Confidential and Copyright


Correlated Subquery
To fetch Employee details whose salary is greater than his
manager salary

SELECT *
Correlated Subquery

FROM Emp a
WHERE a.Sal > (SELECT Sal
FROM Emp b
WHERE b.Empno = a.Mgr);

SPAN Confidential and Copyright


When to Use Joins Rather Than Subqueries

• Often, a query that contains subqueries can be written as a


join. Query performance may be similar with a join and a
subquery. The difference is that a subquery may require
the query optimizer to perform additional steps, such as
Join Vs Subquery

sorting, which may influence the processing strategy.

• Using joins typically allows the query optimizer to retrieve


data in the most efficient way. If a query does not require
multiple steps, it may not be necessary to use a subquery.

SPAN Confidential and Copyright


Inline View
SELECT a.Empno,
a.Ename,
a.Sal,
b.Sal turner_sal
Inline View

FROM Emp a,
(SELECT * FROM Emp
WHERE Ename = 'Turner') b
WHERE a.Sal > b.Sal

SPAN Confidential and Copyright


DML Statements
• INSERT INTO Dept_test
(DeptNo,DName,Capacity,Dept_head)
VALUES (10,’sales’,100,’scott’);

• Inserting the result of a SELECT statement into Dept Table


INSERT INTO Dept
DML

SELECT * FROM Dept_bkp

• UPDATE Dept_test
SET Dname = ‘marketing’
WHERE Deptno = 10;

• DELETE FROM Dept_test WHERE Deptno=10;

SPAN Confidential and Copyright


Predefined Functions
• SYSDATE
To get current date:
SELECT SYSDATE FROM DUAL;
• DECODE
Predefined Functions

To implement If-Then-Else logic within the SQL Statement ,we can use
DECODE.
EX: If DeptNo 10 , comm is 1.10*Sal, if DeptNo 20 , comm is 1.15*Sal,
if DeptNo 30 , comm is 1.10*Sal else comm is 0.5*Sal

SELECT Ename, Job, Sal , DECODE (DeptNo , 10 , 1.10*Sal,


20 , 1.15*Sal,
30, 1.90 *Sal, 0.5*Sal)
Comm

FROM Emp;
SPAN Confidential and Copyright
Predefined Functions
• CASE
To implement If-Then-Else logic within the SQL Statement ,we can use
CASE.

EX: If DeptNo 10 , comm is 1.10*Sal, if DeptNo 20 , comm is 1.15*Sal,


Predefined Functions

if DeptNo 30 , comm is 1.10*Sal else comm is 0.5*Sal

SELECT Ename, Job, Sal ,

CASE WHEN DeptNo = 10 THEN 1.10*Sal

WHEN DeptNo = 20 THEN 1.15*Sal

WHEN DeptNo = 30 THEN 1.90 *Sal


ELSE 0.5*Sal END Comm

FROM Emp;
SPAN Confidential and Copyright
String Functions
• LENGTH: To get length of a string
SELECT LENGTH('Sql Server') FROM DUAL;

• UPPER: To convert the string to UPPER Case


SELECT UPPER('Sql Server') FROM DUAL;
String Functions

• INSTR: Returns the numeric position of a named string.Optionally,


you can provide a position m to start searching, and the occurrence n
of the string. m and n default to 1, meaning start the search at the
beginning and report the first occurrence.
INSTR(column/expression,’string’,[,m], [n]))

Ex: SELECT INSTR('Sql Server‘ , ‘e’,1,1) FROM DUAL;

SPAN Confidential and Copyright


String Functions

• REPLACE: Searches a text expression for a character string and if


found, replaces it with a specified replacement string.

REPLACE(text, search_string , replacement_string)


String Functions

Ex: SELECT REPLACE('Sql Server','e','x') FROM DUAL;

• SUBSTR: Returns specified characters from character value starting


at character position m, n characters long (if n is negative the count
starts from the end of the character value. If n is omitted, all characters
to the end of the string are returned.

SUBSTR(column/expression,m,[,n])
Ex: SELECT SUBSTR(‘Sql Server’,5,6) FROM DUAL;

SPAN Confidential and Copyright


String Functions
• LPAD: Pads the character value right-justified to a total width of n
character positions.

LPAD(column|expression, n, ‘string’)
SELECT LAPD(Ename , 20, ‘ * ’) FROM Emp;
String Functions

• TRIM: Enables you to trim heading or trailing characters(or both)


from a character string.

TRIM(leading|trailing|both , trim_character FROM trim_source)

SELECT TRIM(‘S‘ FROM ‘SQL’) FROM DUAL;

SPAN Confidential and Copyright


Date Functions

•ADD_MONTHS: Adds calendar months to date.

SELECT ADD_MONTHS(Hiredate , 2) FROM Emp;


Date Functions

•MONTHS_BETWEEN: Number of months between two dates


SELECT MONTHS_BETWEEN(SYSDATE , Hiredate) FROM Emp;

•NEXT_DAY: Next day of the date specified


SELECT NEXT_DAY( SYSDATE,'Monday') FROM DUAL;

SPAN Confidential and Copyright


Conversion Functions
• TO_CHAR : Converts a number or date value to a VARCHAR2
character string with format model fmt.

SELECT TO_CHAR(HireDate, 'dd-Mon-YYYY' ) FROM Emp;


Conversion Functions

• TO_DATE : Converts a character string representing a date to a date


value according to the fmt specified.
If fmt is omitted, the format is DD-MON-YY

SELECT TO_DATE('02-Jan-2007', 'dd-Mon-YYYY' ) FROM DUAL;

• TO_NUMBER : Converts a character string containing digits to a


number in the format specified by the optional format model fmt.
SELECT TO_NUMBER('02') FROM DUAL;

SPAN Confidential and Copyright


Creating New Table From Existing Table

• Oracle syntax:

CREATE TABLE Payroll_Bkp AS


SELECT * FROM Payroll

• SQL Server Syntax:


SELECT * INTO Payroll_Bkp FROM Payroll

SPAN Confidential and Copyright


Index

•An index is a performance-tuning method of allowing faster


retrieval of records.

•An index creates an entry for each value that appears in the
Index

indexed columns

SPAN Confidential and Copyright


TCL Statements
Transaction control statements manage the
changes made by DML statements and group
DML statements into transactions.
TCL Statements

Make a transaction's changes permanent


(COMMIT)
Undo the changes in a transaction, either since the
transaction started or since a savepoint
(ROLLBACK)
Set a point to which you can roll back
(SAVEPOINT)

SPAN Confidential and Copyright


Thank You
Thank You

SPAN Confidential and Copyright

You might also like