How to fix P2023: Inconsistent column data in Prisma

PrismaINTERMEDIATEHIGHUpdated Dec 29, 2025· 166 views

The Prisma P2023 error indicates a data type mismatch between your database and what Prisma expects based on your schema. This typically occurs due to integer overflow, invalid data types, failed conversions, or schema mismatches. The fix usually involves validating data types, migrating column types, or ensuring your schema matches your actual database structure.

Quick fix

Fixes P2023: Inconsistent column data

import { Prisma } from '@prisma/client';

try {
  const record = await prisma.user.findUnique({
    where: { id: 'some-id' }
  });
} catch (error) {
  if (error instanceof Prisma.PrismaClientKnownRequestError) {
    if (error.code === 'P2023') {
      console.log('Full error message:', error.message);
      // Example: "Inconsistent column data: Conversion failed: Value 9223372036854775807
      // does not fit in an INT column, try migrating the 'int' column type to BIGINT."
    }
  }
}
  1. Check the specific conversion error message
  2. Migrate Int columns to BigInt for large numbers
  3. Fix schema-to-database mismatches
  4. Fix MongoDB string-to-number conversion issues
prisma — error
import { Prisma } from '@prisma/client';
try {
const record = await prisma.user.findUnique({
where: { id: 'some-id' }
});
} catch (error) {
if (error instanceof Prisma.PrismaClientKnownRequestError) {
if (error.code === 'P2023') {
console.log('Full error message:', error.message);
// Example: "Inconsistent column data: Conversion failed: Value 9223372036854775807
// does not fit in an INT column, try migrating the 'int' column type to BIGINT."
}
}
}
P2023: Inconsistent column data

What this error means

The P2023 error in Prisma indicates "Inconsistent column data" - a critical runtime error that occurs when Prisma cannot safely convert a value retrieved from the database to the expected JavaScript type. This error is thrown when: - A database value cannot be converted to the type specified in your Prisma schema - Data in your database does not match the expected type definition - A conversion fails due to invalid input or out-of-range values For example, if your schema defines a field as an Int but the database contains a value that exceeds the maximum 32-bit integer size, or if a String field contains data that cannot be parsed as the declared type, Prisma will throw P2023. The error message provides details about what conversion failed and often suggests the specific action needed to fix it.

Typical symptoms

  • Prisma Client throws PrismaClientKnownRequestError with code P2023
  • Database queries fail with "Inconsistent column data" message
  • Error includes details like "Conversion failed" or "could not convert"
  • Application crashes when reading from database after schema changes
  • Error occurs only for specific records or rows with certain values
  • Errors appear after upgrading Prisma version
  • RelationJoins preview feature causes unexpected P2023 errors

Common causes

  1. Integer overflow - storing values larger than Int32 max (2,147,483,647) in an Int column
  2. Type mismatch - database column contains a different type than declared in schema
  3. MongoDB string-to-number conversion failure - numeric values stored as strings instead of numbers
  4. Invalid UUID format - passing malformed UUID strings to UUID columns
  5. Bytes field conversion failure - unable to decode base64-encoded bytes properly
  6. DateTime/Timestamp issues - invalid date formats or timezone mismatches
  7. PostgreSQL Citext array parsing bug - using String[] @db.Citext with PostgreSQL adapter
  8. Preview feature conflicts - relationJoins feature causing conversion failures
  9. Data encoding mismatch - binary data or encoding issues with text fields

How to fix "P2023: Inconsistent column data"

1Check the specific conversion error message

Examine the full error message to understand what conversion failed:

typescript
import { Prisma } from '@prisma/client';

try {
  const record = await prisma.user.findUnique({
    where: { id: 'some-id' }
  });
} catch (error) {
  if (error instanceof Prisma.PrismaClientKnownRequestError) {
    if (error.code === 'P2023') {
      console.log('Full error message:', error.message);
      // Example: "Inconsistent column data: Conversion failed: Value 9223372036854775807
      // does not fit in an INT column, try migrating the 'int' column type to BIGINT."
    }
  }
}

Common error message patterns:
- "Conversion failed: Value X does not fit in an INT column" → Integer overflow
- "Failed to convert 'X' to 'Y'" → Type mismatch
- "Could not convert from 'base64 encoded bytes'" → Bytes conversion issue
- "List field did not return an Array" → Array parsing problem
- "Error creating UUID, invalid length" → Invalid UUID format

2Migrate Int columns to BigInt for large numbers

If you encounter "does not fit in an INT column" errors, migrate the column to BIGINT:

