Reason To Use Optimizer Hints

Aug 5, 1999

While investigating performance problems within an application recently I carried out some tests using SET SHOWPLAN ON.

I had a query like this within a stored procedure:

SELECT MAX(X) FROM Y WHERE Z LIKE @MYVAR

Where @MYVAR was passed in. I discovered that SQL Server did a Table Scan even when Z had an index on it. A problem with 200,000 rows!

If I said

SELECT MAX(X) FROM Y WHERE Z LIKE 'HELLO%'

(i.e., used a constant instead of a variable) SQL Server did use the index correctly and did not do a table scan.

I got around this by rewriting my statement:

SELECT MAX(X) FROM Y (INDEX=MYINDEX) WHERE Z LIKE @MYVAR

in other words by manually specifying the index I had created on the Z column.

Hope this helps someone.

View 2 Replies


ADVERTISEMENT

Hints ?

Jun 16, 2004

Is there anything equivalent available in SQL Server for Oracle HINTS ?

eg : Oracle query

select /* + INdex(sno index1) */ sno from test_table

Thanks,
Sam

View 2 Replies View Related

Hints

Jul 23, 2005

I am kind of confused about the way SQL Server 2000 handles the hintsthat users supply with their SQL statements.[color=blue]>From BOL, it seems that one can specify them with "WITH (...)" clauses[/color]in SQL statements known as table hints. Sometimes, multiple uses ofthis form in a statement is OK. Then there is the OPTION clause forspecifying statement hints. However, the documentation on OPTIONsection discourages their use.Being relatively new to SQL Server and still learning about it, what isthe general practice? Use hints or not? And if so, how (through WITHor OPTION clauses)?Cheers!

View 5 Replies View Related

Query Hints

Sep 12, 2005

My experience with query hints are that they are just that, a hint. What I don't understand is when does SQL decide to ignore your hint?
 

View 5 Replies View Related

Index Hints

May 15, 2001

I am running SQL7 SP2 and and noticing table the query processor table scans when I ussue a between 'date1' and 'date2' instead of using the datetime index. If I put in the index hint (index = ix_datetimeXXXX) the query runs fine. My question is does this index hint restict the use of other indexes in the query and secondly how can I specify multiple index hints? Thanks in advance.

View 1 Replies View Related

Query Hints

Sep 29, 2003

Please advise.

Whilst running a query I recieved the error below.
Cannot create a worktable row larger than allowable maximum. Resubmit your query with the ROBUST PLAN hint.

What is ROBUST PLAN hint?.

Help Appreciated.

View 6 Replies View Related

Locking Hints

May 1, 2007

Hi

My VB.Net (with SQL Server backend) application currently allows more than one user to look at a particular record at the same time. This is not a problem unless both those users also try to update that record as well. One user's changes then overwrite the other's.

I've been reading up on locking hints but my database knowledge is a little scant and I'm also rather dense and need things spelling out for me!! So I have a few questions that I hope someone can help with:

If I add an updlock to my update SQL statement, this would allow both users to view the record but would only allow one user's changes through. Is that correct?

For the other user, would SQL Server return an error message that I can use to tell the user that their update has not worked?

Would I have to get my VB.NET application to re-get the record information so that the user who's update failed can see the changes made by the other user and reapply their own changes?

Does the updlock become unlocked once the record is updated or do I need to specifically unlock it somehow?

Thanks!

View 20 Replies View Related

BUG With Join Hints

Apr 20, 2007

I am having problems with doing what seams to be a very easy query. For some reason the SQL Server is trying to do nested loops instead of hash join. I tried to force the use of the hash join using the join hint.





Query 1


select *
from DIM_DATE DD
inner hash join (
select A.student_key,
CONVERT(int, CONVERT(varchar, COALESCE (A.date_withdrawn, getdate()), 112)) AS date_withdrawn_current
FROM FACT_STUDENT AS A
) SSE on DD.date_key= date_withdrawn_current
This query gives an error:

