Sobes.tech
Junior — Middle

How can conditional data filtering be implemented when executing SQL queries?

sobes.tech AI

Answer from AI

To implement conditional data filtering in SQL queries, you can use dynamic query formation considering conditions that may be set or omitted at runtime.

In C#, this is often done using:

  • String concatenation with condition checks (not recommended due to SQL injection risk).
  • Using parameterized queries with conditional parameters.
  • Using ORM, such as Entity Framework, where you can build queries with LINQ, adding conditions as needed.

Example with LINQ:

var query = context.Users.AsQueryable();

if (!string.IsNullOrEmpty(nameFilter)) {
    query = query.Where(u => u.Name.Contains(nameFilter));
}

if (ageFilter.HasValue) {
    query = query.Where(u => u.Age == ageFilter.Value);
}

var result = query.ToList();

This approach allows flexible addition of filters without code duplication and error risk.