Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

alternatives to using IN clause

Tags:

sql

ssms-2014

I am running the below query:

SELECT 
    ReceiptVoucherId, 
    VoucherId, 
    ReceiptId,
    rvtransactionAmount, 
    AmountUsed, 
    TransactionTypeId
FROM 
    [Scratch].[dbo].[LoyaltyVoucherTransactionDetails]
WHERE       
    VoucherId IN 
    (2000723,
    2000738,
    2000774,
    2000873,
    2000888,
    2000924,
    2001023,
    2001038,
    2001074,
    2001173)

the aim being to extract the ReceiptVoucherId / VoucherId / ReceiptId / rvtransactionAmount / AmountUsed / TransactionTypeId data for the list of voucherId's that I have.

My problem here is that my list of VoucherID's is 187k long so an IN clause is not possible as it returns the error:

Internal error: An expression services limit has been reached

Can anyone advise on a alternative to doing it this way?

I am using SSMS 2014

like image 314
PIPRON79 Avatar asked Jul 04 '16 14:07

PIPRON79


People also ask

What can I use instead of in clause?

Using Joins Instead of IN or EXISTS An alternative for IN and EXISTS is an INNER JOIN, while a LEFT OUTER JOIN with a WHERE clause checking for NULL values can be used as an alternative for NOT IN and NOT EXISTS.

What can be used instead of or in SQL?

Often rewriting OR as UNION helps. You could tidy this up somewhat by encapsulating the join of c and b into a CTE and referencing that in both branches of the UNION instead of repeating it - or materialising into a temp table if that initial join is itself expensive. Save this answer.

How can avoid in clause in SQL Server?

Solution 1 The only exception to this is when the range is fixed: if it's always the same ID values in your IN clause, then you could possibly save them in a separate table, and use a JOIN to "glue" the query together.

What can I use instead of not in SQL?

If so, you should consider using a NOT EXISTS operator instead of NOT IN, or recast the statement as a left outer join.


2 Answers

Just create a table containing all this Vouchers (Hopefully you already have one) and then use IN() selecting from the table :

SELECT 
    ReceiptVoucherId, 
    VoucherId, 
    ReceiptId,
    rvtransactionAmount, 
    AmountUsed, 
    TransactionTypeId
FROM 
    [Scratch].[dbo].[LoyaltyVoucherTransactionDetails]
WHERE       
    VoucherId IN (SELECT VoucherId FROM VourchersTable)
like image 86
sagi Avatar answered Sep 26 '22 14:09

sagi


You can try the approach:

select from mytable where id in (select id from othertable)

or left join:

select from othertable left join mytable using id

not sure what has better performance, also second query could give you empty rows if it is not declared as foreign key.

fly-by-post, feel free to improve it.

like image 22
user6548053 Avatar answered Sep 26 '22 14:09

user6548053