---
title: "SQL Server CHECK ... IN (...) is case-insensitive under the default collation"
url: "https://www.dariuszparys.com/notes/sql-server-check-in-is-case-insensitive"
author: "Dariusz Parys"
published: 2026-11-26T00:00:00.000Z
description: "A CHECK constraint that lists the allowed string values of an EF Core enum accepted wrongly cased values, because SQL Server's default collation compares case-insensitively, and the binary collation that fixes it does not exist in SQLite."
tags:
  - ".NET"
  - "EF Core"
  - "SQL Server"
---

# SQL Server CHECK ... IN (...) is case-insensitive under the default collation

## Context

An EF Core enum stored as a string (`HasConversion<string>()`) was guarded by a CHECK constraint, so that a typo in a manual `UPDATE` fails at the database instead of breaking every later read:

```sql
[Mode] IN ('Off', 'AllowedDomainsOnly', 'Open')
```

## Insight

- **The default collation accepts the wrong case.** A migration test showed SQL Server accepted `'open'`. Its default collation (e.g. `SQL_Latin1_General_CP1_CI_AS`) compares case-insensitively, so the "whitelist" accepts any casing.
- **The binary collation fixes SQL Server but breaks SQLite.** `COLLATE Latin1_General_100_BIN2` makes the check exact. If the model is also built with `EnsureCreated` on SQLite in unit tests, those tests fail with `no such collation sequence: Latin1_General_100_BIN2`.
- **Keep the constraint SQL Server-only.** Declare it in `OnModelCreating` behind `Database.IsSqlServer()`, not in the shared `IEntityTypeConfiguration`. The migration snapshot is generated against SQL Server, so it still contains the constraint.

```csharp
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
    modelBuilder.ApplyConfigurationsFromAssembly(typeof(AppDbContext).Assembly);

    if (Database.IsSqlServer())
    {
        modelBuilder.Entity<SettingsEntity>().ToTable("Settings", table =>
            table.HasCheckConstraint(
                "CK_Settings_Mode",
                "[Mode] COLLATE Latin1_General_100_BIN2 IN ('Off', 'AllowedDomainsOnly', 'Open')"));
    }
}
```

**Always cover such a constraint with a migration test against a real SQL Server** (e.g. Testcontainers) that tries a wrong-case value and a typo, and asserts the constraint name in the exception.

Often better: if the value only ever changes at deployment, keep it out of the database. Make it a configuration value bound to an enum, and fail at startup (`ValidateOnStart`) on an unknown value.
