Most likely for requests with conditions
where (c.IINBIN = @IINBIN or @IINBIN = '') and (c.[address] = @address or @address = '')
and
where c.IINBIN = @IINBIN and c.[address] = @address
different plans are being made.
First of all, you should of course look at the semantics of the query and, perhaps, try to rewrite it somehow more optimally. If there is no place to move further in this direction, then you can try the following.
Try to rebuild the indexes and update the statistics (this should be done for each of the tables participating in the query):
alter index all on [TableName] rebuild GO update statistics [TableName] with fullscan GO
More relevant statistics can help build a more optimal plan, and freshly built unfragmented indices help it to be executed more quickly.
You can also try adding the recompile option.
select c.* from dbo.Deals d left join clients c on c.clients_id = d.clientsId where (c.IINBIN = @IINBIN or @IINBIN='') and (c.[address] = @address or @address = '') option (recompile)
This will force the query processor to re-compile the query each time, taking into account the actual values of the @address and @IINBIN . Recompilation takes time, so it is not always possible to get a win in this way.
Finally, you can split the request into two independent ones with the help of an if ... else :
if @IINBIN != '' and @address != '' select c.* from dbo.Deals d left join clients c on c.clients_id = d.clientsId where c.IINBIN = @IINBIN and c.[address] = @address else select c.* from dbo.Deals d left join clients c on c.clients_id = d.clientsId where (c.IINBIN = @IINBIN or @IINBIN = '') and (c.[address] = @address or @address = '')
This is a kind of compromise between a request with the recompile option and without it.
And, of course, you should have useful indexes on the tables for the query. If IINBIN is unique, then I would add an index.
create unique index IX_Clients_IINBIN on Clients (IINBIN) include (address)
if not unique
create index IX_Clients_1 on Clients (IINBIN, address)
(we put forward a more selective column).
For the case when the search goes only by address , you can also add your own index:
create index IX_Clients_2 on Clients (address)
In general, queries of this type (when columns can be filtered in various combinations.) Are not the easiest to optimize, especially if there are not 2 columns, but much more.
select cl.* from ...(cl=cpresumably), i.e. You choose customers, and predicates you have on the table of customers. What do you need in thedbo.Dealsrequest? - i-one