Msg 8622, Level 16, State 1, Line 1
Query processor could not produce a query plan because of the hints defined in this query. Resubmit the query without specifying any hints and without using SET FORCEPLAN

Second query is not really what I want but it illustrate that it works fine when getdate() is not used.



Query 2


select *
from DIM_DATE DD
inner hash join (
select A.student_key,
CONVERT(int, CONVERT(varchar, COALESCE (A.date_withdrawn, A.date_enrolled), 112)) AS date_withdrawn_current
FROM FACT_STUDENT AS A
) SSE on DD.date_key= date_withdrawn_current
Is there some problem with using function getdate() ? It works fine in SQL Server 2000

This problem occurs on the SQL Server 2005 SP2 ( 9.00.3050.00 (X64) )
and (9.00.2050)

View 3 Replies View Related

Optimizer

May 7, 2008

Hello, first of all thanks to share greats posts.

I try do some tests and I get one doubt, why the optimizer don€™t make a constant scan in normal tables, for instance:




Code Snippet
--drop table #tmp
create table #tmp (id Int Identity(1,1) Primary key, name VarChar(250))
go
insert into #tmp(name) values(NEWID())
insert into #tmp(name) values(NEWID())
go
set statistics profile on
go
-- Execution plan create a Constant Scan
select * from #tmp
where id = 1 and id = 5
go
set statistics profile off

GO

--drop table tmp
create table tmp (id Int Identity(1,1) Primary key, name VarChar(250))
go
insert into tmp(name) values(NEWID())
insert into tmp(name) values(NEWID())

go
set statistics profile on
-- Why execution plan does not create a Constant Scan for this case?
select * from tmp
where id = 1 and id = 5
go
set statistics profile off





Thanks

View 4 Replies View Related

Confused About Using Lock Hints?

Mar 19, 2006

I noticed that the online books say the following:
Note  The SQL Server query optimizer automatically makes the correct determination. It is recommended that table-level locking hints be used to change the default locking behavior only when necessary.
Also, at another place in online books, it says:
The table hints are ignored if the table is not accessed by the query plan.
From the above, it seems that using locking hints is not going to guarantee that SQL Server will follow them. Is this true?

View 24 Replies View Related

JOIN Hints: Why SQL Works As Follows?

Sep 9, 1998

Hi,

Why SQL server dose work as follows when I dose not provide any join hints?
It looks like HASH join is the best plan, but SQL dose not. What kind of
JOIN method is used by SQL optimizer?

Thanks in advance,
Wonhyuk William Chung
wonhyukc@usa.net
MCSE/ MCT



-----------
use northwind
go
select orderid, CompanyName --productname,
from orders o inner join customers c on o.customerID = c.CustomerID
/*
Table `Orders`. Scan count 91, logical reads 184, physical reads 0,
read-ahead reads 0.
Table `Customers`. Scan count 1, logical reads 1, physical reads 0,
read-ahead reads 0.
.0553
*/

select orderid, CompanyName --productname,
from orders o inner hash join customers c on o.customerID = c.CustomerID
/*
hash
Table `Customers`. Scan count 1, logical reads 1, physical reads 0,
read-ahead reads 0.
Table `Orders`. Scan count 1, logical reads 4, physical reads 0, read-ahead
reads 0.
.115
*/

select orderid, CompanyName --productname,
from orders o inner merge join customers c on o.customerID = c.CustomerID
/*
merge
Table `Customers`. Scan count 1, logical reads 4, physical reads 1,
read-ahead reads 3.
Table `Orders`. Scan count 1, logical reads 4, physical reads 0, read-ahead
reads 0.
.115
*/

select orderid, CompanyName --productname,
from orders o inner loop join customers c on o.customerID = c.CustomerID
/*
loop
Table `Customers`. Scan count 830, logical reads 1681, physical reads 0,
read-ahead reads 0.
Table `Orders`. Scan count 1, logical reads 5, physical reads 0, read-ahead
reads 0.
.116
*/

