DBA Tips Archive for Oracle

  


Scalar Subqueries

by Jeff Hunter, Sr. Database Administrator


Contents

  1. Scalar Subqueries



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:

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


Copyright (c) 1998-2017 Jeffrey M. Hunter. All rights reserved.

All articles, scripts and material located at the Internet address of http://www.idevelopment.info is the copyright of Jeffrey M. Hunter and is protected under copyright laws of the United States. This document may not be hosted on any other site without my express, prior, written permission. Application to host any of the material elsewhere can be made by contacting me at jhunter@idevelopment.info.

I have made every effort and taken great care in making sure that the material included on my web site is technically accurate, but I disclaim any and all responsibility for any loss, damage or destruction of data or any other property which may arise from relying on it. I will in no case be liable for any monetary damages arising from such loss, damage or destruction.

Last modified on
Saturday, 11-Mar-2006 17:30:48 EST
Page Count: 8960