Ошибка data too long for column

I’ve written a MySQL script to create a database for hypothetical hospital records and populate it with data. One of the tables, Department, has a column named Description, which is declared as type varchar(200). When executing the INSERT command for Description I get an error:

error 1406: Data too long for column ‘Description’ at row 1.

All the strings I’m inserting are less than 150 characters.

Here’s the declaration:

CREATE TABLE Department(
    ...
    Description varchar(200)
    ...);

And here’s the insertion command:

INSERT INTO Department VALUES
(..., 'There is some text here',...), (..., 'There is some more text over here',...);

By all appearances, this should be working. Anyone have some insight?

Raging Bull's user avatar

Raging Bull

18.6k13 gold badges50 silver badges55 bronze badges

asked Sep 19, 2013 at 14:26

Ben C.'s user avatar

11

Change column type to LONGTEXT

answered Dec 18, 2015 at 10:14

Alexander Serkin's user avatar

Alexander SerkinAlexander Serkin

1,6191 gold badge12 silver badges11 bronze badges

2

I had a similar problem when migrating an old database to a new version.

Switch the MySQL mode to not use STRICT.

SET @@global.sql_mode= 'NO_AUTO_CREATE_USER,NO_ENGINE_SUBSTITUTION';

Error Code: 1406. Data too long for column — MySQL

Community's user avatar

answered Jan 20, 2016 at 19:05

calraiden's user avatar

calraidencalraiden

1,6561 gold badge27 silver badges37 bronze badges

2

There is an hard limit on how much data can be stored in a single row of a mysql table, regardless of the number of columns or the individual column length.

As stated in the OFFICIAL DOCUMENTATION

The maximum row size constrains the number (and possibly size) of columns because the total length of all columns cannot exceed this size. For example, utf8 characters require up to three bytes per character, so for a CHAR(255) CHARACTER SET utf8 column, the server must allocate 255 × 3 = 765 bytes per value. Consequently, a table cannot contain more than 65,535 / 765 = 85 such columns.

Storage for variable-length columns includes length bytes, which are assessed against the row size. For example, a VARCHAR(255) CHARACTER SET utf8 column takes two bytes to store the length of the value, so each value can take up to 767 bytes.

Here you can find INNODB TABLES LIMITATIONS

Community's user avatar

answered Sep 19, 2013 at 14:33

STT LCU's user avatar

STT LCUSTT LCU

4,3384 gold badges29 silver badges47 bronze badges

in mysql if you take VARCHAR then change it to TEXT bcoz its size is 65,535
and if you can already take TEXT the change it with LONGTEXT only if u need more then 65,535.

total size of LONGTEXT is 4,294,967,295 characters

answered Sep 17, 2019 at 10:49

Krishna Jangid's user avatar

Krishna JangidKrishna Jangid

4,7915 gold badges26 silver badges33 bronze badges

Varchar has its own limits. Maybe try changing datatype to text.!

answered Sep 19, 2013 at 14:30

Jayesh Amin's user avatar

Jayesh AminJayesh Amin

3142 silver badges12 bronze badges

1

Turns out, as is often the case, it was a stupid error on my part. The way I was testing this, I wasn’t rebuilding the Department table after changing the data type from varchar(50) to varchar(200); I was just re-running the insert command, still with the column as varchar(50).

answered Sep 19, 2013 at 18:14

Ben C.'s user avatar

Ben C.Ben C.

1,7415 gold badges14 silver badges24 bronze badges

For me, I defined column type as BIT (e.g. «boolean»)

When I tried to set column value «1» via UI (Workbench), I was getting a «Data too long for column» error.

Turns out that there is a special syntax for setting BIT values, which is:

b'1'

answered Aug 10, 2020 at 8:47

Illidan's user avatar

IllidanIllidan

4,0073 gold badges38 silver badges49 bronze badges

If your source data is larger than your target field and you just want to cut off any extra characters, but you don’t want to turn off strict mode or change the target field’s size, then just cut the data down to the size you need with LEFT(field_name,size).

