I have a set of tables
dbo.Store_000
dbo.Store_001
....
dbo.Store_216
containing the sales of different stores, where relevant fields are
Username, ItemID, Description, CreatedDate, CountryID
I need to extract the latest 20 sales from all Stores and I wrote the following query:
select top 20 UserName, ItemID, Description, CreatedDate, CountryID
FROM (
SELECT UserName, ItemID, Description, CreatedDate, CountryID FROM dbo.Store_000
UNION ALL
SELECT UserName, ItemID, Description, CreatedDate, CountryID FROM dbo.Store_001
UNION ALL
SELECT UserName, ItemID, Description, CreatedDate, CountryID FROM dbo.Store_002
.....
...
UNION ALL
SELECT UserName, ItemID, Description, CreatedDate, CountryID FROM dbo.Store_216
) ii
order by ii.createdDate desc
currently tables contains some 200M records (all together)
therefore to reduce processing time I created the following index for each table:
CREATE NONCLUSTERED INDEX I2_Store000 ON dbo.Store_000
(UserName)
INCLUDE (itemId, Description, CreatedDate, CountryID)
WITH (
PAD_INDEX = OFF,
DROP_EXISTING = OFF,
STATISTICS_NORECOMPUTE = OFF,
SORT_IN_TEMPDB = OFF,
ONLINE = OFF,
ALLOW_ROW_LOCKS = ON,
ALLOW_PAGE_LOCKS = ON)
ON [PRIMARY]
but it still takes too much (some minutes on our machine)
can you suggest how to improve the query and or the index to reduce processing time?
should I create the index based on CreatedDate since that is the sorting field?
if it can help, HERE can find the MSSMS execution plan.
thanks