Testing Queries
Testing Queries
The greatest challenge with complex queries is that even if you make a
mistake, you usually get results.
The problem is that the results are not the answer to the question you
wanted to ask.
The only way to ensure the results are correct is to thoroughly understand
SQL, to build your queries carefully, and to test your queries.
The first step is to break complex queries into smaller pieces, particularly
when the query involves subqueries.
You need to examine and test each subquery separately.
You can do the same thing with complex Boolean conditions.
Start with a simple condition,
check the results, and then add new conditions.
When the subqueries are correct, use cut-and-paste techniques to combine
them into one main query.
If necessary, save the initial queries as views, and use a completely new
query to combine the results from the views.
The third step is to create sample data to test the queries.
Find or create data that represents the different possible cases.
Optimize queries that will become part of an application and run multiple
times.
Most DBMSs have an optimizer that will suggest performance
improvements. You should also look for alternate ways to write the query
to find a faster approach.
Break questions into smaller pieces.
Test each query.
Check the SQL.
Look at the data.
Check computations.
Combine into subqueries.
Use the cut-and-paste features to reduce errors.
Check for correlated subqueries.
Test sample data.
Identify different cases.
Check final query and subqueries.
Verify calculations.
Test SELECT queries before executing UPDATE queries.
Optimize queries that run multiple times.
Run a query optimizer.
SELECT DISTINCT Animal.Category, Sale.CustomerID FROM Sale INNER
JOIN Animal ON Animal.SaleID = Sale.SaleID WHERE
(Animal.Category=N'Dog') AND Sale.CustomerID IN ( SELECT DISTINCT
Sale.CustomerID FROM Sale INNER JOIN (Merchandise INNER JOIN
SaleItem ON Merchandise.ItemID = SaleItem.ItemID) ON Sale.SaleID =
SaleItem.SaleID WHERE (Merchandise.Category=N'Cat')
List customers who adopted dogs and also bought cat products.
The query consists of four situations:
1. Customers adopted dogs and cat products on the same sale.
2. Customers adopted dogs and then cat products at a different time.
3. Customers adopted dogs and never bought cat products.
4. Customers never adopted dogs but did buy cat products.
The final step in building queries involves data manipulation queries (such as
UPDATE).
You should first create a SELECT query that retrieves the rows you plan to
change.
Examine and test the rows to make sure they are the ones you want to alter.
When you are satisfied that the query is correct, make sure you have a recent
backup of the database—or at least a recent copy of the tables you want to
change.
Now you can convert the SELECT query to an UPDATE or DELETE