SlideShare a Scribd company logo
DQL  [Data Query Language]
Syntax for SELECT statement:   SELECT <COLUMN-LIST> FROM <TABLE-NAME> [WHERE <CONDITION>] GROUP BY <COLUMN-NAME(S)>] [HAVING <CONDITION>] [ORDER BY <EXPRESSION>];     Example:  Select * from EMP;
Selecting one or more columns from the table It is possible to select only few columns from the table.  To list employee number, employee name, job and salary from EMP table, the following query to be given.   Example:  SELECT EMPNO, ENAME, SAL, JOB FROM EMP;   It is not necessary for the column(s) in the SELECT statement, to be in the same order of the table.  
Changing Column names using Aliases To distinguish the real column name with a more meaning full name for better understanding while displaying the results then, an  alias  can be used after that column name.  In EMP table the column MGR stands for MANAGER.  To display MGR column as MANAGER the query can be written using alias as follows:   SQL> SELECT EMPNO, ENAME,  MGR &quot;MANAGER&quot;  FROM EMP;
WHERE Clause   Conditional retrieval of rows using WHERE clause Example: SELECT * FROM EMP WHERE DEPTNO = 10; WHERE clause filters the EMP table with DEPTNO = 10 alone.  Oracle checks the DEPTNO column in each row for an entry as 10,  if found then it sends them as output else skips the rows which does not match the condition.  The WHERE clause in the SELECT statement can have Relational, Logical, Arithmetic and String Operators.  Example 1: SELECT * FROM EMP WHERE ENAME = ‘SMITH’;
Working with NULL values    NULL  values are not 0 or blank.    It represents an unknown or inapplicable value It cannot be compared using the relational and/or  logical operators. The special operator  ‘IS’  is used with the keyword  ‘NULL’  to locate NULL values. Examples: SELECT ENAME FROM EMP WHERE COMM  IS NULL ;   (The above command will list the employee(s) who is not getting commission).   
Order by Clause Displaying the results in a sorted order SQL uses the  ORDER BY  clause to impose an order on the result of a query. ORDER BY clause is used with SELECT statement. One or more columns and/or expressions can be specified in ORDER  BY clause. The  ORDER BY  clause sorts the query output according to the values in one or more selected columns.  Multiple columns are ordered one with another, and the user can specify whether to order them in ascending or descending order. Ascending is default .
Syntax: SELECT <COLUMNS> FROM <TABLE-NAME> ORDER BY  [<COLUMN-NAME>, <COLUMN-NAME>] ASC/DESC; Example 1: SELECT * FROM EMP ORDER BY ENAME; (The above command will list all the employees from EMP table in ascending order of employee name) Example 2: SELECT EMPNO, ENAME, DEPTNO, SAL FROM EMP ORDER BY DEPTNO; (The above command will list all the employees from EMP table in ascending order of Department number) Example 3: SELECT EMPNO, ENAME, HIREDATE EMP ORDER BY HIREDATE DESC; (The above command will list all the employees from EMP  table in descending of hiredate).
Sorting the result on multiple columns   To sort DEPTNO of EMP table in ascending order and then to further sort salary in each department in descending order, the following example query can be issued. Example: SELECT EMPNO, ENAME, DEPTNO, SAL  FROM EMP  ORDER  BY DEPTNO, SAL DESC;  
GROUP BY clause   ORDER BY acts upon rows whereas GROUP BY acts upon groups.  Example: SELECT MAX(SAL), MIN(SAL), AVG(SAL), COUNT(*), SUM(SAL) FROM EMP; Output: MAX(SAL)  MIN(SAL)  AVG(SAL)  COUNT(*)  SUM(SAL) -------------  --------------  -------------  -------------  ------------- 5000  800  2073.2143  14  29025  
To find the maximum of salary for department 10, then the query has to be:   SQL > SELECT MAX(SAL) FROM EMP WHERE DEPTNO = 10;   Output: MAX(SAL) --------------   5000  
To find Department wise  the sum of salary, max of salary, min salary etc., GROUP BY clause comes handy to group the records of the table based on a grouping column.   GROUP BY clause is used with SELECT to combine a group of rows based on the values of a particular column or expression.  Aggregate functions are used to return summary information for each group.  The aggregate functions are applied to the individual groups.  By default, all the rows of a table are treated as a single group only.  The following example will list the max of salary from each department.
Example: SELECT MAX(SAL), DEPTNO FROM EMP GROUP BY DEPTNO;   Output: MAX(SAL)  DEPTNO -------- --------- 5000  10 3000  20 2850   30
The GROUP BY DEPTNO clause divides the rows of the table into groups based on their DEPTNO.  The group function MAX(SAL) is then applied to the rows in each group. A query that uses the GROUP BY clause is termed as a  ‘grouped query’. The columns named in the GROUP BY clause are called the ‘ grouping columns’.  They determine how the rows should be grouped.  If the  SQL statement does not contain a WHERE clause, place the GROUP BY clause after the FROM clause.  If it has a WHERE clause, place the GROUP BY clause after the WHERE clause.
The example lists the number of employees in each job. Example:  SELECT COUNT(*), JOB FROM EMP GROUP BY JOB;   Output: COUNT(*)  JOB ---------  ---------   2  ANALYST   4  CLERK   3  MANAGER   1  PRESIDENT 4                   SALESMAN  
Use of WHERE clause and GROUP BY clause . Example:  SELECT COUNT(*), JOB FROM EMP WHERE DEPTNO = 10 GROUP BY JOB; Output: COUNT(*)  JOB ---------  --------- 1  CLERK 1  MANAGER 1  PRESIDENT First the WHERE clause filters the rows based on the condition.  Followed by this, rows are grouped job-wise.  Then group function COUNT operates on the rows of each group to calculate group wise count.
Grouping rows based on multiple columns Grouping the rows of the table based on more than one column. The following example lists the number of employees for each job type within department. ( Dept wise and then Designation wise ) Example SELECT DEPTNO, JOB, COUNT(*) FROM EMP GROUP BY DEPTNO, JOB; Output: DEPTNO  JOB  COUNT(*) ---------  ---------  --------- 10  CLERK  1 10  MANAGER  1 10  PRESIDENT  1 20  ANALYST  2 20  CLERK  2 20  MANAGER  1 30  CLERK  1 30  MANAGER  1 30  SALESMAN  4
HAVING Clause The GROUP BY . . . HAVING clause is parallel to the WHERE clause. WHERE clause acts upon rows  whereas  GROUP BY . . . HAVING  act on groups.  As specific rows can be fetched with a WHERE clause,  specific groups can be fetched using HAVING clause. HAVING clause has to be placed after the GROUP BY clause when  queried.  The HAVING clause works much like the WHERE clause, except that its logic is related to the results of group functions.
Example to illustrates the use of GROUP BY . . .HAVING clause: Select the dept having more than 3 employees Example 1: SELECT DEPTNO, COUNT(*) FROM EMP  GROUP BY DEPTNO HAVING COUNT(*) > 3;   Output: DEPTNO COUNT(*) ---------  ---------     20  5   30 6    
To display the managers, who have more than 2 people reporting to them.    Example 2: SELECT MGR, COUNT(*) FROM EMP   GROUP BY MGR  HAVING COUNT(*) > 2;   Output: MGR  COUNT(*) --------  -------- 7698  5 7839   3
The following example illustrates WHERE clause, GROUP BY … HAVING clause and ORDER BY clause.   Example: SELECT COUNT(*), SUM(SAL), JOB FROM EMP WHERE DEPTNO = 20 GROUP BY JOB HAVING SUM(SAL) > 2000 ORDER BY JOB;   Output: COUNT(*)  SUM(SAL)  JOB ------------  --------------  --------- 2  6000  ANALYST 1  2975  MANAGER
Difference between Group By, Having Clause and Order By, Where Clause:   Group by clause  groups the rows into smaller groups according to the given query and then shows the output in a particular sequence. Having Clause  is used for condition retrieval of rows from a grouped result. Order by clause  imposes an order on the result of a query. Where Clause  with Order by is used for conditional retrieval of individual rows.
SUB - QUERIES   Sub-Queries are nothing but nested SELECT statement.  The output of inner query is taken as the input of outer query. Sub-queries are used in the WHERE or HAVING clause of another SQL statement (Parent/Main Query).  SQL first evaluates the inner query (or sub query) within the WHERE clause.  The inner query generates values that are tested in the predict of the outer query. The return value of inner query is then substituted in the condition of the outer query.  Sub Queries can use commands namely SELECT, INSERT, UPDATE, DELETE and CREATE.  Sub query can itself contain a sub query.  Oracle 8i places no limit on the level of query nesting.
Advantage of Sub-Queries        The nested sub-query is very useful when you need to select rows from a table with a condition that depends on the data in the table itself.  
Types of Sub-Queries   Sub-query returning one row Sub-query returning more than one row Correlated Sub-query
Sub-query returning one row List the employees belonging to the department of  ALLEN. Example :  Step 1: SELECT DEPTNO FROM EMP  WHERE ENAME = 'ALLEN';   Output: DEPTNO ---------   30   Step 2:  SELECT ENAME FROM EMP WHERE DEPTNO = 30;   Output: ENAME ---------- ALLEN WARD MARTIN BLAKE TURNER JAMES
The  two queries can be combined as a single query.    Example: SELECT ENAME  FROM EMP   WHERE DEPTNO =  (SELECT DEPTNO  FROM EMP   WHERE ENAME = ‘ALLEN’); Output: ENAME ---------- ALLEN WARD MARTIN BLAKE TURNER JAMES  
Sub-query can be used to select the values from multiple tables.  Example:  List the employee(s) who are working in SALES department. SELECT EMPNO, ENAME, JOB, DEPTNO  FROM EMP  WHERE DEPTNO =  (SELECT DEPTNO  FROM DEPT  WHERE DNAME = ‘SALES’);   Output: EMPNO ENAME  JOB  DEPTNO ---------  ----------  --------- -  -------- 7499  ALLEN    SALESMAN  30 7521  WARD    SALESMAN  30 7654  MARTIN SALESMAN  30 7698  BLAKE  MANAGER  30 7844  TURNER SALESMAN  30 7900  JAMES  CLERK  30
Sub-query returning more than one row   When a sub-query returns more than one row we need to use  multi-row comparison operator.  List the employees who are acting as Managers . Example: SELECT EMPNO, ENAME FROM EMP  WHERE EMPNO  IN (SELECT MGR FROM EMP); Output:   EMPNO  ENAME   ------- ----------   7566  JONES   7698  BLAKE   7782  CLARK   7788  SCOTT 7839  KING   7902  FORD  
List the employees who are getting highest salary in each department from EMP table. Example: SELECT EMPNO, ENAME, SAL, DEPTNO FROM EMP  WHERE SAL  IN  (SELECT MAX(SAL) FROM EMP GROUP BY DEPTNO);   Output : EMPNO ENAME  SAL  DEPTNO ----------  ----------  ---------  ---------   7698  BLAKE 2850  30   7788  SCOTT  3000  20   7902  FORD  3000  20 7839  KING  5000  10
List the employee(s) whose salary is more than all MANAGER’s Salary from EMP table.   Example: SELECT EMPNO, ENAME, SAL FROM EMP  WHERE SAL >  ALL (SELECT SAL FROM EMP  WHERE JOB =  'MANAGER');   Output: EMPNO  ENAME  SAL ---------    ----------  ---------   7788    SCOTT  3000   7839    KING  5000   7902    FORD  3000   
To note The inner query must be enclosed in parenthesis. The inner query must be on the right hand side of  the condition. The sub-query may not have an order by clause. The ORDER BY clause appears at the end of the  main select statement. Sub-queries are always executed from the most deeply nested to the least deeply nested, unless they are correlated sub-query.
Correlated Sub-query   A correlated sub-query is a nested sub-query. The outer most query will be executed first. The sub-query is executed repeatedly, once for each row of main(outer) query table. In a correlated sub-query, the column value used in inner sub-query refers to the column value present in the outer query forming a correlated sub-query.
Example: List the employees who earn salary greater than the average salary for their own department. SELECT EMPNO, ENAME, SAL, DEPTNO FROM  EMP A  WHERE SAL >(SELECT AVG(SAL) FROM EMP WHERE DEPTNO = A.DEPTNO);   Output: EMPNO  ENAME  SAL  DEPTNO ----------  ----------  ---------  ---------   7499   ALLEN  1600    30 7566   JONES    2975  20   7698   BLAKE  2850  30 7788   SCOTT  3000  20   7839   KING  5000  10 7902   FORD  3000  20  
Order of execution (corelated subquery) Outer query is executed first select empno,ename,deptno,sal from emp;  Inner query is executed for each row in the outer query select avg(sal) from emp where deptno=10;  and  Compares where the salary is greater for each employeed in deptno 10;
Using Special Operators in Sub-queries   EXISTS ANY SOME ALL operators
Operators   EXISTS This operator is used to check the existence of values This operator produces a Boolean result It takes a sub-query as an argument and evaluates it to True if the sub-query produce any output and false, if the sub-query does not produce any output       ANY, SOME and ALL Used along with the relational operators Similar to IN operator, but only used in sub-queries  
Example for EXISTS operator     List the Employee who has at least one person reporting to him. Example 1: SELECT EMPNO, ENAME, JOB, DEPTNO FROM EMP E  WHERE EXISTS  (SELECT EMPNO FROM EMP WHERE MGR = E.EMPNO);   Output: EMPNO  ENAME SAL DEPTNO --------  ------------ -------- --------- 7499  ALLEN  1600  30 7566  JONES 2975  20 7698  BLAKE 2850  30 7788  SCOTT  3000 20 7839  KING  5000  10   7902  FORD 3000  20
Differences between Correlated Sub-queries and Non- Correlated Sub-queries:   In a  non-correlated sub-query the inner most query is executed first. But in a Correlated sub-query the outer most query is analyzed first and then based on its result the next-query is initiated The sub-query is executed repeatedly, once for each row of main(outer) query table.