INSERT INTO Department VALUES
(..., LEFT('There is some text here',30),...), (..., LEFT('There is some more text over here',30),...);

I used «30» as an example of your target field’s size.

In some of my code, it’s easy to get the target field’s size and do this. But if your code makes that hard, then go with one of the other answers.

answered Feb 25, 2019 at 7:59

Buttle Butkus's user avatar

Buttle ButkusButtle Butkus

9,18613 gold badges79 silver badges120 bronze badges

With Hibernate you can create your own UserType. So thats what I did for this issue. Something as simple as this:

    public class BytesType implements org.hibernate.usertype.UserType {

         private final int[] SQL_TYPES = new int[] { java.sql.Types.VARBINARY };
     //...
    }

There of course is more to implement from extending your own UserType but I just wanted to throw that out there for anyone looking for other methods.

simbabque's user avatar

simbabque

53.6k8 gold badges73 silver badges136 bronze badges

answered Aug 18, 2014 at 15:07

hugh's user avatar

Very old question, but I tried everything suggested above and still could not get it resolved.

Turns out that, I had after insert/update trigger for the main table which tracked the changes by inserting the record in history table having similar structure. I increased the size in the main table column but forgot to change the size of history table column and that created the problem.

I did similar changes in the other table and error is gone.

answered Jun 6, 2019 at 8:43

rahimv's user avatar

rahimvrahimv

5414 silver badges12 bronze badges

1

I try to create a table with a field as 200 characters and I’ve added two rows with early 160 characters and it’s OK. Are you sure your rows are less than 200 characters?

Show SqlFiddle

answered Sep 19, 2013 at 14:35

Joe Taras's user avatar

Joe TarasJoe Taras

15.1k7 gold badges40 silver badges55 bronze badges

1

There was a similar problem when storing a hashed password into a table. Changing the maximum column length didn’t help. Everything turned out to be simple. It was necessary to delete the previously created table from the database, and then test the code with new values ​​of the allowable length.

answered Mar 29, 2021 at 12:12

vollander's user avatar

If you re using type: DataTypes.STRING, then just pass how long this string can be like DataTypes.STRING(1000)

answered May 12, 2021 at 10:42

Dawid Pstrak's user avatar

In my case this error occurred due to entering data a wrong type for example: if it is a long type column, i tried to enter in string type. so please check your data that you are entering and type are same or not

answered Jun 15, 2017 at 5:27

havi havish's user avatar

For me, I try to update column type «boolean» value
When I tried to set column value 1 MySQL Workbench, I was getting a «Data too long for column» error.

So for that there is a special syntax for setting boolean values, which is:

   UPDATE `DBNAME`.`TABLE_NAME` SET `FIELD_NAME` = false WHERE (`ID` = 'ID_VALUE');   //false for 0

   UPDATE `DBNAME`.`TABLE_NAME` SET `FIELD_NAME` = true WHERE (`ID` = 'ID_VALUE');  //true for 1

answered Nov 8, 2022 at 10:20

nikita sharma's user avatar

I had a different problem which gave the same error so I’ll make a quick recap as this seems to have quite different sources and the error does not help much to track down the root cause.

Common sources for INSERT / UPDATE

Size of value in row

This is exactly what the error is complaining about. Maybe it’s just that.
You can:

  • increase the column size: for long strings you can try to use TEXT, MEDIUMTEXT or LONGTEXT
  • trim the value that is too long: you can use tools from the language you’re using to build the query or directly in SQL with LEFT(value,size) or RIGHT(...) or SUBSTRING(...)

Beware that there is a maximum row size in a MySQL table as reported by this answer. Check documentation and InnoDB engine limitations.

Datatype Mismatch

One or more rows are of the wrong datatype.
common sources of error are

  • ENUM
  • BIT: don’t use 1 but b'1'

Data outlier

In a long list of insert one can easily miss a row which has a field not adhering to the column typing, like an ENUM generated from a string.

Python Django

