views:

266

answers:

2

Hi everyone,

As an exercise (read:interview question) in index optimisation, I need a query which is slow on the standard AdventureWorks database in SQL2005. All the queries I've tried take about 1 second and I would prefer to have a query which takes multiple seconds so that it can be optimised effectively.

Can anyone here create such a query or give me pointers to how to create a slow query? I just can't seem to make my queries non-performant :)

+6  A: 

Here you have list of database tables with the most rows:

Tables - Rows count
Sales.SalesOrderDetail - 121317
Production.TransactionHistory - 113443
Production.TransactionHistoryArchive - 89253
Production.WorkOrder - 72591
Production.WorkOrderRouting - 67131
Sales.SalesOrderHeader - 31465
Sales.SalesOrderHeaderSalesReason - 27647
Person.Contact - 19972
Person.Address - 19614
Sales.CustomerAddress - 19220
Sales.Customer - 19185
Sales.ContactCreditCard - 19118
Sales.CreditCard - 19118
Sales.Individual - 18484
Sales.CurrencyRate - 13532

You can try different variations using that tables. For example this query:

SELECT * FROM Sales.SalesOrderDetail s
INNER JOIN Production.Product p ON s.ProductID = p.ProductID

runs for 9 seconds at my computer.

You can run this:

SELECT * FROM Production.TransactionHistory th
INNER JOIN Production.TransactionHistoryArchive tha ON th.Quantity = tha.Quantity

Inner join on unindexed tables. Very artificial example, but for now it takes over 2 minutes to roll on my machine. Now - over 20 minutes. Now - 1h 20 minutes.

Lukasz Lysik
even better, add a "WHERE ListPrice > 1000" or something, on an un-indexed column.
BradC
@Lukasz - the query runs for 9 seconds (3 on my machine) because it returns over 100000 rows, not because it's busy trying to scan tables. Both tables already have indexes on ProductID so I couldn't improve that much.
rein
@BradC - this is the correct approach (filtering by un-indexed column or better yet, joining by un-indexed column) but unfortunately I just can't get to a point where that gives me the bad performance I'm looking for.
rein
Check the last example I've added.
Lukasz Lysik
A: 

try usinga correlated subquery against one of those tables or a cursor.

HLGEM