Hi both Kevin and Rich, thank you both for the fast response. Between your videos and by Access 2019 bible i have two databases up and running, so thanks again. I never thought to use a sub query. If I use a small aggregate subqury within the outer query as the where clause? Will that return all the fields? Thanks again Paul from UK becoming a silver member
Kevin Yip
@Reply 3 years ago
You put the WHERE clause in the query that is more time-consuming to run -- because WHERE limits the number of records to be processed, thus improving performance.
For instance:
SELECT a.ProductID, a.ProductDesc, b.TotalCost FROM ProductsT AS a
INNER JOIN (
SELECT ProductID, Sum([ProductCost]) AS TotalCost
FROM ProductSalesT
GROUP BY ProductID
HAVING ProductID = "12345"
) AS b
ON a.ProductID = b.ProductID
is more efficient than:
SELECT a.ProductID, a.ProductDesc, b.TotalCost FROM ProductsT AS a
INNER JOIN (
SELECT ProductID, Sum([ProductCost]) AS TotalCost
FROM ProductSalesT
GROUP BY ProductID
) AS b
ON a.ProductID = b.ProductID
WHERE a.ProductID = "12345"
even though they (likely) will return the same result.
That's because in the former, the condition ProductID = "12345" is put inside instead of outside. The inside query is a summation query, which is more time-consuming to perform. Hence, putting a condition there will help the performance.
Btw, this above method uses "nested queries", which essentially let you run multiple queries with just one query. The performance hit is not very big if the number of records being processed is kept in check.
You can split them up into two queries, if you prefer. But the placement of WHERE should follow the same rule -- you put it in the query that potentially retrieves the most records.
Sorry, only students may add comments.
Click here for more
information on how you can set up an account.
If you are a Visitor, go ahead and post your reply as a
new comment, and we'll move it here for you
once it's approved. Be sure to use the same name and email address.
This thread is now CLOSED. If you wish to comment, start a NEW discussion in
Visitor Forum.