Step 1: Update your Prisma schema

prisma
model User {
  id       String   @id @default(cuid())
  largeNum BigInt   // Changed from Int to BigInt
  name     String
}

Step 2: Create a migration

bash
npx prisma migrate dev --name migrate_int_to_bigint

Step 3: Update your TypeScript code to handle BigInt

typescript
// Note: BigInt in JavaScript uses the 'n' suffix
const user = await prisma.user.findUnique({
  where: { id: 'user-1' }
});

// user.largeNum is now a BigInt
console.log(typeof user.largeNum); // 'bigint'

// Convert to string if needed
const numberAsString = user.largeNum.toString();

// JSON serialization requires custom handling
JSON.stringify(user, (key, value) =>
  typeof value === 'bigint' ? value.toString() : value
);

Step 4: Handle BigInt in API responses

typescript
// Add a middleware or custom JSON replacer for API responses
const jsonReplacer = (key: string, value: any) => {
  if (typeof value === 'bigint') {
    return value.toString();
  }
  return value;
};

app.post('/api/users', async (req, res) => {
  const user = await prisma.user.findUnique({
    where: { id: 'user-1' }
  });

  res.json(JSON.parse(JSON.stringify(user, jsonReplacer)));
});
3Fix schema-to-database mismatches

Ensure your Prisma schema accurately reflects your actual database structure:

Step 1: Pull the actual database schema

bash
npx prisma db pull

This introspects your database and updates schema.prisma to match reality.

Step 2: Compare your schema with the database

bash
# View what changed
git diff prisma/schema.prisma

Step 3: Fix discrepancies

If your intended schema is different from the database, create a migration:

prisma
// If database has VARCHAR but schema expects Int
model Product {
  id       String  @id @default(cuid())
  price    Decimal @db.Decimal(10, 2)  // Explicitly specify database type
  quantity Int     // Should match database type
}

Step 4: Apply the migration

bash
npx prisma migrate dev --name fix_schema_mismatch
4Fix MongoDB string-to-number conversion issues

If using MongoDB with Prisma, ensure numeric values are stored with the correct type:

Option 1: Fix data in MongoDB first

javascript
// MongoDB migration script
db.users.updateMany(
  { age: { $type: "string" } },
  [
    {
      $set: {
        age: { $toInt: "$age" }
      }
    }
  ]
);

Option 2: Handle conversion during queries

typescript
// Prisma with explicit type casting
const users = await prisma.user.findMany({
  select: {
    id: true,
    age: true
  }
});

// Cast strings to numbers if needed
const usersWithCorrectTypes = users.map(user => ({
  ...user,
  age: typeof user.age === 'string' ? parseInt(user.age, 10) : user.age
}));

Option 3: Use Prisma migrations to transform data

sql
-- SQL migration for MongoDB (if using MongoDB with SQL migration tool)
UPDATE users SET age = CAST(age AS INTEGER) WHERE age IS NOT NULL;
5Validate and fix UUID format issues

If receiving "Error creating UUID, invalid length" errors:

typescript
import { validate as validateUUID } from 'uuid';

async function safeQuery(userId: string) {
  // Validate UUID format before querying
  if (!validateUUID(userId)) {
    throw new Error(`Invalid UUID format: ${userId}`);
  }

  try {
    return await prisma.user.findUnique({
      where: { id: userId }
    });
  } catch (error) {
    if (error instanceof Prisma.PrismaClientKnownRequestError &&
        error.code === 'P2023') {
      throw new Error('Invalid UUID in database or query');
    }
    throw error;
  }
}

// In your API handlers
app.get('/users/:id', async (req, res) => {
  try {
    const user = await safeQuery(req.params.id);
    res.json(user);
  } catch (error) {
    res.status(400).json({ error: error.message });
  }
});
6Disable problematic preview features

If P2023 errors started appearing after enabling preview features, disable them:

Check your schema.prisma for preview features:

prisma
// Remove or comment out problematic features
generator client {
  provider = "prisma-client-js"
  // previewFeatures = ["relationJoins"]  // Comment out
}

Known problematic combinations:
- relationJoins with Bytes fields (Prisma 5.10.2+)
- PostgreSQL adapter with String[] @db.Citext

Regenerate Prisma Client:

bash
npx prisma generate

Check if the P2023 error persists. If removing a preview feature fixes it, report the issue to Prisma GitHub.

7Handle P2023 errors gracefully in your application

Implement error handling for P2023 to prevent application crashes:

typescript
import { Prisma } from '@prisma/client';

