473,903 Members | 5,741 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Using Subqueries - 1

debasisdas
8,127 Recognized Expert Expert
Using Subqueries
=============== ===

The sub query is often referred to as a nested SELECT, Sub - SELECT, or inner SELECT statement.

The sub query executes once before the main query.
The result of the sub query is used by the main query (outer Query).

You can place the sub query in a number of SQL clauses.
WHERE clause
HAVING clause
FROM clause (Inline sub query/inline view)

1.THE NESTED QUERY MUST RETURN A SINGLE COLUMN.
2.THE BETWEEN OPERATOR CAN'T BE USED IN SUBQUERIES.
3.THE RESULT CAN ONLY CONTAIN COLUMNS FROM THE TABLES REFERENCED IN THE OUTER MOST QUERIES.

Types of sub query
---------------------------
Single -row sub queries: -
Queries that return only one row from the inner SELECT statement.

Multiple -row sub queries: -
Return more than one row from the inner SELECT statement.

Note:
---------
Comparison operators fall into two classes. :
Single - row operators (>, >=, =, <>, <, <=)
Multiple - row operators (IN, ANY, SOME, ALL)

Syntax
---------
SELECT select_list FROM table
WHERE expr operator (SELECT select_list FROM table);

**Do not add an ORDER BY clause to a sub query.
*Use single-row operators with single-row sub queries.
*Use multiple-row operators with multiple-row sub queries.

Sample example of Single row sub query: -
=============== =============== ===

Example #1
Who earn more than empno 7566
Expand|Select|Wrap|Line Numbers
  1. SELECT *  FROM emp WHERE sal >(SELECT sal FROM emp WHERE empno=7566);
  2.  
Example #2
Display details of employee whose job is equal to 7369

Expand|Select|Wrap|Line Numbers
  1. SELECT * FROM emp
  2. WHERE job= (SELECT job FROM emp WHERE empno=7369);
  3.  
Example #3

Displays employees whose job title is the same as that of employee 7369 and whose salary is greater than that of employee 7876.
Expand|Select|Wrap|Line Numbers
  1. SELECT * FROM emp WHERE job= (SELECT job FROM emp
  2. WHERE empno=7369)  AND Sal > ( SELECT Sal FROM emp WHERE  empno=7876);
  3.  
USING GROUP FUNCTION in sub-queries
=============== =============== ===
Example #1
--------------------
Display details of all employees whose salary is equal to the minimum salary.

Expand|Select|Wrap|Line Numbers
  1.  SELECT * FROM emp
  2. WHERE sal = (SELECT MIN(sal) FROM emp);
  3.  
Exp:-The MIN group function returns a single value(800) to the outer query.
display data from a main query by using a group function in a subquery to return a single row.

Using HAVING clause with subqueries***** **********
The Oracle Server returns results into the main query's HAVING clause.

Example #2
------------------------
Display all the departments that have a minimum salary greater than that of department 20's MIN(Sal);
Expand|Select|Wrap|Line Numbers
  1. SELECT deptno, MIN(sal) FROM emp GROUP BY deptno HAVING MIN(sal) >
  2. ( SELECT MIN(sal) FROM emp WHERE deptno=20);
  3.  
deptno=20's MIN sal is 800.
i.e. subquery is 800
main query compares MIN(sal) > 800;

Example #3
----------------------
Find the job with the lowest avg salary.
Expand|Select|Wrap|Line Numbers
  1. SELECT job, AVG(sal) FROM emp GROUP BY job
  2. HAVING AVG(sal) = (SELECT  MIN(AVG(sal)) FROM emp GROUP BY job);
  3.  
Also Check Using Subqueries - 2
Sep 17 '07 #1
0 5715

Sign in to post your reply or Sign up for a free account.

Similar topics

6
1808
by: pete | last post by:
Been banging my head against the wall with subqueries. Even simple stuff like this fails: SELECT CompanyName FROM tblcompanies WHERE CompanyName IN (SELECT HostName FROM tblhosts) Am I missing something blindingly obvious, or is MySQL just playing silly buggers? Running v 4.0.18 btw on Windows Server 2003
5
2432
by: Nick | last post by:
Im moving a development app (MySQL 5.0) to a different server which runs MySQL 4.0.20-standard. I am getting errors on queries that have subqueries such as... SELECT id FROM table1 WHERE id IN ( SELECT id FROM table1 )
2
2345
by: Kevin | last post by:
While converting SQL statements for a database change, I discovered a big performance hit in MYSQL with subqueries vices Sybase. I'm hoping that someone might be able to help me understand why? I have two tables USERS (2200 records) and JOB Decriptions (163 records). I wanted to retrieve all the job description not in the USER table. (No Indexes on JOBDESC currently) select JOBDESC from JOBS where JOBDESC not in ( select JOBDESC from...
11
3674
by: SQL_developer | last post by:
Hello, I am trying to update a column in a table with an 8 digit string. The 8 digit number is obtained from another column which is a comments field. e.g. Comments Field :
2
2679
by: psuaudi | last post by:
I have a main query that I would like to call two different subqueries. In MS Access, I usually just save the two subqueries as separate queries which are then called by a third separate and main query. However, I'd like to put them all into one SQL command. Is this possible? Here are the queries: -This query calls the other two queries below- SELECT ., ., Format(((.Date)-(.Date)),"Fixed") AS , .Type FROM INNER JOIN ON (. = .) AND...
4
2963
by: muzu1232004 | last post by:
Can anyone explain me when we use correlated subqueries rather than nested subqueries. Do all the correlated subqueries can be written in nested subqueries form as well ? What are the major conditions that apply whenever we write a correlated subquery and why we go for it ? Please let me know about this as i am not clear which to use when.
1
11447
debasisdas
by: debasisdas | last post by:
Using Co-related sub query ======================== While a subquery is evaluated only once for each table, a correlated subquery is evaluated once for each row. Sub query can take value from outer query. Ex#1 --------- Delete duplicate record from table
0
7681
MMcCarthy
by: MMcCarthy | last post by:
Rather than using the Access design view change the view to SQL. I am going to attempt to outline the general syntax used for SQL queries in Access. Angle brackets <> are used in place of some syntax elements you must supply. The description of these elements will be in the contained in the angle brackets. Square brackets are used to show which parts are optional. Basic SELECT query SELECT <field list> FROM <table/query name(s)>
1
2886
by: lizandra | last post by:
Greetings, I am a newbie, I have been working to extract data from a basic sales db and trying to decide when I should use joins and when I should use subqueries. Much of what I read online says use subqueries only as a last resort, especially correlated ones as they do a record by record data evaluation and are very resource intensive. Are joins and WHERE and HAVING clauses the preferred method for extracting related data? But in SQL...
0
9999
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
9849
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
11285
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
1
10986
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
10501
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
9688
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
8049
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
7208
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
6094
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.