Is SQL IN bad for performance?

There are several considerations when writing a query using the IN operator that can have an affect on performance. First, IN clauses are generally internally rewritten by most databases to use the OR logical connective. So col IN (‘a’,’b’,’c’) is rewritten to: (COL = ‘a’) OR (COL = ‘b’) or (COL = ‘c’). The execution … Read more

How to Join to first row

SELECT Orders.OrderNumber, LineItems.Quantity, LineItems.Description FROM Orders JOIN LineItems ON LineItems.LineItemGUID = ( SELECT TOP 1 LineItemGUID FROM LineItems WHERE OrderID = Orders.OrderID ) In SQL Server 2005 and above, you could just replace INNER JOIN with CROSS APPLY: SELECT Orders.OrderNumber, LineItems2.Quantity, LineItems2.Description FROM Orders CROSS APPLY ( SELECT TOP 1 LineItems.Quantity, LineItems.Description FROM LineItems WHERE … Read more

Can I protect against SQL injection by escaping single-quote and surrounding user input with single-quotes?

First of all, it’s just bad practice. Input validation is always necessary, but it’s also always iffy. Worse yet, blacklist validation is always problematic, it’s much better to explicitly and strictly define what values/formats you accept. Admittedly, this is not always possible – but to some extent it must always be done. Some research papers … Read more