Quick revision
The short answer
Because H2 is a different database that only partly imitates PostgreSQL. Its SQL dialect, data types, functions, sequences, constraints and locking behave differently, native queries and JSON columns reach it untranslated, and the schema it runs on is usually generated by Hibernate rather than created by our real migrations. A green test on H2 proves the code works on H2; to prove it works in production we run the same tests against the same PostgreSQL version with Testcontainers and apply our Flyway or Liquibase migrations.
What to remember
In this answer, we saw that H2 passes tests that PostgreSQL fails because it is a different engine that only imitates PostgreSQL: dialect, types, identifier case, sequences, constraints and locking differ, native queries and JSON columns hit those differences directly, and the schema is usually generated by Hibernate rather than built by our migrations. Running the same tests against the same PostgreSQL version with Testcontainers, with Flyway or Liquibase migrations and ddl-auto set to validate, removes the whole category of surprise.
Your turn
Answer it aloud as you would in the interview, or type your answer below. Then show one part at a time and compare.
Because H2 is a different database that only partly imitates PostgreSQL. Its SQL dialect, data types, functions, sequences, constraints and locking behave differently, native queries and JSON columns reach it untranslated, and the schema it runs on is usually generated by Hibernate rather than created by our real migrations. A green test on H2 proves the code works on H2; to prove it works in production we run the same tests against the same PostgreSQL version with Testcontainers and apply our Flyway or Liquibase migrations.
Why this question is asked
Many Spring Boot projects start with H2 because it needs no setup: add the dependency and @DataJpaTest gives us an in-memory database in a second. Then one day a repository method that was green in every build fails on the first request in production with a SQL syntax error. Interviewers ask it to check whether we know what a test really proves. In this answer, we will recap what H2 is and what its compatibility mode does, look at the main kinds of differences with a failing example, see why a generated schema hides problems, and then set up a test that runs against real PostgreSQL with real migrations.
1A Quick Recap of H2 and Its Compatibility Modes
H2 is a small relational database written in Java. It can run inside the same JVM as our tests and keep everything in memory, so it starts in well under a second and disappears when the tests end. That speed is exactly why Spring Boot uses an embedded database like H2 by default in @DataJpaTest when one is on the classpath.
H2 offers compatibility modes, enabled with a URL setting such as MODE=PostgreSQL. A compatibility mode makes H2 accept some of another database's syntax and imitate some of its behaviour. The key word is some. H2 is not PostgreSQL running in memory; it is a separate engine with its own parser, its own type system, its own query planner and its own locking. So every test on H2 is a test of our code against an imitation, and the gaps in the imitation are where production failures come from.
2Where the Two Databases Differ
The easiest way to see the gap is to follow one small query. Suppose a migration creates a table called customer_order and a native query in our code reads it as "customer_order" in quotes. PostgreSQL folds unquoted names to lower case, so the table really is customer_order and the query works. H2 folds unquoted names to upper case, so the table it created is CUSTOMER_ORDER, the quoted lower-case name does not exist, and the test fails with a table not found error, or, if the test author removes the quotes to make H2 happy, the code now depends on H2's behaviour. Nothing about our business logic changed; only the engine did.
The same thing happens across the whole SQL surface, and the reason is always that H2 implements its own version of each feature. PostgreSQL-only syntax such as INSERT ... ON CONFLICT, the jsonb operators -> and ->>, array types and many date functions is missing in H2 or behaves differently, so check your H2 version before relying on any of it. Types such as jsonb, uuid, timestamptz and numeric are mapped to H2 types that store, compare or round values in their own way, so a value that survives a round trip in H2 may come back different in PostgreSQL. Even ordering can differ, because PostgreSQL places NULL values last in ascending order and compares text with the database collation, while H2's defaults depend on its mode and settings.
Constraints and locking matter even more, because they protect data. PostgreSQL supports partial unique indexes, such as an email that must be unique only where deleted is false, as well as deferrable and exclusion constraints; H2 supports only some of these, so the rule the index enforces may simply not exist in the test. Locking follows each engine's own concurrency design. Row locks, SELECT ... FOR UPDATE SKIP LOCKED and lock timeouts behave differently, so a test of 'two workers claim jobs at the same time' that passes on H2 says very little about what PostgreSQL will do.
| Area | What can differ | Typical symptom |
|---|---|---|
| SQL dialect | ON CONFLICT, jsonb operators, arrays, functions | Syntax error only in production |
| Data types | jsonb, uuid, timestamptz, numeric rounding | Wrong value or cast error |
| Identifiers | Upper versus lower case folding | Relation does not exist |
| Sequences | Increment size, allocation, caching | Duplicate ids or startup failure |
| Constraints | Partial and deferrable constraints | Constraint missing in the test |
| Locking | SKIP LOCKED, lock timeouts, MVCC details | Concurrency bug never reproduced |
3Native Queries and JSON Columns Reach the Database Untranslated
When we write JPQL or use derived query methods, Hibernate translates them into SQL for the configured dialect, which hides many differences. A native query is different: Hibernate sends our SQL string as it is. So a native query is tested against whatever database runs the test, and on H2 that is the wrong database. Here is a typical example.
The second outcome is the worse one, because the bent query then fails or returns the wrong rows in PostgreSQL. JSON columns have the same problem even without native queries: an attribute mapped with @JdbcTypeCode(SqlTypes.JSON) becomes jsonb in PostgreSQL and a different JSON type in H2, with different rules for comparison and indexing.
Sequences deserve a special mention. Hibernate's default sequence generator allocates ids in blocks of 50, and expects the database sequence to increment by 50. If the real migration creates the sequence with INCREMENT BY 1, ids can collide or Hibernate can refuse to start, depending on the version and settings; check your version. On H2 with a generated schema, Hibernate created the sequence itself with the increment it wanted, so the mismatch never appears in tests.
4A Generated Schema Hides the Real Schema
This is the difference people miss most often. With H2, tests usually run with spring.jpa.hibernate.ddl-auto=create-drop, so Hibernate builds the tables from our entity classes at startup. Production runs Flyway or Liquibase migrations that a person wrote, with the real column types, indexes, check constraints, partial unique indexes, triggers and default values.
So the test runs against a schema that only exists in the test. If an entity says a column is a String but the migration created it as varchar(20), the generated test schema uses a longer column and a 30 character value passes. If the migration adds a unique index that the entity does not mention, the test never sees the constraint. And if a migration itself has a bug, the tests never run it at all, so the first place it runs is the production deployment.
5Testing Against the Real Engine With Testcontainers
The fix is to run repository tests against the same engine and the same major version as production, on the schema our migrations build. Testcontainers starts PostgreSQL in Docker, Spring Boot's @ServiceConnection wires the connection details into the context, and Flyway runs the migrations at startup just as it does in production.
Notice the three choices. Replace.NONE stops Spring Boot from replacing our data source with an embedded one. ddl-auto=validate means Hibernate does not create anything; it only checks that the entities match the tables the migrations created, so a mapping that disagrees with the real schema fails the test at startup. And the image tag matches the production major version. The container class's package differs between Testcontainers 1.x and 2.x, so check your version for the import.
The cost is a few seconds to start PostgreSQL, paid once per test JVM if we share the container in a static field, and Spring's context cache reuses the application context between classes with the same configuration. For most teams that is a fair price for tests that finally say something true about production.
6Follow-up questions
Is H2 ever the right choice?
Yes, for code where the database is incidental: a quick prototype, a library that must work on any database through plain JPQL, or a teaching example. For a service that runs on PostgreSQL in production, I would not use H2 for repository or migration tests. Logic that does not touch SQL belongs in plain unit tests, which are faster than either.
Why not just use H2's PostgreSQL mode more carefully?
Because the mode can only imitate what its authors chose to imitate, and we cannot know in advance which difference our next query will hit. The failures are also asymmetric: a test that passes on H2 gives false confidence, and the bug appears in production. Running the real engine removes the whole category instead of guarding against it one query at a time.
7Conclusion
In this answer, we saw that H2 passes tests that PostgreSQL fails because it is a different engine that only imitates PostgreSQL: dialect, types, identifier case, sequences, constraints and locking differ, native queries and JSON columns hit those differences directly, and the schema is usually generated by Hibernate rather than built by our migrations. Running the same tests against the same PostgreSQL version with Testcontainers, with Flyway or Liquibase migrations and ddl-auto set to validate, removes the whole category of surprise.
Open with
The short answer is that a test on H2 proves the code works on H2, not on PostgreSQL. H2's compatibility mode only imitates PostgreSQL partly. The dialect differs, so things like ON CONFLICT, jsonb operators or arrays are missing or behave differently.
Then, if they want more
Types such as jsonb, uuid and timestamptz map differently, identifiers fold to upper case instead of lower case, and locking and concurrency behaviour follow H2's own design. Native queries are the classic trap, because Hibernate passes them through untranslated.
The other big reason is the schema: H2 tests usually use ddl-auto create-drop, so Hibernate builds tables from the entities, while production runs Flyway migrations with real column sizes, partial unique indexes and sequence increments, which the test never sees.
So what I do is run repository tests with Testcontainers on the same PostgreSQL major version as production, set AutoConfigureTestDatabase replace to NONE, use @ServiceConnection, let Flyway build the schema and set ddl-auto to validate. With one shared container per JVM it costs a few seconds, and the tests finally tell the truth about production.
About this answer
- Last updated
- 12 November 2026
- Versions it names
- PostgreSQL 17
- Checked
- Its structure and format are checked automatically. Use it as a carefully prepared study note: where a detail matters, confirm it against the documentation below. What the checks cover
- Where the question comes from
- Written by Scrivio for practice. It is not taken from an interview.
- Official documentation
- JUnit user guide, Mockito documentation
Report an issue with this answer
Copy the line below and send it to the author with what you found. It carries the address of this page.
Issue with "Why can a repository test pass on H2 but fail on PostgreSQL in production?": https://scrivio-interview-library.netlify.app/java/integration-testing/8f5410731e/