Guides to moving from SQL Server to PostgreSQL are mostly tables of syntax: TOP becomes LIMIT, GETDATE() becomes now(), square brackets become double quotes. That part is easy, because the database tells you about every mistake. The expensive part is the statements that are valid on both databases and return something else. Nothing reports those. A user does, weeks later.
This case moves the data access code of a small customer application and looks for exactly those. The code is on GitHub: chudovo/application-modernization, case 11. Everything runs against a real SQL Server 2022 and a real PostgreSQL 17.
At a glance
| Before | After | |
|---|---|---|
| Database | SQL Server 2022 | PostgreSQL 17 |
| String comparison | case-insensitive everywhere | case-sensitive unless asked otherwise |
| Keys | IDENTITY | identity columns, sequences reset after the copy |
| Insert or update | try, catch the duplicate, update | INSERT … ON CONFLICT |
| Behaviour checks passing | 14 of 14 | 14 of 14, after 4 of 14 in the first attempt |
Step 1: checks that SQL Server defines
All SQL of the application sits behind one interface with an implementation per database. Fourteen checks call that interface and compare results: find a customer, register one, list, page, sum, count days. SQL Server defines what is expected, because that is what users have seen for years. Every check runs on a fresh database; for PostgreSQL the data is first copied over from SQL Server.
("days since the last order are calendar days", async store =>
{
// Ordered at 23:30, asked at 00:30: one hour later, and a day later.
Equal("1", (await store.DaysSinceLastOrderAsync(1, JustAfterMidnight)).ToString());
}),
("a known e-mail address in another letter case is refused as a duplicate", async store =>
{
try { await store.RegisterAsync("Anna S.", "Anna@Example.com", "DE"); }
catch (DuplicateEmailException) { return; }
throw new InvalidOperationException("the duplicate was accepted");
}),
Step 2: the translation everyone starts with
The first PostgreSQL version is the SQL Server code with each statement translated to PostgreSQL syntax and nothing else: the concatenation operator, RETURNING instead of OUTPUT, COALESCE instead of ISNULL, EXTRACT instead of DATEDIFF, true instead of 1. It compiles, and every statement is valid.
| Checks passing | |
|---|---|
| SQL Server | 14 of 14 |
| Translated statements, data copied as it is | 4 of 14 |
| Translated statements, identity sequences reset | 5 of 14 |
| Finished version | 14 of 14 |
With the sequences reset, one of the nine remaining failures is an error message. The other eight are wrong answers:
| Check | SQL Server | Translated statement on PostgreSQL |
|---|---|---|
| Find by e-mail in another letter case | found | not found |
| Register a known address in another letter case | refused | accepted: a second account |
| Find by name in another case, with a trailing space | found | not found |
| Search names for MEIER | bernd Meier | nothing |
| Call list, customers who never ordered first | NULL sorts first | NULL sorts last |
| Average items per order, 13 / 5 | 2 | 3 |
| Days since an order at 23:30, asked at 00:30 | 1 | 0 |
| Insert, catch the duplicate, update, in one transaction | works | current transaction is aborted |
Letter case: a setting nobody remembers choosing
With its default collation SQL Server compares every string without regard to letter case: in equality, in LIKE, and in unique constraints. Nobody wrote that down as a requirement, and the application depends on it in four places. The second row of the table is the serious one: on PostgreSQL the unique constraint lets Anna@Example.com register next to anna@example.com.
The e-mail column becomes citext, a PostgreSQL type that compares without case. The finished version then failed its own first run, which is how this trap was found:
CREATE EXTENSION IF NOT EXISTS citext;
-- email citext NOT NULL, CONSTRAINT uq_customers_email UNIQUE (email)
SELECT ... FROM customers WHERE email = @p0 -- the parameter is text: compared as text, case-sensitive
SELECT ... FROM customers WHERE email = @p0::citext -- compared as citext
A parameter arrives as text, and PostgreSQL resolves the comparison of citext with text as text with text. The column type alone is not enough; the parameter has to be cast. A test keeps both statements side by side.
Days are counted differently
-- SQL Server: counts the midnights between two moments
SELECT DATEDIFF(day, last_order_at, @now) FROM customers WHERE id = @id -- 1
-- The usual translation: counts whole 24-hour periods
SELECT EXTRACT(DAY FROM (@now - last_order_at)) FROM customers WHERE id = @id -- 0
-- What DATEDIFF did
SELECT @now::date - last_order_at::date FROM customers WHERE id = @id -- 1
An order placed at 23:30 is one day old an hour later by the first definition and zero days old by the second. Every reminder, deadline and overdue report built on the old function shifts by up to a day, and only for some rows.
A failed statement ends the transaction
// SQL Server: a failed statement leaves the transaction usable.
try
{
// INSERT customers (name, email, region) VALUES (...)
}
catch (SqlException e) when (e.Number is 2627 or 2601) // duplicate key
{
// UPDATE customers SET name = @p0 WHERE email = @p1
}
// INSERT audit (at, message) VALUES (...)
await transaction.CommitAsync();
This pattern is everywhere in code written for SQL Server. On PostgreSQL the failed insert aborts the transaction, and every statement after it is refused until a rollback. The fix is not a different way to catch the error:
-- PostgreSQL: the first error ends the transaction ("current transaction is aborted").
-- One statement that cannot fail on a duplicate replaces the pattern.
INSERT INTO customers (name, email, region) VALUES (@p0, @p1, @p2)
ON CONFLICT (email) DO UPDATE SET name = EXCLUDED.name;
Identity sequences do not follow the data
-- Rows are copied with their ids. The identity sequences do not notice and still start at 1.
SELECT setval(pg_get_serial_sequence('orders', 'id'), COALESCE((SELECT max(id) FROM orders), 0) + 1, false);
Without this, the first insert after the migration collides with a copied row. The translated version made it worse. It treated every unique violation as a duplicate e-mail address, so a new customer with a new address was told that the address already exists. For the same reason one check passed by accident until the sequences were reset: the duplicate was refused, but because of the key, not the address.
Two smaller ones
- NULL sorts at the other end. Ordering by the date of the last order puts customers who never ordered first on SQL Server and last on PostgreSQL. NULLS FIRST restores the list.
- The average of integers. On SQL Server the average of an integer column is an integer, cut off: 2. PostgreSQL returns 2.6, which the application rounded to 3. The finished version computes what the dashboard has always shown. Whether 2 is right is a fair question, to be decided on purpose.
One difference in the other direction
ISNULL(note, ‘no note on file’) takes the type of its first argument, a column of ten characters, and SQL Server has been showing users the text “no note on”. COALESCE on PostgreSQL returns all of it. Here the migration repairs something, so it is recorded in a test of its own and not hidden among the shared checks.
Moving the data
The copy is followed by a verification that reads every table from both databases and compares row counts and a checksum over all values. Values are normalised first, so that a bit and a boolean, or money and numeric, give the same text. One test changes a single amount by a cent on the PostgreSQL side and expects the verification to notice.
What is verified, and what is not
| Check | Result |
|---|---|
| 14 behaviour checks on SQL Server 2022 | 14 / 14 |
| The same 14 on PostgreSQL 17, data copied from SQL Server | 14 / 14 |
| The same 14 on the translated statements | 4 / 14, and 5 / 14 with sequences reset |
| Data copy with counts and checksums, pitfalls | 5 / 5 |
- No stored procedures, triggers or views. This application keeps its SQL in the application. T-SQL inside the database is the larger part of most real migrations and is not touched here.
- No volume. Eleven rows are copied one at a time. A real copy uses bulk loading and needs a plan for changes that arrive while it runs.
- No performance comparison. Some of the fixes need their own indexes on a real table.
- One pair of collations. SQL Server’s default and the PostgreSQL image’s locale. With other settings on either side the list of differences changes.
Run it yourself
You need the .NET 10 SDK and Docker for both databases:
docker run -d -e ACCEPT_EULA=Y -e MSSQL_SA_PASSWORD=Local_dev_only_1 -p 14330:1433 mcr.microsoft.com/mssql/server:2022-latest
docker run -d -e POSTGRES_PASSWORD=local_dev_only -p 54320:5432 postgres:17
dotnet test tests/Crm.Tests
When this path fits
Leaving SQL Server for PostgreSQL is usually a licence decision, and it pays off when the application owns its SQL and has tests like these around it. The lesson of this case is where to spend the effort: not on the statements that fail, but on finding the ones that do not. How this fits with the other ways of modernising a database is covered in the legacy database modernization guide. A related case changes a column while the application runs: zero-downtime schema change with expand and contract.
If you need a team for a migration like this, see our comparison of modernization vendors.