Check if you have sample_history enabled, after a change in a column size it must be updated too.

answered Feb 7 at 9:54

Guglie's user avatar

GuglieGuglie

2,0211 gold badge23 silver badges42 bronze badges

When inserting values to a table in MySQL, you might run into this error:

Error Code: 1406. Data too long for column

That error message means you are inserting a value that is greater than the defined maximum size of the column.

The solution to resolve this error is to update the table and change the column size.

Example

We have a simple table employees:

CREATE TABLE employees (
 id int(5),
 full_name varchar(5)
);

And you insert the first row of data:

INSERT INTO employees
 VALUES(1, 'Alex with an extra long full name, longer than 10');

Since the full_name value is longer than the defined length, MySQL will throw the error Data too long for column. To resolve that, modify the column size:

ALTER TABLE employees 
  MODIFY COLUMN full_name varchar(50);

Another workaround is to disable the STRICT mode, MySQL will automatically truncate any insert values that exceed the specified column width instead of showing the error. The trade-off is, you might not be aware that your data won’t fit and end up losing original data.

To disable the STRICT mode, you can:

  • Edit your MySQL configuration file:

Open your my.ini (Windows) or my.cnf (Unix) file and look for “sql-mode”, and remove the tag STRICT_TRANS_TABLES

  • Or execute this command:
SET @@global.sql_mode= '';

Need a good GUI tool for databases? TablePlus provides a native client that allows you to access and manage Oracle, MySQL, SQL Server, PostgreSQL, and many other databases simultaneously using an intuitive and powerful graphical interface.

Download TablePlus for Mac.

Not on Mac? Download TablePlus for Windows.

On Linux? Download TablePlus for Linux

Need a quick edit on the go? Download TablePlus for iOS

TablePlus in Dark mode

One of the column in my table was initially created as a varchar(1000). Now there is a need to increase the size of that column to hold around 5000 characters. I used the alter statement to increase the size of that column.

DESC table_name as well as SHOW CREATE TABLE table_name clearly indicates the new size of that column to be 5000 characters. However, interestingly when I try to insert any data exceeding 1000 characters ERROR 1406 (22001) : Data too long for column error shows up.

Out of desperation I changed the datatype to text, and still it’s limited to 1000 characters. Any suggestion?

I created an other dummy table with a column size of varchar(5000) and that works just fine.

Engine used is InnoDB and Default Charset is UTF8.

marc_s's user avatar

marc_s

8,7726 gold badges44 silver badges51 bronze badges

asked Mar 19, 2013 at 3:40

idok's user avatar

8

I had what appeared to be exactly the same problem. I had a column that was VARCHAR(30), and I used ALTER TABLE myTable MODIFY COLUMN myColumn VARCHAR(60) NOT NULL, to double its size. But I kept getting «Error Code: 1406 Data too long for column ‘myColumn’ at row 1» whenever I tried to insert a value that was > 30 characters. It seemed, somehow, that mySQL had some «memory» of the previous column size, and was still enforcing it, even though INFORMATION_SCHEMA.COLUMNS showed the column’s character_maximum_length as the new value, 60. I was convinced it was a mySQL bug.

I eventually discovered the actual problem was that this particular table had a trigger on it, whose purpose was to maintain an audit trail of changes, by populating a similarly-defined myTableHistory table. I had forgotten to do an ALTER TABLE myTableHistory to increase the size of the same column in that table.

answered Dec 12, 2013 at 15:13

Bob F's user avatar

Bob FBob F

562 bronze badges

1

мне нужно выложить таблицу полностью, «макрос обрезающий значения в столбце» это значит урезать таблицу? если да то это не решение проблемы, естественно..

я не понимаю «макс длинна строки около 60000 символов», моя таблица 183 000 знаков с пробелами, то есть мне нужно разбить одну таблицу на 3 таблицы меньшего размера? ну это ерунда какая то.. или я не правильно понимаю..

а что это за ограничение, что именно ставит такое ограничение? и как его обойти, самое главное?