View 1 Replies View Related

Multiple Optimization Hints

Sep 3, 1999

I need to use two hints (INDEX=indexname) and (NOLOCK).
I've tried
(INDEX=indexname),(NOLOCK)
(INDEX=indexname,NOLOCK)
(INDEX=indexname)(NOLOCK)

and nothing works.

Thanks

View 1 Replies View Related

Subquery Woes; Hints ?

Feb 9, 2008

hi all,
I'm trying to run queries on relatively small tables (a few hundred thousand rows) with subqueries of counts per primary key columns as such:

(ColA in tableA is the primary key)

select * from tableA p
where exists (select 1 from ( select ColA, count(1) cnt
from TableA
group by ColA
having count(1)>1 ) t
where t.ColA= p.ColA)
order by some_col

my problem is that sqlserver 2005 sp5 does not materialize the internal subquery properly, or execute it beforehand and it gets confused as heck and pegs the CPUs at 100% forever.

What hints can I use to solve this issue?
I've tried to use ..... "with ...." to prepare/materialize the table upfront, no luck, one version of statement pegged one cpu at 100%, while the other statement pegged ALL cpu's at 100% -- don't remember which.

My only solution right now was to create these subqueries as PHYSICAL tables -- and this would solve the problem but that would entail creating a lot of un-necessary objects.

thanks much for any feedback!!
Cos

View 5 Replies View Related

Query Optimizer

Jul 12, 2001

Hello,

I have a SQL command which I run on two separate servers. Both servers and configured and built the same. On server 1 it takes mere seconds, but on server 2 it takes over 5 minutes.

I have checked the execution plan on both servers and they are completely different. I ran UPDATE STATISTICS WITH FULLSCAN on both servers, but the execution plans were still different.

My question is why are the execution plans so different and how do I get them to execute with the same plan.

Thanks,
Chris.

View 1 Replies View Related

Strange Optimizer

Jul 20, 2005

I tried this:use northwindgoSELECT OrderDateFROM Orders WHERE OrderDate > '19950101'see the query plan? okSELECT OrderDate, EmployeeIdFROM Orders WHERE OrderDate > '19950101'see the query plan? what appened?the only way to make an index seek instead of an index scan is toforce theindex usage ( with(index=orderdate) ), but I don't like this solutionalso try this:SELECT *FROM Orders WHERE employeeId > 9andSELECT *FROM Orders WHERE employeeId > 8Can someone explain why this appens? and how can I overturn theperformance loss problem (well not in orders table, but in my tablethere are 300K records and making a scan to retrieve 50 records is notexactly what I want)thanks to all

View 2 Replies View Related

Optimizer Not Working?

Oct 31, 2007

Hi,

The product uses a simple stored procedure. The query times out when there are five million records in the table. It looks like below:


DECLARE


@CreatedStatus int,

@PendingStatus int;

SELECT


@CreatedStatus = [LV].[ufGetCode]('SaleStatus', 'Created'), -- which returns 1001

@PendingStatus = [LV].[ufGetCode]('SaleStatus', 'Pending'); -- which returns 1002


SELECT *

FROM LV.Detail WITH (READPAST)

WHERE Status = @CreatedStatus OR


Status = @PendingStatus;


Status columne is non-clustered index. The query takes more than 30 seconds. But when i use the query below:

SELECT * FROM LV.Detail WITH (READPAST) WHERE Status = 1001 or Status = 1002
The query is done very fast. No time out.


Anybody knows what makes difference? I am using SQL 2005.

View 3 Replies View Related

What Is An Optimizer In MS SQL Server ?

Mar 12, 2008



What does mean by Optimizer in MS SQL ? What is it ?
How do you use it ? what are the benifits of use it ?

View 4 Replies View Related

Traceflag To Ignore Index Hints

Jul 23, 2001

Hello.