async function fetchUserWithErrorHandling(userId: string) {
  try {
    return await prisma.user.findUnique({
      where: { id: userId }
    });
  } catch (error) {
    if (error instanceof Prisma.PrismaClientKnownRequestError) {
      if (error.code === 'P2023') {
        console.error('Data consistency error:', error.message);
        // Log for debugging
        logger.error('P2023 inconsistent column data', {
          userId,
          originalError: error.meta
        });

        // Return graceful error to user
        throw new Error(
          'Unable to retrieve user data. Please contact support if this persists.'
        );
      }
    }
    throw error;
  }
}

// In Express/Next.js
app.get('/api/users/:id', async (req, res) => {
  try {
    const user = await fetchUserWithErrorHandling(req.params.id);
    res.json(user);
  } catch (error) {
    res.status(500).json({
      error: error.message,
      code: 'INTERNAL_ERROR'
    });
  }
});

Advanced notes

Version-Specific Behavior:
- Prisma 4.0.0+: Stricter type checking on integer values (may trigger new P2023 errors on existing data)
- Prisma 5.10.2+: relationJoins preview feature has known Bytes conversion bugs
- Prisma 6.0+: PostgreSQL adapter has issues with citext array fields

Database-Specific Issues:

SQLite: Integer overflow checks are strict. Values exceeding 32-bit integer limits require BigInt type.

PostgreSQL:
- Citext arrays may fail to parse with certain adapter versions
- Timestamptz fields can cause conversion failures
- Use explicit @db types: @db.Timestamp, @db.Timestamptz

MySQL: Type mismatches are common with JSON fields. Always validate JSON before storing.

MongoDB: String-to-number conversion is a frequent source of P2023. Ensure documents use correct BSON types.

Recovery Strategies for Production:

1. Data Audit: Query the database directly to identify problematic rows

sql
-- PostgreSQL example
   SELECT * FROM "User" WHERE id = 'affected-id';

2. Partial Migrations: If only specific rows are affected, update them in isolation

typescript
// Fetch without the problematic field first
   const user = await prisma.user.findUnique({
     where: { id: 'user-1' },
     select: { id: true, name: true }  // Skip problematic field
   });

3. Rollback and Investigate: If errors appeared after schema changes

bash
npx prisma migrate resolve --rolled-back "migration-name"

Common Misconceptions:
- P2023 is NOT a connection issue (it's data integrity)
- P2023 is NOT solved by reconnecting (the data mismatch persists)
- P2023 requires fixing the actual data or schema, not just error handling

Testing P2023 Scenarios:

typescript
describe('P2023 Error Handling', () => {
  it('should handle inconsistent column data gracefully', async () => {
    // Manually insert invalid data (bypass Prisma validation)
    await prisma.$executeRawUnsafe(
      'INSERT INTO "User" (id, age) VALUES ($1, $2)',
      ['test-id', '99999999999999999999'] // Value too large for Int
    );

    // Attempt to read should throw P2023
    await expect(
      prisma.user.findUnique({ where: { id: 'test-id' } })
    ).rejects.toThrow('P2023');
  });
});

Frequently asked questions

What does "P2023: Inconsistent column data" mean?
The P2023 error in Prisma indicates "Inconsistent column data" - a critical runtime error that occurs when Prisma cannot safely convert a value retrieved from the database to the expected JavaScript type. This error is thrown when: - A database value cannot be converted to the type specified in your Prisma schema - Data in your database does not match the expected type definition - A conversion fails due to invalid input or out-of-range values For example, if your schema defines a field as an Int but the database contains a value that exceeds the maximum 32-bit integer size, or if a String field contains data that cannot be parsed as the declared type, Prisma will throw P2023. The error message provides details about what conversion failed and often suggests the specific action needed to fix it.
How do I fix "P2023: Inconsistent column data"?
The Prisma P2023 error indicates a data type mismatch between your database and what Prisma expects based on your schema. This typically occurs due to integer overflow, invalid data types, failed conversions, or schema mismatches. The fix usually involves validating data types, migrating column types, or ensuring your schema matches your actual database structure.
What causes "P2023: Inconsistent column data"?
Integer overflow - storing values larger than Int32 max (2,147,483,647) in an Int column Type mismatch - database column contains a different type than declared in schema MongoDB string-to-number conversion failure - numeric values stored as strings instead of numbers
Is the "P2023: Inconsistent column data" error serious?
Yes. This is a high-severity error that usually blocks work until it is fixed, but the steps above resolve it.

Official resources & further reading