More Related Content

What's hot (20)

PDF
SQL BASIC QUERIES SOLUTION ~hmftj
LGS, GBHS&IC, University Of South-Asia, TARA-Technologies
 
PPTX
SQL
Vineeta Garg
 
PPT
MySQL
Gouthaman V
 
PPTX
SQL Operators.pptx
RUBAB79
 
PPT
MYSQL Aggregate Functions
Leroy Blair
 
PPT
Aggregating Data Using Group Functions
Salman Memon
 
PDF
Sql tutorial
Rumman Ansari
 
PDF
DBMS 5 | MySQL Practice List - HR Schema
Mohammad Imam Hossain
 
PPT
Writing Basic SQL SELECT Statements
Salman Memon
 
PPTX
Sql - Structured Query Language
Wan Hussain Wan Ishak
 
DOC
Sql queries with answers
vijaybusu
 
PPT
Introduction to structured query language (sql)
Sabana Maharjan
 
PPTX
Oraclesql
Priya Goyal
 
PDF
SQL Functions and Operators
Mohan Kumar.R
 
DOC
Plsql task answers
Nawaz Sk
 
PPT
Introduction to-sql
BG Java EE Course
 
PPT
Sql Tutorials
Priyabrat Kar
 
PPTX
Sql operator
Pooja Dixit
 
