Friday, March 30, 2012
Optimizing SQL Filtering - Conceptual question
table1:
====
field1: PK, indexed
field2: FK, indexed
field3: numeric field, non indexed
field4: date field, non indexed
I want to know if this SQL is slower than the second:
select ... from table
where field3 = value // non indexed field first
and field1 = value // indexed field last
select ... from table
where field1 = value // indexed field first
and field3 = value // non indexed field last
Which is faster? Does it matter which field is before? Or the server
organize the fields automatically?
Is the order of fields in the 'where' part important to the query execution
speed?
If I put indexed fields first in the list, the query is executing faster
than if I put an non indexed field first?
I'm using SQL Server 2000.
Thank you very much
Daniel E. Alvarez
IMS Soluciones Tecnolgicas S.A.
quilate@.kropol.com.ar
Daniel,
The order of fields in the WHERE clause should not affect the order that the
optimizer uses.
Are you seeing that behavior? (I was unclear from your text below.) I
would suggest rerunning your tests several times and take timings from each
test cycle.
Russell Fields
(For a very complex set of joins the optimizer must eventually stop
optimizing and execute. In a case like that, the order of the FROM and
WHERE clause MAY have the side-effect of changing where the optimizer
decides to move on.)
"Daniel Alvarez" <dalvarez@.flashmail.com> wrote in message
news:#NluJkTKEHA.1156@.TK2MSFTNGP09.phx.gbl...
> I expose a simple example of what I'm trying to figure it out:
> table1:
> ====
> field1: PK, indexed
> field2: FK, indexed
> field3: numeric field, non indexed
> field4: date field, non indexed
> I want to know if this SQL is slower than the second:
> select ... from table
> where field3 = value // non indexed field first
> and field1 = value // indexed field last
> select ... from table
> where field1 = value // indexed field first
> and field3 = value // non indexed field last
> Which is faster? Does it matter which field is before? Or the server
> organize the fields automatically?
> Is the order of fields in the 'where' part important to the query
execution
> speed?
> If I put indexed fields first in the list, the query is executing faster
> than if I put an non indexed field first?
> I'm using SQL Server 2000.
> Thank you very much
> --
> Daniel E. Alvarez
> IMS Soluciones Tecnolgicas S.A.
> quilate@.kropol.com.ar
>
sql
Optimizing SQL Filtering - Conceptual question
table1:
====
field1: PK, indexed
field2: FK, indexed
field3: numeric field, non indexed
field4: date field, non indexed
I want to know if this SQL is slower than the second:
select ... from table
where field3 = value // non indexed field first
and field1 = value // indexed field last
select ... from table
where field1 = value // indexed field first
and field3 = value // non indexed field last
Which is faster? Does it matter which field is before? Or the server
organize the fields automatically?
Is the order of fields in the 'where' part important to the query execution
speed?
If I put indexed fields first in the list, the query is executing faster
than if I put an non indexed field first?
I'm using SQL Server 2000.
Thank you very much
Daniel E. Alvarez
IMS Soluciones Tecnolgicas S.A.
quilate@.kropol.com.arDaniel,
The order of fields in the WHERE clause should not affect the order that the
optimizer uses.
Are you seeing that behavior? (I was unclear from your text below.) I
would suggest rerunning your tests several times and take timings from each
test cycle.
Russell Fields
(For a very complex set of joins the optimizer must eventually stop
optimizing and execute. In a case like that, the order of the FROM and
WHERE clause MAY have the side-effect of changing where the optimizer
decides to move on.)
"Daniel Alvarez" <dalvarez@.flashmail.com> wrote in message
news:#NluJkTKEHA.1156@.TK2MSFTNGP09.phx.gbl...
> I expose a simple example of what I'm trying to figure it out:
> table1:
> ====
> field1: PK, indexed
> field2: FK, indexed
> field3: numeric field, non indexed
> field4: date field, non indexed
> I want to know if this SQL is slower than the second:
> select ... from table
> where field3 = value // non indexed field first
> and field1 = value // indexed field last
> select ... from table
> where field1 = value // indexed field first
> and field3 = value // non indexed field last
> Which is faster? Does it matter which field is before? Or the server
> organize the fields automatically?
> Is the order of fields in the 'where' part important to the query
execution
> speed?
> If I put indexed fields first in the list, the query is executing faster
> than if I put an non indexed field first?
> I'm using SQL Server 2000.
> Thank you very much
> --
> Daniel E. Alvarez
> IMS Soluciones Tecnolgicas S.A.
> quilate@.kropol.com.ar
>
Optimizing SQL Filtering - Conceptual question
table1:
==== field1: PK, indexed
field2: FK, indexed
field3: numeric field, non indexed
field4: date field, non indexed
I want to know if this SQL is slower than the second:
select ... from table
where field3 = value // non indexed field first
and field1 = value // indexed field last
select ... from table
where field1 = value // indexed field first
and field3 = value // non indexed field last
Which is faster? Does it matter which field is before? Or the server
organize the fields automatically?
Is the order of fields in the 'where' part important to the query execution
speed?
If I put indexed fields first in the list, the query is executing faster
than if I put an non indexed field first?
I'm using SQL Server 2000.
Thank you very much
--
Daniel E. Alvarez
IMS Soluciones Tecnológicas S.A.
quilate@.kropol.com.arDaniel,
The order of fields in the WHERE clause should not affect the order that the
optimizer uses.
Are you seeing that behavior? (I was unclear from your text below.) I
would suggest rerunning your tests several times and take timings from each
test cycle.
Russell Fields
(For a very complex set of joins the optimizer must eventually stop
optimizing and execute. In a case like that, the order of the FROM and
WHERE clause MAY have the side-effect of changing where the optimizer
decides to move on.)
"Daniel Alvarez" <dalvarez@.flashmail.com> wrote in message
news:#NluJkTKEHA.1156@.TK2MSFTNGP09.phx.gbl...
> I expose a simple example of what I'm trying to figure it out:
> table1:
> ====> field1: PK, indexed
> field2: FK, indexed
> field3: numeric field, non indexed
> field4: date field, non indexed
> I want to know if this SQL is slower than the second:
> select ... from table
> where field3 = value // non indexed field first
> and field1 = value // indexed field last
> select ... from table
> where field1 = value // indexed field first
> and field3 = value // non indexed field last
> Which is faster? Does it matter which field is before? Or the server
> organize the fields automatically?
> Is the order of fields in the 'where' part important to the query
execution
> speed?
> If I put indexed fields first in the list, the query is executing faster
> than if I put an non indexed field first?
> I'm using SQL Server 2000.
> Thank you very much
> --
> Daniel E. Alvarez
> IMS Soluciones Tecnológicas S.A.
> quilate@.kropol.com.ar
>
Monday, March 26, 2012
Optimizer Logic Tracing Tool
what I need is a tool which gives details on the choice of an
execution plan by the SQL Server. For example, the cost for a hash
join might be 200 and 100 for a nested loop, and therefore a nested
loop is used. Same thing for the access paths for each table/view
involved. In Oracle, we turn on event 100053 to see this kind of info.
Thanx
Daniel"Daniel Roy" <danielroy10junk@.hotmail.com> wrote in message
news:3722db.0401160711.7b1d34b4@.posting.google.com ...
> Guys,
> what I need is a tool which gives details on the choice of an
> execution plan by the SQL Server. For example, the cost for a hash
> join might be 200 and 100 for a nested loop, and therefore a nested
> loop is used. Same thing for the access paths for each table/view
> involved. In Oracle, we turn on event 100053 to see this kind of info.
> Thanx
> Daniel
There's no real equivalent in MSSQL - you can see the plan that optimizer
selected, not the logic it used to arrive at that plan. Query Analyzer can
display the cost of each step in the plan, and how many rows were affected,
either after the query runs or before (by asking for an estimated plan).
This is more or less a graphical presentation of the SET SHOWPLAN_ALL ON
output.
Simon|||> There's no real equivalent in MSSQL - you can see the plan that optimizer
> selected, not the logic it used to arrive at that plan. Query Analyzer can
> display the cost of each step in the plan, and how many rows were affected,
> either after the query runs or before (by asking for an estimated plan).
> This is more or less a graphical presentation of the SET SHOWPLAN_ALL ON
> output.
Isn't there ANY other way to understand the optimizer's logic in
choosing a specific execution plan as opposed to another one?
Daniel
optimized indexing
I would like to consider optimized indexing on the table which really does
not exist in my database, but will serve as an example for creating indexes.
Suppose that there is a table with following fields:
- family name,
- first name,
- dateofbirth,
- street,
- home number,
- city
Suppose also that there is an searching engine that is querying our example
table with statistics by these parameters:
- family name and first name - 50%,
- family name only - 20%,
- first name only - 15%,
- family name and street - 15%
Is it Ok (because of the best querying) to create following indexes:
- IX1 (family name, first name),
- IX2 (first name)
- IX3 (family name, street)
or there are other options?
Best Regards from SinclairSinclair (Sinclair@.discussions.microsoft.com) writes:
> I would like to consider optimized indexing on the table which really
> does not exist in my database, but will serve as an example for creating
> indexes.
> Suppose that there is a table with following fields:
> - family name,
> - first name,
> - dateofbirth,
> - street,
> - home number,
> - city
> Suppose also that there is an searching engine that is querying our
> example table with statistics by these parameters:
> - family name and first name - 50%,
> - family name only - 20%,
> - first name only - 15%,
> - family name and street - 15%
> Is it Ok (because of the best querying) to create following indexes:
> - IX1 (family name, first name),
> - IX2 (first name)
> - IX3 (family name, street)
> or there are other options?
Well, the above is not bad, but it fails to take in account the question is
which index to make the clustered index.
Since family name is popular, that is my pick for the clustered index. This
results in:
ClusterIX - (family naee)
NC_IX1 - (first name)
NC_IX2 - (street)
You may be missing family name from the non-clustered indexes, but it is
not. The clustrered index works as row locator in the non-clustered indexes,
so all columns in the clustered index appears there as well. (It would not
be wrong to explicitly include family name in these indexes.)
> I apologize to ask again. Related to the example in previous question
> about optimized indexing, should there be changes in proposed indexes,
> if the field [family name] takes part in INNER JOIN with some other
> table (Foreign key)?
With knowing only this, it is difficult to say whether it would matter
at all. But if it does, it is likely to enfoce the idea that family
name should be the clustered index.
Erland Sommarskog, SQL Server MVP, esquel@.sommarskog.se
Books Online for SQL Server 2005 at
http://www.microsoft.com/technet/pr...oads/books.mspx
Books Online for SQL Server 2000 at
http://www.microsoft.com/sql/prodin...ions/books.mspx
Friday, March 23, 2012
optimize queries with unexpected results
This is one for the MVP’s. I am trying to optimize queries but I am findin
g
un-expected results. I am using sql 2000.
For example, I have read in several sites that referencing objects with
qualified owner names is faster. The truth is that I am experiencing all the
contrary. Am I doing something wrong in my test or this is just a rumour and
no objects should be qualified?
I am running both next queries in my own desktop machine, and clearing the
chache every time I run the query as per below scripts . As I understand tha
t
the workload in my machine might vary (not really doing nothing during the
test) I am taking at least 10 runs of each script and take the average
results.
I would expect better results for script 2 that for one (test show the
contrary), can anybody explain why? I am examining several counters, but
would be happy enough if just logical reads would show better results. With
this results … how can I face the developers and tell them this and other
supposed coding “advantages”, or shall I just forget about reality and t
amper
the results in a Mendel fashion :-) ?
Script1:
SET STATISTICS IO on
SET STATISTICS TIME on
--above to lines just run once in each window
DBCC DROPCLEANBUFFERS
dbcc freeproccache
SELECT TOP 1000 *
FROM Table1 , Table2
where Table1.Idfield= Table2.Idfield
Script2:
SET STATISTICS IO on
SET STATISTICS TIME on
--above to lines just run once in each window
DBCC DROPCLEANBUFFERS
dbcc freeproccache
SELECT TOP 1000 *
FROM dbo.Table1 , dbo.Table2
where dbo.Table1.Idfield= dbo.Table2.Idfield
Thanks in advance, your help is much appreciated,
TristanIn addition to the [procedure cache] which contains execution plans,
there is also the [buffer cache] which contains previously read data and
index pages. This can have an even greater impact on query duration,
especially if you are executing the same query back to back. Since this is a
local instance of SQL Server, you may want to stop / re-start the service
prior to each test.
http://msdn.microsoft.com/library/d...br />
1zu4.asp
Also, in Query Analyzer, choose the menu option Query.. Show Execution
Plan. After the query comples, hovering the mouse over each step will reveal
information like whether a index s
performed and the actual I/O and CPU cost. If (after completely clearing all
caches) one run has basically the same I./O cost as another run, then there
are probably other environmental factors that influenced the outcome.
Performance on a desktop PC will be more variable than on a production
server, becuase there are so many other background services and processes,
such as anti-virus, running.
"Tristan" <Tristan@.discussions.microsoft.com> wrote in message
news:1D180C57-9AFF-458D-9529-9560FB154B73@.microsoft.com...
> Hi,
> This is one for the MVP's. I am trying to optimize queries but I am
> finding
> un-expected results. I am using sql 2000.
> For example, I have read in several sites that referencing objects with
> qualified owner names is faster. The truth is that I am experiencing all
> the
> contrary. Am I doing something wrong in my test or this is just a rumour
> and
> no objects should be qualified?
> I am running both next queries in my own desktop machine, and clearing the
> chache every time I run the query as per below scripts . As I understand
> that
> the workload in my machine might vary (not really doing nothing during the
> test) I am taking at least 10 runs of each script and take the average
> results.
> I would expect better results for script 2 that for one (test show the
> contrary), can anybody explain why? I am examining several counters, but
> would be happy enough if just logical reads would show better results.
> With
> this results . how can I face the developers and tell them this and other
> supposed coding "advantages", or shall I just forget about reality and
> tamper
> the results in a Mendel fashion :-) ?
> Script1:
> SET STATISTICS IO on
> SET STATISTICS TIME on
> --above to lines just run once in each window
> DBCC DROPCLEANBUFFERS
> dbcc freeproccache
> SELECT TOP 1000 *
> FROM Table1 , Table2
> where Table1.Idfield= Table2.Idfield
> Script2:
> SET STATISTICS IO on
> SET STATISTICS TIME on
> --above to lines just run once in each window
> DBCC DROPCLEANBUFFERS
> dbcc freeproccache
> SELECT TOP 1000 *
> FROM dbo.Table1 , dbo.Table2
> where dbo.Table1.Idfield= dbo.Table2.Idfield
> Thanks in advance, your help is much appreciated,
> Tristan
>|||The first thing you should do is to look at the query plan for each of these
scenarios and see what the difference is..
Wayne Snyder MCDBA, SQL Server MVP
Mariner, Charlotte, NC
I support the Professional Association for SQL Server ( PASS) and it''s
community of SQL Professionals.
"Tristan" wrote:
> Hi,
> This is one for the MVP’s. I am trying to optimize queries but I am find
ing
> un-expected results. I am using sql 2000.
> For example, I have read in several sites that referencing objects with
> qualified owner names is faster. The truth is that I am experiencing all t
he
> contrary. Am I doing something wrong in my test or this is just a rumour a
nd
> no objects should be qualified?
> I am running both next queries in my own desktop machine, and clearing the
> chache every time I run the query as per below scripts . As I understand t
hat
> the workload in my machine might vary (not really doing nothing during the
> test) I am taking at least 10 runs of each script and take the average
> results.
> I would expect better results for script 2 that for one (test show the
> contrary), can anybody explain why? I am examining several counters, but
> would be happy enough if just logical reads would show better results. Wit
h
> this results … how can I face the developers and tell them this and othe
r
> supposed coding “advantages”, or shall I just forget about reality and
tamper
> the results in a Mendel fashion :-) ?
> Script1:
> SET STATISTICS IO on
> SET STATISTICS TIME on
> --above to lines just run once in each window
> DBCC DROPCLEANBUFFERS
> dbcc freeproccache
> SELECT TOP 1000 *
> FROM Table1 , Table2
> where Table1.Idfield= Table2.Idfield
> Script2:
> SET STATISTICS IO on
> SET STATISTICS TIME on
> --above to lines just run once in each window
> DBCC DROPCLEANBUFFERS
> dbcc freeproccache
> SELECT TOP 1000 *
> FROM dbo.Table1 , dbo.Table2
> where dbo.Table1.Idfield= dbo.Table2.Idfield
> Thanks in advance, your help is much appreciated,
> Tristan
>|||Hi JT / Wayne,
I was allready looking with execution plans plans and where the exactly the
same, statistics showed brutal differences, but the worst was with the logia
l
reads, it just didnt make sense a diference of 1000 between one method and
the other. As sometimes happends in this job guys, closed the window and
opened another one and the error disapeared.
Anyway, thanks a lot guys.
Hi JT, FYI from BOL "Use DBCC DROPCLEANBUFFERS to test queries with a cold
buffer cache without shutting down and restarting the server.", dont know if
there are any other methods to clear more buffer than the ones I ussed,
though u r right to advise not to test in PC, sorry but prod and UAT are
fried with users :-)
"JT" wrote:
> In addition to the [procedure cache] which contains execution plans,
> there is also the [buffer cache] which contains previously read data and
> index pages. This can have an even greater impact on query duration,
> especially if you are executing the same query back to back. Since this is
a
> local instance of SQL Server, you may want to stop / re-start the service
> prior to each test.
> http://msdn.microsoft.com/library/d... />
a_1zu4.asp
> Also, in Query Analyzer, choose the menu option Query.. Show Execution
> Plan. After the query comples, hovering the mouse over each step will reve
al
> information like whether a index s
> performed and the actual I/O and CPU cost. If (after completely clearing a
ll
> caches) one run has basically the same I./O cost as another run, then ther
e
> are probably other environmental factors that influenced the outcome.
> Performance on a desktop PC will be more variable than on a production
> server, becuase there are so many other background services and processes,
> such as anti-virus, running.
>
>
> "Tristan" <Tristan@.discussions.microsoft.com> wrote in message
> news:1D180C57-9AFF-458D-9529-9560FB154B73@.microsoft.com...
>
>|||There can be probably "wrong" index use problem, look ath te query analyzer,
which index is really used in
query and probably you must force the
select INDEX hint
Wayne Snyder wrote:
>The first thing you should do is to look at the query plan for each of thes
e
>scenarios and see what the difference is..
>
>[quoted text clipped - 45 lines]
Message posted via http://www.webservertalk.com|||Tristan,
The execution plans of the two queries should be the same. If they are
not, then that is a different issue.
If you use TOP 1000 and the join between Table1 and Table2 produces more
than 1000 rows, then the results can differ between runs. That is not a
good test situation.
The difference between a qualified and unqualified object is only
relevant in the query compilation phase. The potential performance
difference will not show up in the logical reads.
Gert-Jan
Tristan wrote:
> Hi,
> This is one for the MVP’s. I am trying to optimize queries but I am find
ing
> un-expected results. I am using sql 2000.
> For example, I have read in several sites that referencing objects with
> qualified owner names is faster. The truth is that I am experiencing all t
he
> contrary. Am I doing something wrong in my test or this is just a rumour a
nd
> no objects should be qualified?
> I am running both next queries in my own desktop machine, and clearing the
> chache every time I run the query as per below scripts . As I understand t
hat
> the workload in my machine might vary (not really doing nothing during the
> test) I am taking at least 10 runs of each script and take the average
> results.
> I would expect better results for script 2 that for one (test show the
> contrary), can anybody explain why? I am examining several counters, but
> would be happy enough if just logical reads would show better results. Wit
h
> this results … how can I face the developers and tell them this and othe
r
> supposed coding “advantages”, or shall I just forget about reality and
tamper
> the results in a Mendel fashion :-) ?
> Script1:
> SET STATISTICS IO on
> SET STATISTICS TIME on
> --above to lines just run once in each window
> DBCC DROPCLEANBUFFERS
> dbcc freeproccache
> SELECT TOP 1000 *
> FROM Table1 , Table2
> where Table1.Idfield= Table2.Idfield
> Script2:
> SET STATISTICS IO on
> SET STATISTICS TIME on
> --above to lines just run once in each window
> DBCC DROPCLEANBUFFERS
> dbcc freeproccache
> SELECT TOP 1000 *
> FROM dbo.Table1 , dbo.Table2
> where dbo.Table1.Idfield= dbo.Table2.Idfield
> Thanks in advance, your help is much appreciated,
> Tristan
Optimizator and indexes
server setting or index type...)
I'll give an example to clarify :
I have a table with fields
Customer_Code char(10) not null
Invoice_Numberintnot null
and an index on those fields IX_1.
there are about 2,000,000 records in the table and those two fields are
not unique, and I cant use clustered index because of the nature of the
table (need it for something else).
When I use query like :
Select * from CustInv where Customer_Code='ABC' and invoice_Number=2
depending on the ammount of data statistics computes, query is executed
using the IX_1 or IX_1 is ignored. The documentation says that using of
indexes is determened by the uniqueness of the data, but my tests show
that every usage of index is faster.
I can fool the optimizer when using query like
Select * from CustInv where Customer_Code='ABC' and invoice_Number>=2
and invoice_number<=2
but all that it does is extends the optimizer's tolerance (IX_1) is
ignored for some queries in that form also.
Because my database and indexes are dynamically created, I cannot use
hints for indexes, so if anyone knows a way to tell the database
something like : "If you have an index on where fields, use it ALWAYS",
the knowledge would be gratly appretiated! :)
Thanx in advance! Sorry for a longer post and maybe fuzzy explanation of
the problem...
IgorIgor,
If you create the tables (and indexes) dynamically, then it should be no
problem for you to name your indexes and constraints. And if you can
name your indexes/constraints, then you can use index hints.
BTW: There is no way to force the use of a particular index without
using hints. Such option would make no sense at all.
SQL-Server uses a cost based optimizer and will minimize I/O, it will
choose indexes that will minimize query execution times.
With a hot cache, an index hint can in some situations increase
performance. Note however that the index hint can become troublesome
when the amount of data grows (or unused space increases), or when the
cache size shrinks (because other processes need the server's memory).
If the query that you are actually using is more complex then the one
below, then please post it. There may be other options...
Hope this helps,
Gert-Jan
Igor wrote:
> Is there a way to force optimizer to use indexes without hints? (some
> server setting or index type...)
> I'll give an example to clarify :
> I have a table with fields
> Customer_Code char(10) not null
> Invoice_Number int not null
> and an index on those fields IX_1.
> there are about 2,000,000 records in the table and those two fields are
> not unique, and I cant use clustered index because of the nature of the
> table (need it for something else).
> When I use query like :
> Select * from CustInv where Customer_Code='ABC' and invoice_Number=2
> depending on the ammount of data statistics computes, query is executed
> using the IX_1 or IX_1 is ignored. The documentation says that using of
> indexes is determened by the uniqueness of the data, but my tests show
> that every usage of index is faster.
> I can fool the optimizer when using query like
> Select * from CustInv where Customer_Code='ABC' and invoice_Number>=2
> and invoice_number<=2
> but all that it does is extends the optimizer's tolerance (IX_1) is
> ignored for some queries in that form also.
> Because my database and indexes are dynamically created, I cannot use
> hints for indexes, so if anyone knows a way to tell the database
> something like : "If you have an index on where fields, use it ALWAYS",
> the knowledge would be gratly appretiated! :)
> Thanx in advance! Sorry for a longer post and maybe fuzzy explanation of
> the problem...
> Igor|||Igor (bija@.baja.com) writes:
> Because my database and indexes are dynamically created, I cannot use
> hints for indexes, so if anyone knows a way to tell the database
> something like : "If you have an index on where fields, use it ALWAYS",
> the knowledge would be gratly appretiated! :)
Believe me, you don't want that. Say that you have:
SELECT * FROM tbl WHERE nonclusteredindexedcol = @.value
If there is a good distribution of values in nonclusteredindexedcol,
the index will be good. But say that for 30% of the rows, the value
is the one the same. The cost for using the index rather than scanning
the table, will be considerably lower than using the index, since when
using the index the same page will be accessed more than once.
It is true, though, that the optimizer is overly conservative when it
comes to using non-clustered index, and in my opinion, the threshold
when it switches to table scan is a little low.
For a table where I know my data, I don't shudder for using an index
hint. But for a dynamically created database like yours, this sounds
risky.
A better alternative might be to build non-clustered indexes which
comprises all columns you need. If that is all columns of the table,
that is in practice a second clustered index on the table. It may
not be good for update speed though.
You could also investigate indexed views.
--
Erland Sommarskog, SQL Server MVP, esquel@.sommarskog.se
Books Online for SQL Server SP3 at
http://www.microsoft.com/sql/techin.../2000/books.asp|||Thanks for the reply.
Unfortunately, the query is as simple as I posted.
I didn't mean forcing usage of an PARTICULAR index, but telling the
optimizer if there is an index on the table with my where clause, use
it. :)
What I ment by dynamically creating indexes is that some tables index
themselves depending on the usage and data in them. The index names are
created dynamically and for me to choose one would mean scanning the
where clause and index names table...
And, if the only way to get the optimizer to actually optimize is to
turn it off, I can use DBF+NTX :))
btw, the irony is that the more complex the query, the smarter the
optimizer gets! :((
Gert-Jan Strik wrote:
> Igor,
> If you create the tables (and indexes) dynamically, then it should be no
> problem for you to name your indexes and constraints. And if you can
> name your indexes/constraints, then you can use index hints.
> BTW: There is no way to force the use of a particular index without
> using hints. Such option would make no sense at all.
> SQL-Server uses a cost based optimizer and will minimize I/O, it will
> choose indexes that will minimize query execution times.
> With a hot cache, an index hint can in some situations increase
> performance. Note however that the index hint can become troublesome
> when the amount of data grows (or unused space increases), or when the
> cache size shrinks (because other processes need the server's memory).
> If the query that you are actually using is more complex then the one
> below, then please post it. There may be other options...
> Hope this helps,
> Gert-Jan|||Thanks for the reply!
I agree with you on the threshold of the optimizer. But my problem
manifests itself like this :
My table is about 2,000,000 records, with an estimated growth of about
250,000 a month (don't think a giant index would be nice :))
When a result set will contain 3 records the query time is about 20secs
(stupid thing scans the table)
When a result set will contain 50,000 records (or so the optimizer
thinks), the query time is about 5 secs!
(uses index)
When I show this to my user, I get beat up by a stick! :))
Also, the server has only 1G of ram, so it cannot cache everything (if
it could, i wouldn't have noticed this) and is a dedicated server (only
SQL2000).
Not dealing with the inteligence (stupidity?) of the optimizer, is there
a way to increase the threshold for the table scan?
database is optimized every night and is currently about 10G!
Erland Sommarskog wrote:
> Igor (bija@.baja.com) writes:
>>Because my database and indexes are dynamically created, I cannot use
>>hints for indexes, so if anyone knows a way to tell the database
>>something like : "If you have an index on where fields, use it ALWAYS",
>>the knowledge would be gratly appretiated! :)
>
> Believe me, you don't want that. Say that you have:
> SELECT * FROM tbl WHERE nonclusteredindexedcol = @.value
> If there is a good distribution of values in nonclusteredindexedcol,
> the index will be good. But say that for 30% of the rows, the value
> is the one the same. The cost for using the index rather than scanning
> the table, will be considerably lower than using the index, since when
> using the index the same page will be accessed more than once.
> It is true, though, that the optimizer is overly conservative when it
> comes to using non-clustered index, and in my opinion, the threshold
> when it switches to table scan is a little low.
> For a table where I know my data, I don't shudder for using an index
> hint. But for a dynamically created database like yours, this sounds
> risky.
> A better alternative might be to build non-clustered indexes which
> comprises all columns you need. If that is all columns of the table,
> that is in practice a second clustered index on the table. It may
> not be good for update speed though.
> You could also investigate indexed views.|||Hi Igor
have you tried manually updating statistics more often?|||Tzvika Barenholz wrote:
> Hi Igor
> have you tried manually updating statistics more often?
Yes. Database has a plan to do it every night. but optimizer decides on
the basis of the statistics which is bad in my case... :(|||Igor,
If table CustInv has a nonclustered compound index on
(Customer_Code,Invoice_Number) and you run the query
Select * from CustInv where Customer_Code='ABC' and invoice_Number=2
and this query (0) will only return a few rows, then I would be *very*
surprised if the optimizer did not use the nonclustered index.
However, if what you are actually doing is this (1)
EXEC MySProc 'ABC', 2
or this (2)
Declare @.Customer_Code char(10)
Declare @.invoice_Number int
Set @.Customer_Code='ABC'
Set @.invoice_Number=2
Select * from CustInv where Customer_Code=@.Customer_Code and
invoice_Number=@.invoice_Number
then that is a different story.
Situation 1 is different because of parameter sniffing (check out Google
for more info). If you are using that, adding WITH RECOMPILE to the
stored procdure definition could be a solution.
In situation 2, it is not the statistics of the value pair ('ABC',2)
that is used, but the selectivity of the entire index, because the
variable values are not known compile time. The query optimizer will
then create a plan for the worst case scenario. If your data is evenly
distributed, then it could use the nonclustered index. However, if your
data distribution is skewed, and there is a combination with a very high
occurrence, then SQL-Server will probably choose a query plan with a
clustered index scan. Whatever query plan is chosen, it is used for all
different variable values.
Please let us know which type of query is actually causing the bad
performance: Type 0, 1 or 2.
Gert-Jan
Igor wrote:
> Thanks for the reply.
> Unfortunately, the query is as simple as I posted.
> I didn't mean forcing usage of an PARTICULAR index, but telling the
> optimizer if there is an index on the table with my where clause, use
> it. :)
> What I ment by dynamically creating indexes is that some tables index
> themselves depending on the usage and data in them. The index names are
> created dynamically and for me to choose one would mean scanning the
> where clause and index names table...
> And, if the only way to get the optimizer to actually optimize is to
> turn it off, I can use DBF+NTX :))
> btw, the irony is that the more complex the query, the smarter the
> optimizer gets! :((
> Gert-Jan Strik wrote:
> > Igor,
> > If you create the tables (and indexes) dynamically, then it should be no
> > problem for you to name your indexes and constraints. And if you can
> > name your indexes/constraints, then you can use index hints.
> > BTW: There is no way to force the use of a particular index without
> > using hints. Such option would make no sense at all.
> > SQL-Server uses a cost based optimizer and will minimize I/O, it will
> > choose indexes that will minimize query execution times.
> > With a hot cache, an index hint can in some situations increase
> > performance. Note however that the index hint can become troublesome
> > when the amount of data grows (or unused space increases), or when the
> > cache size shrinks (because other processes need the server's memory).
> > If the query that you are actually using is more complex then the one
> > below, then please post it. There may be other options...
> > Hope this helps,
> > Gert-Jan|||Gert-Jan,
Unfortunately, query (0) is the one with a problem! :)
But, i've tried q(2) and this works fine??
Also, I've tried this on a box with 4G of ram - works perfectly (not the
speed, the plan)... If only I could find a way to increase the threshold
for I/O performance... :)
Anyway, thanks a lot for a great post - i'll play around with it some
more, but my nerves are breaking... :)
Gert-Jan Strik wrote:
> Igor,
> If table CustInv has a nonclustered compound index on
> (Customer_Code,Invoice_Number) and you run the query
> Select * from CustInv where Customer_Code='ABC' and invoice_Number=2
> and this query (0) will only return a few rows, then I would be *very*
> surprised if the optimizer did not use the nonclustered index.
> However, if what you are actually doing is this (1)
> EXEC MySProc 'ABC', 2
> or this (2)
> Declare @.Customer_Code char(10)
> Declare @.invoice_Number int
> Set @.Customer_Code='ABC'
> Set @.invoice_Number=2
> Select * from CustInv where Customer_Code=@.Customer_Code and
> invoice_Number=@.invoice_Number
> then that is a different story.
> Situation 1 is different because of parameter sniffing (check out Google
> for more info). If you are using that, adding WITH RECOMPILE to the
> stored procdure definition could be a solution.
> In situation 2, it is not the statistics of the value pair ('ABC',2)
> that is used, but the selectivity of the entire index, because the
> variable values are not known compile time. The query optimizer will
> then create a plan for the worst case scenario. If your data is evenly
> distributed, then it could use the nonclustered index. However, if your
> data distribution is skewed, and there is a combination with a very high
> occurrence, then SQL-Server will probably choose a query plan with a
> clustered index scan. Whatever query plan is chosen, it is used for all
> different variable values.
> Please let us know which type of query is actually causing the bad
> performance: Type 0, 1 or 2.
> Gert-Jan
>
> Igor wrote:
>>Thanks for the reply.
>>
>>Unfortunately, the query is as simple as I posted.
>>I didn't mean forcing usage of an PARTICULAR index, but telling the
>>optimizer if there is an index on the table with my where clause, use
>>it. :)
>>What I ment by dynamically creating indexes is that some tables index
>>themselves depending on the usage and data in them. The index names are
>>created dynamically and for me to choose one would mean scanning the
>>where clause and index names table...
>>
>>And, if the only way to get the optimizer to actually optimize is to
>>turn it off, I can use DBF+NTX :))
>>
>>btw, the irony is that the more complex the query, the smarter the
>>optimizer gets! :((
>>
>>Gert-Jan Strik wrote:
>>
>>>Igor,
>>>
>>>If you create the tables (and indexes) dynamically, then it should be no
>>>problem for you to name your indexes and constraints. And if you can
>>>name your indexes/constraints, then you can use index hints.
>>>
>>>BTW: There is no way to force the use of a particular index without
>>>using hints. Such option would make no sense at all.
>>>
>>>SQL-Server uses a cost based optimizer and will minimize I/O, it will
>>>choose indexes that will minimize query execution times.
>>>
>>>With a hot cache, an index hint can in some situations increase
>>>performance. Note however that the index hint can become troublesome
>>>when the amount of data grows (or unused space increases), or when the
>>>cache size shrinks (because other processes need the server's memory).
>>>
>>>If the query that you are actually using is more complex then the one
>>>below, then please post it. There may be other options...
>>>
>>>Hope this helps,
>>>Gert-Jan|||Igor (bija@.baja.com) writes:
> Thanks for the reply!
> I agree with you on the threshold of the optimizer. But my problem
> manifests itself like this :
> My table is about 2,000,000 records, with an estimated growth of about
> 250,000 a month (don't think a giant index would be nice :))
> When a result set will contain 3 records the query time is about 20secs
> (stupid thing scans the table)
> When a result set will contain 50,000 records (or so the optimizer
> thinks), the query time is about 5 secs!
> (uses index)
> When I show this to my user, I get beat up by a stick! :))
Not seeing the table, its indexes and its plan, it's difficult to say
something useful.
But it is worth keeping in mind that stastistics are normally maintained
for single columns, if your query has two conditions of which each
value is fairly common, but the combination is not, the optimizer
may be confused. You can create two-column statistics, but I don't know
whether they actually have any practical importance.
Assuming that your query is dynamically generated, you could add an
index hint like:
WITH INDEX (2, 3, 4, ...)
where you simply include the index ids of the non-clustered indexes
of the table. You would have to query sysindexes to find them. (You
need to exclude statistics and hypothetical indexes.)
If that doesn't work out, you probably need to reconsider your
strategy with dynamic indexing.
--
Erland Sommarskog, SQL Server MVP, esquel@.sommarskog.se
Books Online for SQL Server SP3 at
http://www.microsoft.com/sql/techin.../2000/books.asp
Tuesday, March 20, 2012
Optimization
for performance.
Example 1:
Server: ServerProd
Database: DB1
Query: Select * from Table1
Example 2:
Server: ServerProd
Database: DB2
Query: Select * from DB1..Table1
Does anybody know?
AngieThere is no difference. See with the query plan.
"Angela Shinkle" <ashinkle@.aspenmed.org> wrote in message
news:OhdCXAXpDHA.2772@.TK2MSFTNGP10.phx.gbl...
> I was asked to find out if there is any difference between the two queries
> for performance.
> Example 1:
> Server: ServerProd
> Database: DB1
> Query: Select * from Table1
>
> Example 2:
> Server: ServerProd
> Database: DB2
> Query: Select * from DB1..Table1
>
> Does anybody know?
> Angie
>|||no comment on this, but if the user and owner are
different, it will help to specify the table owner
>--Original Message--
>I was asked to find out if there is any difference
between the two queries
>for performance.
>Example 1:
> Server: ServerProd
> Database: DB1
> Query: Select * from Table1
>
>Example 2:
> Server: ServerProd
> Database: DB2
> Query: Select * from
DB1..Table1
>
>Does anybody know?
>Angie
>
>.
>|||If anything I would think the DB1..Table1 would be slower, however,
specifying the ownername for your table stops SQL from having to search on
your username to see if you have a table name that, so select * from
dbo.table1 is slightly faster than select * from table1 as SQL would go out
and see if there were any tables named yourusername.table1 and if not, then
select dbo.table1
HTH
--
Ray Higdon MCSE, MCDBA, CCNA
--
"Angela Shinkle" <ashinkle@.aspenmed.org> wrote in message
news:OhdCXAXpDHA.2772@.TK2MSFTNGP10.phx.gbl...
> I was asked to find out if there is any difference between the two queries
> for performance.
> Example 1:
> Server: ServerProd
> Database: DB1
> Query: Select * from Table1
>
> Example 2:
> Server: ServerProd
> Database: DB2
> Query: Select * from DB1..Table1
>
> Does anybody know?
> Angie
>|||Yep, I did some tests a while ago.
dbo.tblname is the fastest.
Including database name is slightly slower, even if you already are in the
correct database.
--
Tibor Karaszi, SQL Server MVP
Archive at:
http://groups.google.com/groups?oi=djq&as_ugroup=microsoft.public.sqlserver
"Ray Higdon" <rayhigdon@.higdonconsulting.com> wrote in message
news:OTjHfnYpDHA.2500@.TK2MSFTNGP10.phx.gbl...
> If anything I would think the DB1..Table1 would be slower, however,
> specifying the ownername for your table stops SQL from having to search on
> your username to see if you have a table name that, so select * from
> dbo.table1 is slightly faster than select * from table1 as SQL would go
out
> and see if there were any tables named yourusername.table1 and if not,
then
> select dbo.table1
> HTH
> --
> Ray Higdon MCSE, MCDBA, CCNA
> --
> "Angela Shinkle" <ashinkle@.aspenmed.org> wrote in message
> news:OhdCXAXpDHA.2772@.TK2MSFTNGP10.phx.gbl...
> > I was asked to find out if there is any difference between the two
queries
> > for performance.
> >
> > Example 1:
> > Server: ServerProd
> > Database: DB1
> > Query: Select * from Table1
> >
> >
> > Example 2:
> > Server: ServerProd
> > Database: DB2
> > Query: Select * from DB1..Table1
> >
> >
> > Does anybody know?
> >
> > Angie
> >
> >
>
Monday, February 20, 2012
openxml rowset problem
I'm trying to get some xml data into sql server but i ran into this problem: openxml seems to repeat results ...
I simplified my example to this:
----------------
Declare @.rDoc int,
@.sDoc varchar(4000)
Set @.sDoc = '
<ROOT>
<Rider>aaa</Rider>
<Rider>bbb</Rider>
<Rider>ccc</Rider>
</ROOT>'
EXEC sp_xml_preparedocument @.rDoc OUTPUT, @.sDoc
SELECT *
FROM OPENXML (@.rDoc, 'ROOT/Rider', 1)
WITH (RiderName varchar(50) '../Rider')
------------------
it returns 3 records for the 'rider' elements, _but_ all the records contain the text 'aaa' :/
does anybody know the solution to this?
cheers,
alexIf you did the WITH statement below instead it would work - note also as a general practice you should avoid walking "up" the xml data structure (the '../Rider' construct) for performance reasons
Declare @.rDoc int,
@.sDoc varchar(4000)
Set @.sDoc = '
<ROOT>
<Rider>aaa</Rider>
<Rider>bbb</Rider>
<Rider>ccc</Rider>
</ROOT>'
EXEC sp_xml_preparedocument @.rDoc OUTPUT, @.sDoc
SELECT *
FROM OPENXML (@.rDoc, 'ROOT/Rider', 1)
WITH (RiderName varchar(50) '.')|||thanks alot! :)