There is a trace flag that tells SQL Server to ignore index hinting in incoming queries. I'm having a Monday morning problem and I can't remember the trace number nor find it in my notes. Can anyone else come up with it?

Thanks in advance,
-darin

View 1 Replies View Related

Lots Of Txt Files Has To Be Loaded (hints??)

Aug 18, 2006

have a dts package that does txt -> sql server.
i have 200 txt files with the same exact format.

just want to know if i can write a SP passing a parameter that loads this txt files. because i dont wanna create 200 packages or 200 sources to load 200 txt files.


say:
exec SP_loadTXT txt1

or should i use bulk insert?

any approaches are fine. any suggestions are fine too.

View 14 Replies View Related

SQL Seems To Ignore UPDLOCK && ROWLOCK Hints

Dec 3, 2007



I've got a SELECT WITH (UPDLOCK, ROWLOCK) WHERE followed by an UPDATE WHERE statement. The results of the SELECT statement are deserialized in C# and updates are made to the deserialized object. Then the object is serialized back into the table with the UPDATE statement. I've got this code running within a transaction scope with the ReadCommited isolation level.

My service receives requests to update data and the requests can come in on different threads. What I'm seeing, is that once in a while, the log messages from my application indicate that two different threads are able to issue the above SELECT statement and both are receiving results. This is a problem since the thread that issues the last UPDATE will overwrite the changes made by the first. Each thread has its own connection and transaction scope.

I've researched all over the place and have tried a few different things, but all things point to the fact that query hints are just hints and that SQL may or may not pay attention to them. If that's the case, how am I suppose to perform a SELECT with the intention of updating so that no one else can do the same? I haven't tried table level locking, but I'd really like to avoid that if possible.

-Mike

View 4 Replies View Related

Sql Server Query Optimizer

Feb 7, 2008

Hi,
   Can some one please send me the Sql Server 2005 QUERY OPTIMIZER artilce links?
Thanks

View 1 Replies View Related

Sql 2000 Query Optimizer?

Apr 22, 2004

I'm looking for an in depth book, article, faq, whatever, regarding the query optimizer...

I've read the books online pretty thoroughly and have been sql coding for a number of years. The system I work on relies heavily on real time access to data and the number crunching procedures we use are a critical part of the design. For the most part, sometimes through trial and error, I have been able to find ways to achieve the performance we need, but I'm often surprised by the methods that prove most effective.

For example, I have cases where I can only get the performance I'm looking for using table functions, and other cases where indexed temporary tables are the only way. I have statements that run fast as a select statement, but when converted to an update statement limp along, forcing me to resort to cursors, temp tables, or table hints with varying degrees of success.

I'm wondering if anyone has come across material that takes an in depth look at the various technologies available and how to tweek queries. I want to get away from hours of testing and hacking.

Thanks for reading. All replies are appreciated.

View 3 Replies View Related

Reading Query Optimizer

Jul 6, 1999

I am running a query showplan on a query. Can someone tell me how
to read what I am seeing? Or where I can get this information.

Thanks in advance,
Dianne

View 2 Replies View Related

Query Optimizer For Sql 2005

Feb 5, 2008

One quick question.

Is query optimizer a tool in sql that optimizes your queries? If so how do you use it?

Thanks

View 1 Replies View Related

MS SQL 2005: Where Clause And Optimizer

Feb 1, 2007

Way back when, and at least in version 7 IIRC, the query optimizer gaveup when the where clause in a statement contained more than 4 searchconditions.Does anyone know if such a limitation still exist in MS SQL 2005? TheBOL seems to be silent on the issue.Boa

View 2 Replies View Related

Weird Optimizer Choice

Jul 20, 2005