PPTX
Sql clauses by Manan Pasricha
MananPasricha
 
SQL Operators.pptx
RUBAB79
 
MYSQL Aggregate Functions
Leroy Blair
 
Aggregating Data Using Group Functions
Salman Memon
 
Sql tutorial
Rumman Ansari
 
DBMS 5 | MySQL Practice List - HR Schema
Mohammad Imam Hossain
 
Writing Basic SQL SELECT Statements
Salman Memon
 
Sql - Structured Query Language
Wan Hussain Wan Ishak
 
Sql queries with answers
vijaybusu
 
Introduction to structured query language (sql)
Sabana Maharjan
 
Oraclesql
Priya Goyal
 
SQL Functions and Operators
Mohan Kumar.R
 
Plsql task answers
Nawaz Sk
 
Introduction to-sql
BG Java EE Course
 
Sql Tutorials
Priyabrat Kar
 
Sql operator
Pooja Dixit
 
Sql clauses by Manan Pasricha
MananPasricha
 

Viewers also liked (18)

PPTX
SQL Server - CLR integration
Peter Gfader
 
PDF
Sql tutorial, tutorials sql
Vivek Singh
 
PDF
Travel research-2015-boomer-travel-trends-infographic-aarp-res-gen
Next Avenue
 
PDF
Sql wksht-5
Mukesh Tekwani
 
