Wednesday 23 October 2013

Scalar Subqueries in Oracle

Scalar Subqueries
Introduced in Oracle9i, scalar subqueries allow you to treat the output of a subquery as a column or even an expression within a SELECT statement. It is a query that only selects one column or expression and returns just one row. If the scalar subquery fails to return select any rows, Oracle will use a NULL value for the output of the scalar subquery. Before Oracle9i, it was possible to use the scalar subquery within the SET clause of the UPDATE statement and within the VALUES list of the INSERT INTO statement. This ability provides greater flexibility to use the scalar subquery just about anywhere you can use an expression. Sometimes it is easier to list the places you CANNOT use a scalar subquery:

  • For default column values
  • As the basis for a function-based index
  • As a hash expression for a cluster
  • In CHECK constraints for DDL statements
  • In WHEN conditions for CASE statements
  • In GROUP BY and HAVING clauses for SQL queries
  • In CONNECT BY and START WITH clauses for SQL queries
The following is an example of using the scalar subquery to determine how many rows in the DEPARTMENT table contain an employee corresponding to each row in the EMPLOYEE table:

SQL> SELECT
  2      d.dept_id
  3    , d.dept_name
  4    , (SELECT count(*) FROM employee e 
  5       WHERE e.dept_id = d.dept_id) as "How Many Departments"
  6  FROM department d;


   DEPT_ID DEPT_NAME         How Many Departments
---------- --------------- ----------------------
       100 Finance                              1
       101 Engineering                          2
       103 HR                                   1

No comments:

Post a Comment