I'm very puzzled by the choice of NC index being made by the optimizerin this example. I don't actually think it should use an NC index atall.I have:Table: CustomerStatus_TSingle data page19 recordsClustered Index on CustomerStatusID:CREATE TABLE [CustomerStatus_T] ([CustomerStatusID] [int] NOT NULL ,[Name] [varchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,[Description] [varchar] (200) COLLATE SQL_Latin1_General_CP1_CI_ASNULL ,[Code] [varchar] (30) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,[CodeAlt] [varchar] (30) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,[Ordinal] [int] NULL ,[Default] [int] NULL ,[Display] [bit] NOT NULL ,[StatusType] [varchar] (1) COLLATE SQL_Latin1_General_CP1_CI_AS NULL,[DateCreated] [smalldatetime] NULL ,[DateUpdated] [smalldatetime] NULL ,[DateArchived] [smalldatetime] NULL ,CONSTRAINT [PK_ROMS_CustomerStatus] PRIMARY KEY CLUSTERED([CustomerStatusID]) ON [PRIMARY]) ON [PRIMARY]If I run the following query, it does exactly what I expect and scansthe clustered index:SELECT customerStatusID, [Name] FROM CustomerStatus_TWHERE dateArchived IS NULLAND Display = 1AND StatusType = 'Q‘and gives the following QEP and IO statistics:|--Clustered Index Scan(OBJECT:([Reach_Roms].[dbo].[CustomerStatus_T].[PK_ROMS_CustomerStatus]),WHERE:(([CustomerStatus_T].[DateArchived]=NULL AND[CustomerStatus_T].[StatusType]='Q') ANDConvert([CustomerStatus_T].[Display])=1))Table 'CustomerStatus_T'. Scan count 1, logical reads 2, physicalreads 0,read-ahead reads 0.If I now put a NC index on the statustype column:create index ix_nci_statustype on customerstatus_t(statustype)the query plan changes to:SELECT customerStatusID, [Name] FROM CustomerStatus_TWHERE dateArchived IS NULLAND Display = 1AND StatusType = 'Q‘|--Filter(WHERE:([CustomerStatus_T].[DateArchived]=NULL ANDConvert([CustomerStatus_T].[Display])=1))|--Bookmark Lookup(BOOKMARK:([Bmk1000]),OBJECT:([Reach_Roms].[dbo].[CustomerStatus_T]))|--IndexSeek(OBJECT:([Reach_Roms].[dbo].[CustomerStatus_T].[ix_nci_statustype]),S EEK:([CustomerStatus_T].[StatusType]='Q') ORDEREDFORWARD)Table 'CustomerStatus_T'. Scan count 1, logical reads 7,physical reads 0, read-ahead reads 0.For some bizarre reason, the optimizer thinks that a NC index lookupon a single-page table, which ultimately costs 7 IOs, is cheaper thana table (or Clustered Index) scan of a single page. Why? Theshowplan cost also shows that it expects the NC index to be cheaper(which is presumably why it goes and uses it), but even after runningUPDATE STATISTICS on the table it still chooses the same idiotic queryplan.Any thoughts, or has anyone seen similar behaviour before, and cananyone please explain it to me?p.s. I don't actually WANT to put a NC index on this table, but Inoticed the behaviour by accident which is why I'm asking the question:-)

View 3 Replies View Related

Join Filter Causes Conflicting Locking Hints

Jul 14, 2006

Hi,

Using Merge replication, I have a table that is filtered using the HOST_NAME() function. The filter also makes use of a function (as the HOST_NAME() is overriden to return some complex data).

Everything replicates and filters just fine. but when I add a join filter on a different table (the join filter is a simple foreign key join) I get the following error when the snapshot agent is run:



Message: Conflicting locking hints are specified for table "fn_GetIDList". This may be caused by a conflicting hint specified for a view.
Command Text: sp_MSsetup_partition_groups
Parameters: @publication = test1



fn_GetIDList is the function used in the original filter.

Thanks for any help



Graham

View 6 Replies View Related

Table And Query Hints Not Working In SSCE 3.1 ?

Aug 23, 2007

I am trying to use hints and they don't seem to be working.
Something like:

select * from TABLE_NAME with (tablock,xlock)

