Launch Offer: Use codelaunch30for 30% off

value too long for type character varying

This error occurs when you try to insert a string that's longer than the column's maximum length.

The value too long error means your string exceeds the column's character limit.

Understanding the Error

ERROR: value too long for type character varying(50)

The string you're inserting is longer than the column allows.

Common Causes

1. String Exceeds Limit

SQL
-- Column is VARCHAR(50)
INSERT INTO users (name) VALUES ('This is a really long name that exceeds fifty characters limit');

2. Unexpected Input Length

User input or API data longer than anticipated.

3. Encoding Differences

Multi-byte characters taking more space than expected.

How to Fix It

Solution 1: Truncate the Value

SQL
-- Truncate to fit
INSERT INTO users (name)
VALUES (LEFT('Very long name here...', 50));

Solution 2: Increase Column Size

SQL
-- Make column larger
ALTER TABLE users ALTER COLUMN name TYPE VARCHAR(255);

-- Or use TEXT for unlimited length
ALTER TABLE users ALTER COLUMN name TYPE TEXT;

Solution 3: Validate Before Insert

JAVASCRIPT
function validateUser(name) {
  if (name.length > 50) {
    throw new Error('Name must be 50 characters or less');
  }
  return name;
}

Solution 4: Use TEXT Type

SQL
-- TEXT has no length limit
CREATE TABLE articles (
  id SERIAL PRIMARY KEY,
  content TEXT
);

Solution 5: Truncate in Application

JAVASCRIPT
const maxLength = 50;
const safeName = name.slice(0, maxLength);
await db.query('INSERT INTO users (name) VALUES ($1)', [safeName]);

Solution 6: Add Check Constraint with Better Error

SQL
ALTER TABLE users ADD CONSTRAINT name_length
CHECK (length(name) <= 50);
-- Gives clearer error than truncation

Finding Column Lengths

SQL
-- Check column definitions
SELECT column_name, data_type, character_maximum_length
FROM information_schema.columns
WHERE table_name = 'users';

-- Or in psql
\d users

Best Practices

  1. Use TEXT for variable-length strings when possible
  2. Validate input in application layer
  3. Set reasonable limits for VARCHAR columns
  4. Document length requirements in API specs
  5. Handle truncation gracefully if needed