473,657 Members | 2,572 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Finding a way to avoid joins/inner selects

In SQL 2005 I'm writing a query that works fine as an inner select or
a join but I know there's gotta be a way to do it without doing either
of those, for obvious performance reasons. I just want to hit the
database once.

Lets say you have a table with 2 columns, users and shipments. A user
can have multiple shipments but those shipments can only be inbound or
outbound so the table would look like this (I'm keeping it very basic
for the sake of this example):

Shipments
User Shipment
1 Inbound
1 Inbound
1 Inbound
1 Inbound
2 Inbound
2 Outbound
2 Inbound
3 Inbound
3 Inbound
3 Inbound
3 Inbound
4 Outbound
4 Outbound
4 Outbound

I want to pull back all users that did not have any outbound
shipments. I know I can do it with an inner select:

select user
from users
where user not in
(
select user
from shipments
where shipment = 'Outbound'
)

This seems so simple but I don't know how I'd do it without hitting
the database twice. Any ideas?
Nov 14 '08 #1
3 3195
Not sure how much you simplified your scenario, but with the sample data
provided you can use this query to get users who have only Inbound
shipments:

SELECT [user]
FROM Shipments
GROUP BY [user]
HAVING MAX(shipment) = 'Inbound';

As alternative you can rewrite the query you had using NOT EXISTS:

SELECT [user]
FROM Shipments AS A
WHERE NOT EXISTS(SELECT *
FROM Shipments AS B
WHERE B.[user] = A.[user]
AND B.shipment = 'Outbound');

--
Plamen Ratchev
http://www.SQLStudio.com
Nov 14 '08 #2
(np****@gmail.c om) writes:
I want to pull back all users that did not have any outbound
shipments. I know I can do it with an inner select:

select user
from users
where user not in
(
select user
from shipments
where shipment = 'Outbound'
)

This seems so simple but I don't know how I'd do it without hitting
the database twice.
Who says that you hit it twice? Keep in mind that SQL is a declarative
language. You state your intent, the optimizer finds out the best way
do it. OK, so in practice it does matter quite a bit how your queries,
but there are also a lot of cases where the optimizer will implement
your query in a different way.

Which is the best way to express a query, is often difficult to tell
beforehand. When you have different ways to go, benchmarking is
about compulsory. But even then you need to be careful, because what
is true for 10000 rows and one distribution, may not be true for 10
million rows and another distribution.

--
Erland Sommarskog, SQL Server MVP, es****@sommarsk og.se

Links for SQL Server Books Online:
SQL 2008: http://msdn.microsoft.com/en-us/sqlserver/cc514207.aspx
SQL 2005: http://msdn.microsoft.com/en-us/sqlserver/bb895970.aspx
SQL 2000: http://www.microsoft.com/sql/prodinf...ons/books.mspx

Nov 14 '08 #3
Thank you guys for all your help. I will try different methods and
check the execution plans.
Nov 17 '08 #4

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

3
6411
by: Prem | last post by:
Hi, I am having many problems with inner join. my first problem is : 1) I want to know the precedance while evaluating query with multiple joins. eg. select Employees.FirstName, Employees.LastName, TerritoryID, Employees.EmployeeID, RegionID, ProductID from Employees
4
3991
by: Sri | last post by:
I am writing a download process in which i have a condition where i need to join four tables. Each table have lot of data say around 300000 recs. my question is when i am doing the joins on the columns is there any specific order i need to follow.
1
1230
by: gnog | last post by:
hello we have 3 tables bugs bugid | bugname custom_field_value bugid | fieldid | fieldvalue
0
4026
by: Alpenk | last post by:
I'm trying to update an empty field in a table using the update statment. The table has a number of joins and the update statement comes up with an error when I enter the main table to update. should i be including the joins here as well? I get the following error: Server: Msg 208, Level 16, State 1, Line 178 Invalid object name 'TD_EXTRACT'. Server: Msg 208, Level 16, State 1, Line 178 Invalid object name '#Neil.Mortgage'. The code im...
2
1614
by: gkellymail | last post by:
the following query works fine: select link.idx, link.x_table, link.x_id_a, link.x_id_z, a.strandid, b.strandid from link_detail, link, strand A, strand B where link_detail.x_table = 'enclosure' and link_detail.x_id = 3 and link.idx = link_detail.linkidx and A.strandid = link.x_id_a and B.strandid = link.x_id_z would someone please convert this to a more efficient query using inner
1
3105
by: imranpariyani | last post by:
Hi i have a severe performance problem with one of my views which has 6 to 8 joins .. any help will be appreciated.. the view is: CREATE OR REPLACE VIEW thsn.trade_view AS SELECT tra.tra_id, tra.per_id, tra.fir_id, tra.tra_dcn, tra.tra_startdate::date AS tra_startdate, tra.tra_enddate::date AS tra_enddate, tra.tra_highprice, tra.tra_lowprice, tra.tra_shares, tra.tra_marketvalue, tra.tra_commonsharesheld, tra.tra_directsharesheld,...
2
19718
by: narendra vuradi | last post by:
Hi I have a requirement where in i haev to convert the SQL from Oracle to the one which will run on the SQL server. in the Oracle Query i am doing multiple joins, between some 13 tables. and some of these joins are inner joins and some are Left outer joins. table1 inner joined with table 2 table2 inner join with table3 table2 inner join with table4 table2 left join with table5
9
11915
by: shapper | last post by:
Hello, I am used to SQL but I am starting to use LINQ. How can I create Left, Right and Inner joins in LINQ? How to distinguish the different joins? Here is a great SQL example: http://www.codinghorror.com/blog/archives/000976.html
6
1781
by: loffing4 | last post by:
I'm trying to write a query that selects the top five members of a forum based on how many total points they have. A member's total points are calculated as follows: (3 * # answers posted) + (10 * # questions posted) + (15 * # members recruited). The relevant parts of the tables are listed below: table members ( member_id int(10), ... recruiter_id int(10) /* id of member who recruited this member (0 if none) */ ) ...
0
8425
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
8845
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
8743
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
0
8622
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
7355
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
6177
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
4333
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
2
1973
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
2
1736
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.