Hello,
I have these two tables: Invoices and InvoiceLines, linked together by InvoiceId field.
Is there some Left Outer join just to check if there exist any InvoiceLines for the Invoices? (true or false);
something like If Exists(Select...)
For now I've tried (for a 2million record Invoice table and roughly 40million lines table):
1. Select i.InvoiceNumber,Case When l.InvoiceIs Is null Then 0 Else 1 End As HasLines From Invoices i Left Outer Join (Select InvoiceId From InvoiceLines Group By InvoiceId) l on i.InvoiceId=l.InvoiceId (the quickest 1'13")
2. Select i.InvoiceNumber,Case When l.InvoiceIs Is null Then 0 Else 1 End As HasLines From Invoices i Left Outer Join (Select Distinct InvoiceId From InvoiceLines) l on i.InvoiceId=l.InvoiceId (1'15")
3. Select i.InvoiceNumber,Case When l.InvoiceIs Is null Then 0 Else 1 End As HasLines From Invoices i Left Outer Join (Select InvoiceId From (Select InvoiceId,N=Row_Number() Over (Partition By InvoiceId Order By Id) FromInvoiceLines) l Where N=1) l on i.InvoiceId=l.InvoiceId (1:32")
4. Select i.InvoiceNumber,Case When l.InvoiceIs Is null Then 0 Else 1 End As HasLines From Invoices i Left Outer Join (Select InvoiceId From Invoice d Where Exists(Select InvoiceId From InvoiceLines dl Where dl.InvoiceId=d.InvoiceId)) l on i.InvoiceId=l.InvoiceId (1'20")
But I don't want to actually read something, just to 'touch' the table and see if at least one record exist.
Do you think there is another way?
Thank you, Daniel