fails.

Documentation clearly states that this is supported (TABLOCK, NOLOCK, XLOCK, etc.), so I must be missing something simple.

Please let me know how do I use Hints in SQL Server 2005 Compact.
Thanks.


PS.
I am using C#. It doesn't work in my code when I use

SqlCeDataReader rs = cmd.ExecuteReader();

And it doesn't work from inside the VS 2005 "query tool" or whatever it is called, when you do "Connect to Database" and so on.

View 1 Replies View Related

Using Lock Hints In Query In An OLE DB Command Component

Dec 3, 2007

Do you know of a way, in the OLE DB Command (Executing a sql command for each record), to specify a lock hint?

Example: in my component, I want to update a table but I want to specify a ROWLOCK or UPDLOCK hint.

When I try using this sql statement in the 'SqlCommand' property:

UPDATE DIM_Accounts WITH (UPDLOCK)

SET COL1 = ''

SSIS gives a syntax error.

Do you know any workarounds?

Thanks!

View 7 Replies View Related

Standard Packages - Where To Store? Hints Needed

Jul 25, 2006

Hi,

I would like to implement a kind of standard packages which can be used in all other processes and will be started using the variables.

But I do not know where to store these kind of packages in "best practise", because we

- would like to use them in Dev and in "Real" also without having to change something in the other processes

- we are storing the packages in the folders of the package store

and as far as I understood I would have to share the package store to all developers though that they would be able to do this?

Then I would better choose another folder with defined access rights I think...

Or would it be better to spend some time in developing a custom component?
But this component would work with recordsets rather than the standard data flow elemtents and therefor I would expect a leak of performance...
Or is it possible to do "trasnformation" from a packae to a custom component?

Thanks in advice!

cheers,
Markus

View 2 Replies View Related

Does Using Isnull() Prevent The Optimizer From Using The Index For That Col.?

Apr 3, 2001

Hi all,
This table,

create table test (
t1 int,
t2 char(4) )

has about a few hundred rows. I have created a nonclustered index on column t1.

When I execute the following query, the query execution plan shows that the optimizer performs an index seek using the index on col. t1.

select * from test where t1 = 4

But, when I run the following query, using isnull(), the optimizer always performs a table scan.

select * from test where isnull(t1, 0) = 4

Could someone please explain why?

Thanks in advance,
Praveena

View 1 Replies View Related

SQL 2012 :: How To Determine When A Statistic Was Last Used By The Optimizer

Aug 25, 2015

Is there a DMV or similar in SQL 2012, or SQL 2008, that shows when a statistic was last used by the optimizer? I would like to cleanup some of the auto-generated stats, assuming it's possible to do so. In particular I'm looking to drop those statistics that were created by one-off queries, data loads, etc, and are now doing nothing but adding to the execution time of Update Statistics jobs.

View 6 Replies View Related

Why Optimizer Is Not Smart? Is Dynamic SQL My Only Option...

Feb 8, 2007

declare @ContactId as integerset @ContactId = 5select *from Person.Contactwhere ContactId = @ContactIdOR @ContactId = -1If you run this in SQL 2005 on the AdventureWorks database,why the logical reads is 561Table 'Contact'. Scan count 1, logical reads 56and not 2 when you run without the second OR condition:declare @ContactId as integerset @ContactId = 5select *from Person.Contactwhere ContactId = @ContactIdHow can i use the same SP and either get one record returnedby passing the ID of the field, or pass a dummy parameter like-1 in order to get ALL the records returned.In this case even when i pass a parameter like ContactID = 5there is still a table scan (clustered index scan in this case)happening for the other OR condition.There's no method to tell SQL to start checking the first conditionwhether or not it is true then if it is false then check the second ORconditon. On the same topic does this mean all OR conditions areALWAYS verified regardless if one of them has already been determinedto be True?Thank you

View 2 Replies View Related







Copyrights 2005-15 www.BigResource.com, All rights reserved