SQL Server Interview Question #186

What is SQL injection and how should it be prevented?

Security, Backup, Recovery, Administration & Real-World Scenarios Senior Advanced

Detailed Explanation

SQL injection occurs when untrusted input is incorporated into executable SQL syntax, allowing an attacker to alter the intended command.

The primary defense is parameterization: use EF Core parameters, ADO.NET SqlParameter, Dapper parameters, or parameterized stored procedures. Avoid concatenating user input into SQL strings. Dynamic identifiers require strict allow-list validation and safe quoting because table and column names cannot be ordinary value parameters.

Least-privilege database credentials provide an additional containment layer but do not replace parameterization.

Code Example

-- Parameterized ADO.NET-style SQL concept:
SELECT Id, Email
FROM dbo.Users
WHERE Email = @Email;