PPT
sql statement
zx25 zx25
 
PPT
SQL querys in detail || Sql query slides
gourav kottawar
 
PDF
Top 25 Coldest Cities in America
nichecom
 
DOC
Sql queires
MohitKumar1985
 
ODT
Sql queries interview questions
Pyadav010186
 
PPT
SQL : introduction
Shakila Mahjabin
 
PDF
The Career Guide to Green Jobs
Kelly Services
 
PPTX
SQL Basics
Hammad Rasheed
 
PPT
SQL Tutorial - Basic Commands
1keydata
 
PPT
Sql ppt
Anuja Lad
 
DOCX
Sql Queries
User1test
 
DOC
A must Sql notes for beginners
Ram Sagar Mourya
 
PPT
Slideshare Powerpoint presentation
elliehood
 
PPTX
Slideshare ppt
Mandy Suzanne
 
SQL Server - CLR integration
Peter Gfader
 
Sql tutorial, tutorials sql
Vivek Singh
 
Travel research-2015-boomer-travel-trends-infographic-aarp-res-gen
Next Avenue
 
Sql wksht-5
Mukesh Tekwani
 
sql statement
zx25 zx25
 
SQL querys in detail || Sql query slides
gourav kottawar
 
Top 25 Coldest Cities in America
nichecom
 
Sql queires
MohitKumar1985
 
Sql queries interview questions
Pyadav010186
 
SQL : introduction
Shakila Mahjabin
 
The Career Guide to Green Jobs
Kelly Services
 
SQL Basics
Hammad Rasheed
 
SQL Tutorial - Basic Commands
1keydata
 
Sql ppt
Anuja Lad
 
Sql Queries
User1test
 
A must Sql notes for beginners
Ram Sagar Mourya
 
Slideshare Powerpoint presentation
elliehood
 
Slideshare ppt
Mandy Suzanne
 
Ad

Similar to Sql query [select, sub] 4 (20)

DOCX
Clauses in sql server
Naveen Kumar Veligeti
 
PDF
Group by clause mod
Nitesh Singh
 
PPT
Introduction to Oracle Functions--(SQL)--Abhishek Sharma
अभिषेक शर्मा
 
PDF
Introduction to oracle functions
Nitesh Singh
 
PPT
Sql dml & tcl 2
Dr. C.V. Suresh Babu
 
PPT
Module03
Sridhar P
 
DOCX
Database Query Using SQL_ip.docx
VandanaGoyal21
 
PPTX
SQL Data Manipulation language and DQL commands
sonali sonavane
 
PPT
Oracle tips and tricks
Yanli Liu
 
PPT
Aggregate Functions,Final
mukesh24pandey
 
PPTX
Les05 Aggregating Data Using Group Function
NETsolutions Asia: NSA – Thailand, Sripatum University: SPU
 
PDF
Chapter9 more on database and sql
KV(AFS) Utarlai, Barmer (Rajasthan)
 
PPT
Les06
Sudharsan S
 
PPTX
Sql
Aman Lalpuria
 
PPT
Les18
Vijay Kumar
 
PDF
Sql order by clause
Vivek Singh
 
PDF
5. Group Functions
Evelyn Oluchukwu
 
PPTX
SQL.pptx
MrHello6
 
PDF
Database Systems - SQL - DDL Statements (Chapter 3/3)
Vidyasagar Mundroy
 
PPTX
Unit 3-p2relationaldatabasescodeing.pptx
artipunia12
 
Clauses in sql server
Naveen Kumar Veligeti
 
Group by clause mod
Nitesh Singh
 
Introduction to Oracle Functions--(SQL)--Abhishek Sharma
अभिषेक शर्मा
 
Introduction to oracle functions
Nitesh Singh
 
Sql dml & tcl 2
Dr. C.V. Suresh Babu
 
Module03
Sridhar P
 
Database Query Using SQL_ip.docx
VandanaGoyal21
 
SQL Data Manipulation language and DQL commands
sonali sonavane
 
Oracle tips and tricks
Yanli Liu
 
Aggregate Functions,Final
mukesh24pandey
 
Les05 Aggregating Data Using Group Function
NETsolutions Asia: NSA – Thailand, Sripatum University: SPU
 
Chapter9 more on database and sql
KV(AFS) Utarlai, Barmer (Rajasthan)
 
Sql order by clause
Vivek Singh
 
5. Group Functions
Evelyn Oluchukwu
 
SQL.pptx
MrHello6
 
Database Systems - SQL - DDL Statements (Chapter 3/3)
Vidyasagar Mundroy
 
