A blog on SQL , PLSQL , Linux concepts. Interview Questions from different companies. For suggestions and contributions, reach me at sivak36@gmail.com
Monday, September 26, 2016
Oracle SQL WITH Query
WITH Query:
In complex queries that process the same subquery multiple times, the WITH clause lets you factor out the subquery, give it a name, then reference that name multiple times within
the original complex query.
This query joins two tables and computes the aggregate SUM(SAL) more than once.
The text in blue represents the parts of the query that are repeated.
SELECT dname, SUM(sal) AS dept_total
FROM emp, dept
WHERE emp.deptno = dept.deptno
GROUP BY dname HAVING SUM(sal) >( SELECT SUM(sal) * 1/3 FROM emp, dept
WHERE emp.deptno = dept.deptno ) ORDER BY SUM(sal) DESC;
Query optimized with WITH syntax.
The aggregation and fetch from the database tables is done only once
WITH summary AS
( SELECT dname, SUM(sal) AS dept_total FROM emp, dept WHERE emp.deptno = dept.deptno GROUP BY dname )
SELECT dname, dept_total
FROM summary
WHERE dept_total > ( SELECT SUM(dept_total) * 1/3 FROM summary )
ORDER BY dept_total DESC;
Featured Post
Will the data from Oracle Database be lost after formatting the system in which it is installed?
So Someone asked me a question, Will the data from Oracle Database be lost after formatting the system in which it is installed? Since the ...
Popular Posts
-
Experience Level - 3- 5 Years SQL Questions: Brief about your experience, skills and projects you worked on. 1.Differenfe betw...
-
Data Dictionary tables/Views contain information about the database and its objects. These are automatically created and maintained by oracl...
-
E 1st round Queries on joins, group by , not in, rank , dense rank, decode, case. (for half an hour to write queries ,given different ta...
-
Select * from a where hiredate+60 < sysdate; (here hiredate is non-unique index, so query scanning index range or full table scanning. ...
-
Generate Sequence of Numbers from 1 to N using SQL Query SELECT LEVEL AS ID FROM DUAL CONNECT BY LEVEL <= 20; ...
-
Stages of Processing SQL Statement: SQL statements pass through several stages during their processing: Parsing Binding Executing O...
-
Introduction Both LAG and LEAD functions have the same usage, as shown below. LAG (value_expression [,offset] [,default]) OVER ([quer...
-
About Temporary Tables : Temporary tables are database tables that hold session specific data Each session can only see and modify its o...
-
Parameter Modes in PLSQL procedures and functions are IN , OUT, IN OUT. The differences are as follows.