ни на одном движке с таким не сталкивался.. а перетащить мне нужно эту таблицу которая без каких либо проблем встает на opencart, с которого мы сознательно переехали на shop-script, как на более мощный, современный, и удобный движок. и уперлись в этот затык на ровном месте можно сказать..

Tried to post a comment but seems to have disappeared.. I’ll try again:

Here’s the content of the upgrade func after running flask db migrate and upgrade (after changing the Paper model to have a content_path type of Text). As you can see, it does not seem to have picked up the change, despite havingg compare_types=True as shown above in env.py. Note however that it did pick up the change when I changed the len of the String arg from 64;

def upgrade():
# ### commands auto generated by Alembic — please adjust! ###
op.create_table(‘paper’,
sa.Column(‘id’, sa.Integer(), nullable=False),
sa.Column(‘content_path’, sa.String(length=1048576), nullable=True),
sa.Column(‘title’, sa.String(length=64), nullable=True),
sa.Column(‘abstract’, sa.String(length=1048576), nullable=True),
sa.Column(‘coauthors’, sa.String(length=64), nullable=True),
sa.PrimaryKeyConstraint(‘id’)
)
op.create_index(op.f(‘ix_paper_coauthors’), ‘paper’, [‘coauthors’], unique=False)
op.create_index(op.f(‘ix_paper_title’), ‘paper’, [‘title’], unique=False)
op.create_table(‘photograph’,
sa.Column(‘id’, sa.Integer(), nullable=False),
sa.Column(‘content_path’, sa.String(length=64), nullable=True),
sa.Column(‘title’, sa.String(length=64), nullable=True),
sa.Column(‘subject’, sa.String(length=64), nullable=True),
sa.PrimaryKeyConstraint(‘id’)
)
op.create_index(op.f(‘ix_photograph_subject’), ‘photograph’, [‘subject’], unique=False)
op.create_index(op.f(‘ix_photograph_title’), ‘photograph’, [‘title’], unique=False)
op.create_table(‘project’,
sa.Column(‘id’, sa.Integer(), nullable=False),
sa.Column(‘content_path’, sa.String(length=1048576), nullable=True),
sa.Column(‘title’, sa.String(length=64), nullable=True),
sa.Column(‘abstract’, sa.String(length=1048576), nullable=True),
sa.Column(‘coauthors’, sa.String(length=64), nullable=True),
sa.PrimaryKeyConstraint(‘id’)
)
op.create_index(op.f(‘ix_project_coauthors’), ‘project’, [‘coauthors’], unique=False)
op.create_index(op.f(‘ix_project_title’), ‘project’, [‘title’], unique=False)
op.create_table(‘painting’,
sa.Column(‘id’, sa.Integer(), nullable=False),
sa.Column(‘content_path’, sa.String(length=64), nullable=True),
sa.Column(‘title’, sa.String(length=64), nullable=True),
sa.Column(‘subject’, sa.String(length=64), nullable=True),
sa.Column(‘photo_id’, sa.Integer(), nullable=True),
sa.ForeignKeyConstraint([‘photo_id’], [‘photograph.id’], ),
sa.PrimaryKeyConstraint(‘id’)
)
op.create_index(op.f(‘ix_painting_subject’), ‘painting’, [‘subject’], unique=False)
op.create_index(op.f(‘ix_painting_title’), ‘painting’, [‘title’], unique=False)
# ### end Alembic commands ###

Понравилась статья? Поделить с друзьями:

Не пропустите эти материалы по теме:

  • Яндекс еда ошибка привязки карты
  • Ошибка d1 viessmann vitogas 100 что делать
  • Ошибка data bin не найден при установке игры
  • Ошибка dbghelp dll и как ее исправить
  • Ошибка d1 viessmann vitogas 050

  • 0 0 голоса
    Рейтинг статьи
    Подписаться
    Уведомить о
    guest

    0 комментариев
    Старые
    Новые Популярные
    Межтекстовые Отзывы
    Посмотреть все комментарии