Unit 3-p2relationaldatabasescodeing.pptx
artipunia12
 
Ad

More from Dr. C.V. Suresh Babu (20)

PPTX
Data analytics with R
Dr. C.V. Suresh Babu
 
PPTX
Association rules
Dr. C.V. Suresh Babu
 
PPTX
Clustering
Dr. C.V. Suresh Babu
 
PPTX
Classification
Dr. C.V. Suresh Babu
 
PPTX
Blue property assumptions.
Dr. C.V. Suresh Babu
 
PPTX
Introduction to regression
Dr. C.V. Suresh Babu
 
PPTX
Expert systems
Dr. C.V. Suresh Babu
 
PPTX
Dempster shafer theory
Dr. C.V. Suresh Babu
 
PPTX
Bayes network
Dr. C.V. Suresh Babu
 
PPTX
Bayes' theorem
Dr. C.V. Suresh Babu
 
PPTX
Knowledge based agents
Dr. C.V. Suresh Babu
 
PPTX
Rule based system
Dr. C.V. Suresh Babu
 
PPTX
Formal Logic in AI
Dr. C.V. Suresh Babu
 
PPTX
Production based system
Dr. C.V. Suresh Babu
 
PPTX
Game playing in AI
Dr. C.V. Suresh Babu
 
PPTX
Diagnosis test of diabetics and hypertension by AI
Dr. C.V. Suresh Babu
 
PPTX
A study on “impact of artificial intelligence in covid19 diagnosis”
Dr. C.V. Suresh Babu
 
PDF
A study on “impact of artificial intelligence in covid19 diagnosis”
Dr. C.V. Suresh Babu
 
Data analytics with R
Dr. C.V. Suresh Babu
 
Association rules
Dr. C.V. Suresh Babu
 
Classification
Dr. C.V. Suresh Babu
 
Blue property assumptions.
Dr. C.V. Suresh Babu
 
Introduction to regression
Dr. C.V. Suresh Babu
 
Expert systems
Dr. C.V. Suresh Babu
 
Dempster shafer theory
Dr. C.V. Suresh Babu
 
Bayes network
Dr. C.V. Suresh Babu
 
Bayes' theorem
Dr. C.V. Suresh Babu
 
Knowledge based agents
Dr. C.V. Suresh Babu
 
Rule based system
Dr. C.V. Suresh Babu
 
Formal Logic in AI
Dr. C.V. Suresh Babu
 
Production based system
Dr. C.V. Suresh Babu
 
Game playing in AI
Dr. C.V. Suresh Babu
 
Diagnosis test of diabetics and hypertension by AI
Dr. C.V. Suresh Babu
 
A study on “impact of artificial intelligence in covid19 diagnosis”
Dr. C.V. Suresh Babu
 
A study on “impact of artificial intelligence in covid19 diagnosis”
Dr. C.V. Suresh Babu
 

Recently uploaded (20)

PPT
Ericsson LTE presentation SEMINAR 2010.ppt
npat3
 
PDF
Bitcoin for Millennials podcast with Bram, Power Laws of Bitcoin
Stephen Perrenod
 
PDF
NLJUG Speaker academy 2025 - first session
Bert Jan Schrijver
 
PDF
“Squinting Vision Pipelines: Detecting and Correcting Errors in Vision Models...
Edge AI and Vision Alliance
 
PDF
Transforming Utility Networks: Large-scale Data Migrations with FME
Safe Software
 
PDF
Peak of Data & AI Encore AI-Enhanced Workflows for the Real World
Safe Software
 
PDF
Staying Human in a Machine- Accelerated World
Catalin Jora
 
PPTX
New ThousandEyes Product Innovations: Cisco Live June 2025
ThousandEyes
 
PPTX
Agentforce World Tour Toronto '25 - MCP with MuleSoft
Alexandra N. Martinez
 
PPTX
COMPARISON OF RASTER ANALYSIS TOOLS OF QGIS AND ARCGIS
Sharanya Sarkar
 
PPTX
AI Penetration Testing Essentials: A Cybersecurity Guide for 2025
defencerabbit Team
 
PDF
UPDF - AI PDF Editor & Converter Key Features
DealFuel
 
PPTX
Mastering ODC + Okta Configuration - Chennai OSUG
HathiMaryA
 
PDF
Book industry state of the nation 2025 - Tech Forum 2025
BookNet Canada
 
PPTX
MuleSoft MCP Support (Model Context Protocol) and Use Case Demo
shyamraj55
 
PDF
SIZING YOUR AIR CONDITIONER---A PRACTICAL GUIDE.pdf
Muhammad Rizwan Akram
 
PDF
“Computer Vision at Sea: Automated Fish Tracking for Sustainable Fishing,” a ...
Edge AI and Vision Alliance
 
PDF
UiPath DevConnect 2025: Agentic Automation Community User Group Meeting
DianaGray10
 
PDF
Mastering Financial Management in Direct Selling
Epixel MLM Software
 
PDF
How do you fast track Agentic automation use cases discovery?
DianaGray10
 
Ericsson LTE presentation SEMINAR 2010.ppt
npat3
 
Bitcoin for Millennials podcast with Bram, Power Laws of Bitcoin
Stephen Perrenod
 
NLJUG Speaker academy 2025 - first session
Bert Jan Schrijver
 
