• Share
  • Email
  • Embed
  • Like
  • Save
  • Private Content
Sql query [select, sub] 4
 

Sql query [select, sub] 4

on

  • 1,429 views

 

Statistics

Views

Total Views
1,429
Views on SlideShare
1,428
Embed Views
1

Actions

Likes
1
Downloads
2
Comments
0

1 Embed 1

http://mj89sp3sau2k7lj1eg3k40hkeppguj6j-a-sites-opensocial.googleusercontent.com 1

Accessibility

Categories

Upload Details

Uploaded via as Microsoft PowerPoint

Usage Rights

© All Rights Reserved

Report content

Flagged as inappropriate Flag as inappropriate
Flag as inappropriate

Select your reason for flagging this presentation as inappropriate.

Cancel
  • Full Name Full Name Comment goes here.
    Are you sure you want to
    Your message goes here
    Processing…
Post Comment
Edit your comment

    Sql query [select, sub] 4 Sql query [select, sub] 4 Presentation Transcript

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