473,609 Members | 2,173 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Subqueries in SQL

NeoPa
32,566 Recognized Expert Moderator MVP
To use a subquery (SQ) in SQL there are two ways :
  1. Treating the SQ as a record source (like a table).
  2. Treating the SQ as a single value.
In either case, the SQ is a simple SELECT query but surrounded by parentheses ().
In case 1 the SQ should either be in the FROM clause or, sometimes possible put within the In() command.
In case 2 the SQ can be used in place of any other item that returns a value (SELECT; WHERE; HAVING; GROUP BY; etc).

Assume the following structure :
Expand|Select|Wrap|Line Numbers
  1. Table Name=tblOKData
  2. ID; Autonumber; PK
  3. Name; String
with records :
Expand|Select|Wrap|Line Numbers
  1. 1   Bat
  2. 2   Ball
  3. 3   Racquet
Expand|Select|Wrap|Line Numbers
  1. Table Name=tblALLData
  2. ID; Autonumber; PK
  3. Name; String
with records :
Expand|Select|Wrap|Line Numbers
  1. 1   Glass
  2. 2   Cup
  3. 3   Plate
  4. 21  Bat
  5. 22  Ball
  6. 23  Racquet
Using a SQ within In().
Say that we wanted to show the tblAllData.ID for all items whose names match those found in the tblOKData table. We could use an INNER JOIN in this case, but alternatively (necessary to illustrate the point here) we could do it with a SQ.
The code would be :
Expand|Select|Wrap|Line Numbers
  1. SELECT ID
  2. FROM tblAllData
  3. WHERE Name In(SELECT [Name]
  4.               FROM tblOKData)
Using a SQ within the FROM clause as a Recordset.
The simplest form of this is to surround a basic SELECT query in parentheses and rename (AS {Name}).
In this case we want the same effect as the SQL above.
The code would be :
Expand|Select|Wrap|Line Numbers
  1. SELECT subQ.ID
  2. FROM (SELECT *
  3.       FROM tblAllData) AS subQ INNER JOIN tblOKData
  4.   ON subQ.Name = tblOKData.Name
Using a SQ as a Simple Value.
We want to select all tblAllData.IDs which are greater than the average value of these IDs.
The code would be :
Expand|Select|Wrap|Line Numbers
  1. SELECT [ID]
  2. FROM tblAllData
  3. WHERE [ID]>(SELECT Avg([ID])
  4.             FROM tblAllData)
Attached Files
File Type: zip SubQueries.Zip (8.6 KB, 754 views)
Jan 26 '07 #1
0 14707

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

Similar topics

6
1797
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
6
2053
by: Daniel Elliott | last post by:
Hello, I was wondering if anyone would be able to help me with a problem I'm having. I'm trying to use the following query: SELECT Distinct c.site_id FROM campsite c WHERE c.site_id NOT IN (SELECT cs.site_id FROM campsite_status cs WHERE c.site_id = cs.site_id
5
2421
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
2327
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...
2
3253
by: CSN | last post by:
Is there much difference between using subqueries and separating out them into separate queries? __________________________________ Do you Yahoo!? Yahoo! SiteBuilder - Free web site building tool. Try it! http://webhosting.yahoo.com/ps/sb/ ---------------------------(end of broadcast)--------------------------- TIP 8: explain analyze is your friend
2
1548
by: orin | last post by:
Hi all, I've seen mention that you can use nested subqueries down to as many levels as you like but whenever I run the following: select * from table1 where tab1ID in (select tab1ID from table2 where tab2ID in (select tab2ID from Table3 where Tab3ID=N))
2
2666
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
2953
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.
0
5697
debasisdas
by: debasisdas | last post by:
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
1
2875
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
8035
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
8534
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...
0
8374
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
6969
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...
0
5502
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
4002
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
1
2502
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
1
1630
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
0
1366
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

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.