“Squinting Vision Pipelines: Detecting and Correcting Errors in Vision Models...
Edge AI and Vision Alliance
 
Transforming Utility Networks: Large-scale Data Migrations with FME
Safe Software
 
Peak of Data & AI Encore AI-Enhanced Workflows for the Real World
Safe Software
 
Staying Human in a Machine- Accelerated World
Catalin Jora
 
New ThousandEyes Product Innovations: Cisco Live June 2025
ThousandEyes
 
Agentforce World Tour Toronto '25 - MCP with MuleSoft
Alexandra N. Martinez
 
COMPARISON OF RASTER ANALYSIS TOOLS OF QGIS AND ARCGIS
Sharanya Sarkar
 
AI Penetration Testing Essentials: A Cybersecurity Guide for 2025
defencerabbit Team
 
UPDF - AI PDF Editor & Converter Key Features
DealFuel
 
Mastering ODC + Okta Configuration - Chennai OSUG
HathiMaryA
 
Book industry state of the nation 2025 - Tech Forum 2025
BookNet Canada
 
MuleSoft MCP Support (Model Context Protocol) and Use Case Demo
shyamraj55
 
SIZING YOUR AIR CONDITIONER---A PRACTICAL GUIDE.pdf
Muhammad Rizwan Akram
 
“Computer Vision at Sea: Automated Fish Tracking for Sustainable Fishing,” a ...
Edge AI and Vision Alliance
 
UiPath DevConnect 2025: Agentic Automation Community User Group Meeting
DianaGray10
 
Mastering Financial Management in Direct Selling
Epixel MLM Software
 
How do you fast track Agentic automation use cases discovery?
DianaGray10
 

Sql query [select, sub] 4

  • 1. DQL [Data Query Language]
  • 2. Syntax for SELECT statement:   SELECT <COLUMN-LIST> FROM <TABLE-NAME> [WHERE <CONDITION>] GROUP BY <COLUMN-NAME(S)>] [HAVING <CONDITION>] [ORDER BY <EXPRESSION>];     Example: Select * from EMP;
  • 3. Selecting one or more columns from the table It is possible to select only few columns from the table. To list employee number, employee name, job and salary from EMP table, the following query to be given.   Example: SELECT EMPNO, ENAME, SAL, JOB FROM EMP;   It is not necessary for the column(s) in the SELECT statement, to be in the same order of the table.  
  • 4. Changing Column names using Aliases To distinguish the real column name with a more meaning full name for better understanding while displaying the results then, an alias can be used after that column name. In EMP table the column MGR stands for MANAGER. To display MGR column as MANAGER the query can be written using alias as follows:   SQL> SELECT EMPNO, ENAME, MGR &quot;MANAGER&quot; FROM EMP;
  • 5. WHERE Clause   Conditional retrieval of rows using WHERE clause Example: SELECT * FROM EMP WHERE DEPTNO = 10; WHERE clause filters the EMP table with DEPTNO = 10 alone. Oracle checks the DEPTNO column in each row for an entry as 10, if found then it sends them as output else skips the rows which does not match the condition. The WHERE clause in the SELECT statement can have Relational, Logical, Arithmetic and String Operators. Example 1: SELECT * FROM EMP WHERE ENAME = ‘SMITH’;
  • 6. Working with NULL values   NULL values are not 0 or blank.   It represents an unknown or inapplicable value It cannot be compared using the relational and/or logical operators. The special operator ‘IS’ is used with the keyword ‘NULL’ to locate NULL values. Examples: SELECT ENAME FROM EMP WHERE COMM IS NULL ;   (The above command will list the employee(s) who is not getting commission).   
  • 7. Order by Clause Displaying the results in a sorted order SQL uses the ORDER BY clause to impose an order on the result of a query. ORDER BY clause is used with SELECT statement. One or more columns and/or expressions can be specified in ORDER BY clause. The ORDER BY clause sorts the query output according to the values in one or more selected columns. Multiple columns are ordered one with another, and the user can specify whether to order them in ascending or descending order. Ascending is default .
  • 8. Syntax: SELECT <COLUMNS> FROM <TABLE-NAME> ORDER BY [<COLUMN-NAME>, <COLUMN-NAME>] ASC/DESC; Example 1: SELECT * FROM EMP ORDER BY ENAME; (The above command will list all the employees from EMP table in ascending order of employee name) Example 2: SELECT EMPNO, ENAME, DEPTNO, SAL FROM EMP ORDER BY DEPTNO; (The above command will list all the employees from EMP table in ascending order of Department number) Example 3: SELECT EMPNO, ENAME, HIREDATE EMP ORDER BY HIREDATE DESC; (The above command will list all the employees from EMP table in descending of hiredate).
  • 9. Sorting the result on multiple columns   To sort DEPTNO of EMP table in ascending order and then to further sort salary in each department in descending order, the following example query can be issued. Example: SELECT EMPNO, ENAME, DEPTNO, SAL FROM EMP ORDER BY DEPTNO, SAL DESC;  
  • 10. GROUP BY clause   ORDER BY acts upon rows whereas GROUP BY acts upon groups. Example: SELECT MAX(SAL), MIN(SAL), AVG(SAL), COUNT(*), SUM(SAL) FROM EMP; Output: MAX(SAL) MIN(SAL) AVG(SAL) COUNT(*) SUM(SAL) ------------- -------------- ------------- ------------- ------------- 5000 800 2073.2143 14 29025  
  • 11. To find the maximum of salary for department 10, then the query has to be:   SQL > SELECT MAX(SAL) FROM EMP WHERE DEPTNO = 10;   Output: MAX(SAL) -------------- 5000  
  • 12. To find Department wise the sum of salary, max of salary, min salary etc., GROUP BY clause comes handy to group the records of the table based on a grouping column.   GROUP BY clause is used with SELECT to combine a group of rows based on the values of a particular column or expression. Aggregate functions are used to return summary information for each group. The aggregate functions are applied to the individual groups. By default, all the rows of a table are treated as a single group only. The following example will list the max of salary from each department.
  • 13. Example: SELECT MAX(SAL), DEPTNO FROM EMP GROUP BY DEPTNO;   Output: MAX(SAL) DEPTNO -------- --------- 5000 10 3000 20 2850  30
  • 14. The GROUP BY DEPTNO clause divides the rows of the table into groups based on their DEPTNO. The group function MAX(SAL) is then applied to the rows in each group. A query that uses the GROUP BY clause is termed as a ‘grouped query’. The columns named in the GROUP BY clause are called the ‘ grouping columns’. They determine how the rows should be grouped. If the SQL statement does not contain a WHERE clause, place the GROUP BY clause after the FROM clause. If it has a WHERE clause, place the GROUP BY clause after the WHERE clause.
  • 15. The example lists the number of employees in each job. Example: SELECT COUNT(*), JOB FROM EMP GROUP BY JOB;   Output: COUNT(*) JOB --------- --------- 2 ANALYST 4 CLERK 3 MANAGER 1 PRESIDENT 4                   SALESMAN  
  • 16. Use of WHERE clause and GROUP BY clause . Example: SELECT COUNT(*), JOB FROM EMP WHERE DEPTNO = 10 GROUP BY JOB; Output: COUNT(*) JOB --------- --------- 1 CLERK 1 MANAGER 1 PRESIDENT First the WHERE clause filters the rows based on the condition. Followed by this, rows are grouped job-wise. Then group function COUNT operates on the rows of each group to calculate group wise count.
  • 17. Grouping rows based on multiple columns Grouping the rows of the table based on more than one column. The following example lists the number of employees for each job type within department. ( Dept wise and then Designation wise ) Example SELECT DEPTNO, JOB, COUNT(*) FROM EMP GROUP BY DEPTNO, JOB; Output: DEPTNO JOB COUNT(*) --------- --------- --------- 10 CLERK 1 10 MANAGER 1 10 PRESIDENT 1 20 ANALYST 2 20 CLERK 2 20 MANAGER 1 30 CLERK 1 30 MANAGER 1 30 SALESMAN 4
  • 18. HAVING Clause The GROUP BY . . . HAVING clause is parallel to the WHERE clause. WHERE clause acts upon rows whereas GROUP BY . . . HAVING act on groups. As specific rows can be fetched with a WHERE clause, specific groups can be fetched using HAVING clause. HAVING clause has to be placed after the GROUP BY clause when queried. The HAVING clause works much like the WHERE clause, except that its logic is related to the results of group functions.
  • 19. Example to illustrates the use of GROUP BY . . .HAVING clause: Select the dept having more than 3 employees Example 1: SELECT DEPTNO, COUNT(*) FROM EMP GROUP BY DEPTNO HAVING COUNT(*) > 3;   Output: DEPTNO COUNT(*) --------- --------- 20 5 30 6    
  • 20. To display the managers, who have more than 2 people reporting to them.   Example 2: SELECT MGR, COUNT(*) FROM EMP GROUP BY MGR HAVING COUNT(*) > 2;   Output: MGR COUNT(*) -------- -------- 7698 5 7839   3
  • 21. The following example illustrates WHERE clause, GROUP BY … HAVING clause and ORDER BY clause.   Example: SELECT COUNT(*), SUM(SAL), JOB FROM EMP WHERE DEPTNO = 20 GROUP BY JOB HAVING SUM(SAL) > 2000 ORDER BY JOB;   Output: COUNT(*) SUM(SAL) JOB ------------ -------------- --------- 2 6000 ANALYST 1 2975 MANAGER
  • 22. Difference between Group By, Having Clause and Order By, Where Clause:   Group by clause groups the rows into smaller groups according to the given query and then shows the output in a particular sequence. Having Clause is used for condition retrieval of rows from a grouped result. Order by clause imposes an order on the result of a query. Where Clause with Order by is used for conditional retrieval of individual rows.
  • 23. SUB - QUERIES   Sub-Queries are nothing but nested SELECT statement. The output of inner query is taken as the input of outer query. Sub-queries are used in the WHERE or HAVING clause of another SQL statement (Parent/Main Query). SQL first evaluates the inner query (or sub query) within the WHERE clause. The inner query generates values that are tested in the predict of the outer query. The return value of inner query is then substituted in the condition of the outer query. Sub Queries can use commands namely SELECT, INSERT, UPDATE, DELETE and CREATE. Sub query can itself contain a sub query. Oracle 8i places no limit on the level of query nesting.
  • 24. Advantage of Sub-Queries       The nested sub-query is very useful when you need to select rows from a table with a condition that depends on the data in the table itself.  
  • 25. Types of Sub-Queries   Sub-query returning one row Sub-query returning more than one row Correlated Sub-query
  • 26. Sub-query returning one row List the employees belonging to the department of ALLEN. Example : Step 1: SELECT DEPTNO FROM EMP WHERE ENAME = 'ALLEN';   Output: DEPTNO --------- 30   Step 2: SELECT ENAME FROM EMP WHERE DEPTNO = 30;   Output: ENAME ---------- ALLEN WARD MARTIN BLAKE TURNER JAMES
  • 27. The two queries can be combined as a single query.   Example: SELECT ENAME FROM EMP WHERE DEPTNO = (SELECT DEPTNO FROM EMP WHERE ENAME = ‘ALLEN’); Output: ENAME ---------- ALLEN WARD MARTIN BLAKE TURNER JAMES  
  • 28. Sub-query can be used to select the values from multiple tables. Example: List the employee(s) who are working in SALES department. SELECT EMPNO, ENAME, JOB, DEPTNO FROM EMP WHERE DEPTNO = (SELECT DEPTNO FROM DEPT WHERE DNAME = ‘SALES’);   Output: EMPNO ENAME JOB DEPTNO --------- ---------- --------- - -------- 7499 ALLEN SALESMAN 30 7521 WARD SALESMAN 30 7654 MARTIN SALESMAN 30 7698 BLAKE MANAGER 30 7844 TURNER SALESMAN 30 7900 JAMES CLERK 30
  • 29. Sub-query returning more than one row   When a sub-query returns more than one row we need to use multi-row comparison operator. List the employees who are acting as Managers . Example: SELECT EMPNO, ENAME FROM EMP WHERE EMPNO IN (SELECT MGR FROM EMP); Output: EMPNO ENAME ------- ---------- 7566 JONES 7698 BLAKE 7782 CLARK 7788 SCOTT 7839 KING 7902 FORD  
  • 30. List the employees who are getting highest salary in each department from EMP table. Example: SELECT EMPNO, ENAME, SAL, DEPTNO FROM EMP WHERE SAL IN (SELECT MAX(SAL) FROM EMP GROUP BY DEPTNO);   Output : EMPNO ENAME SAL DEPTNO ---------- ---------- --------- --------- 7698 BLAKE 2850 30 7788 SCOTT 3000 20 7902 FORD 3000 20 7839 KING 5000 10
  • 31. List the employee(s) whose salary is more than all MANAGER’s Salary from EMP table.   Example: SELECT EMPNO, ENAME, SAL FROM EMP WHERE SAL > ALL (SELECT SAL FROM EMP WHERE JOB = 'MANAGER');   Output: EMPNO ENAME SAL --------- ---------- --------- 7788 SCOTT 3000 7839 KING 5000 7902 FORD 3000  
  • 32. To note The inner query must be enclosed in parenthesis. The inner query must be on the right hand side of the condition. The sub-query may not have an order by clause. The ORDER BY clause appears at the end of the main select statement. Sub-queries are always executed from the most deeply nested to the least deeply nested, unless they are correlated sub-query.
  • 33. Correlated Sub-query   A correlated sub-query is a nested sub-query. The outer most query will be executed first. The sub-query is executed repeatedly, once for each row of main(outer) query table. In a correlated sub-query, the column value used in inner sub-query refers to the column value present in the outer query forming a correlated sub-query.
  • 34. Example: List the employees who earn salary greater than the average salary for their own department. SELECT EMPNO, ENAME, SAL, DEPTNO FROM EMP A WHERE SAL >(SELECT AVG(SAL) FROM EMP WHERE DEPTNO = A.DEPTNO);   Output: EMPNO ENAME SAL DEPTNO ---------- ---------- --------- --------- 7499 ALLEN 1600 30 7566 JONES 2975 20 7698 BLAKE 2850 30 7788 SCOTT 3000 20 7839 KING 5000 10 7902 FORD 3000 20  
  • 35. Order of execution (corelated subquery) Outer query is executed first select empno,ename,deptno,sal from emp; Inner query is executed for each row in the outer query select avg(sal) from emp where deptno=10; and Compares where the salary is greater for each employeed in deptno 10;
  • 36. Using Special Operators in Sub-queries   EXISTS ANY SOME ALL operators
  • 37. Operators EXISTS This operator is used to check the existence of values This operator produces a Boolean result It takes a sub-query as an argument and evaluates it to True if the sub-query produce any output and false, if the sub-query does not produce any output      ANY, SOME and ALL Used along with the relational operators Similar to IN operator, but only used in sub-queries  
  • 38. Example for EXISTS operator     List the Employee who has at least one person reporting to him. Example 1: SELECT EMPNO, ENAME, JOB, DEPTNO FROM EMP E WHERE EXISTS (SELECT EMPNO FROM EMP WHERE MGR = E.EMPNO);   Output: EMPNO ENAME SAL DEPTNO -------- ------------ -------- --------- 7499 ALLEN 1600 30 7566 JONES 2975 20 7698 BLAKE 2850 30 7788 SCOTT 3000 20 7839 KING 5000 10 7902 FORD 3000 20
  • 39. Differences between Correlated Sub-queries and Non- Correlated Sub-queries:   In a non-correlated sub-query the inner most query is executed first. But in a Correlated sub-query the outer most query is analyzed first and then based on its result the next-query is initiated The sub-query is executed repeatedly, once for each row of main(outer) query table.