Перейти к содержимому

Varchar 255 сколько символов

  • автор:

# Data Types

To make the multiplication with 2 MySQL automatically converts the string 123 into a number.

The conversion to a number starts from left to right. If the conversion is not possible the result is 0

# VARCHAR(255) — or not

Suggested max len

First, I will mention some common strings that are always hex, or otherwise limited to ASCII. For these, you should specify CHARACTER SET ascii ( latin1 is ok) so that it will not waste space:

Why not simply 255? There are two reasons to avoid the common practice of using (255) for everything.

  • When a complex SELECT needs to create temporary table (for a subquery, UNION , GROUP BY , etc), the preferred choice is to use the MEMORY engine, which puts the data in RAM. But VARCHARs are turned into CHAR in the process. This makes VARCHAR(255) CHARACTER SET utf8mb4 take 1020 bytes. That can lead to needing to spill to disk, which is slower.
  • In certain situations, InnoDB will look at the potential size of the columns in a table and decide that it will be too big, aborting a CREATE TABLE .

VARCHAR versus TEXT

Usage hints for *TEXT , CHAR , and VARCHAR , plus some Best Practice:

  • Never use TINYTEXT .
  • Almost never use CHAR — it is fixed length; each character is the max length of the CHARACTER SET (eg, 4 bytes/character for utf8mb4).
  • With CHAR , use CHARACTER SET ascii unless you know otherwise.
  • VARCHAR(n) will truncate at n characters; TEXT will truncate at some number of bytes. (But, do you want truncation?)
  • *TEXT may slow down complex SELECTs due to how temp tables are handled.

# INT as AUTO_INCREMENT

Any size of INT may be used for AUTO_INCREMENT . UNSIGNED is always appropriate.

Keep in mind that certain operations "burn" AUTO_INCREMENT ids. This could lead to an unexpected gap. Examples: INSERT IGNORE and REPLACE . They may preallocate an id before realizing that it won’t be needed. This is expected behavior and by design in the InnoDB engine and should not discourage their use.

# Others

There is already a separate entry for "FLOAT, DOUBLE, and DECIMAL" and "ENUM". A single page on datatypes is likely to be unwieldy — I suggest "Field types" (or should it be called "Datatypes"?) be an overview, then split into these topic pages:

  • INTs
  • FLOAT, DOUBLE, and DECIMAL
  • Strings (CHARs, TEXT, etc)
  • BINARY and BLOB
  • DATETIME, TIMESTAMP, and friends
  • ENUM and SET
  • Spatial data (MySQL 5.7.8+)
  • How to represent Money, and other common ‘types’ that need shoehorning into existing datatypes

Where appropriate, each topic page should include, in addition to syntax and examples:

  • Considerations when ALTERing
  • Size (bytes)
  • Contrast with non-MySQL engines (low priority)
  • Considerations when using the datatype in a PRIMARY KEY or secondary key
  • other Best Practice
  • other Performance issues

(I assume this "example" will self-distruct when my suggestions have been satisfied or vetoed.)

# Introduction (numeric)

MySQL offers a number of different numeric types. These can be broken down into

Group Types
Integer Types INTEGER , INT , SMALLINT , TINYINT , MEDIUMINT , BIGINT
Fixed Point Types DECIMAL , NUMERIC
Floating Point Types FLOAT , DOUBLE
Bit Value Type BIT

# Integer Types

Minimal unsigned value is always 0.

Type Storage
(Bytes)
Minimum Value
(Signed)
Maximum Value
(Signed)
Maximum Value
(Unsigned)
TINYINT 1 -2 7
-128
2 7 -1
127
2 8 -1
255
SMALLINT 2 -2 15
-32,768
2 15 -1
32,767
2 16 -1
65,535
MEDIUMINT 3 -2 23
-8,388,608
2 23 -1
8,388,607
2 24 -1
16,777,215
INT 4 -2 31
-2,147,483,648
2 31 -1
2,147,483,647
2 32 -1
4,294,967,295
BIGINT 8 -2 63
-9,223,372,036,854,775,808
2 63 -1
9,223,372,036,854,775,807
2 64 -1
18,446,744,073,709,551,615

# Fixed Point Types

MySQL’s DECIMAL and NUMERIC types store exact numeric data values. It is recommended to use these types to preserve exact precision, such as for money.

# Decimal

These values are stored in binary format. In a column declaration, the precision and scale should be specified

Precision represents the number of significant digits that are stored for values.

Scale represents the number of digits stored after the decimal

5 represents the precision and 2 represents the scale . For this example, the range of values that can be stored in this column is -999.99 to 999.99

If the scale parameter is omitted, it defaults to 0

This data type can store up to 65 digits.

The number of bytes taken by DECIMAL(M,N) is approximately M/2 .

# Floating Point Types

FLOAT and DOUBLE represent approximate data types.

REAL is a synonym for FLOAT . DOUBLE PRECISION is a synonym for DOUBLE .

Although MySQL also permits (M,D) qualifier, do not use it. (M,D) means that values can be stored with up to M total digits, where D can be after the decimal. Numbers will be rounded twice or truncated; this will cause more trouble than benefit.

Because floating-point values are approximate and not stored as exact values, attempts to treat them as exact in comparisons may lead to problems. Note in particular that a FLOAT value rarely equals a DOUBLE value.

# Bit Value Type

The BIT type is useful for storing bit-field values. BIT(M) allows storage of up to M-bit values where M is in the range of 1 to 64

You can also specify values with bit value notation.

Sometimes it is handy to use ‘shift’ to construct a single-bit value, for example (1 << 7) for 128.

The maximum combined size of all BIT columns in an NDB table is 4096.

# CHAR(n)

CHAR(n) is a string of a fixed length of n characters. If it is CHARACTER SET utf8mb4 , that means it occupies exactly 4*n bytes, regardless of what text is in it.

Most use cases for CHAR(n) involve strings that contain English characters, hence should be CHARACTER SET ascii . ( latin1 will do just as good.)

# DATE, DATETIME, TIMESTAMP, YEAR, and TIME

The DATE datatype comprises the date but no time component. Its format is ‘YYYY-MM-DD’ with a range of ‘1000-01-01’ to ‘9999-12-31’.

The DATETIME type includes the time with a format of ‘YYYY-MM-DD HH:MM:SS’. It has a range from ‘1000-01-01 00:00:00’ to ‘9999-12-31 23:59:59’.

The TIMESTAMP type is an integer type comprising date and time with an effective range from ‘1970-01-01 00:00:01’ UTC to ‘2038-01-19 03:14:07’ UTC.

The YEAR type represents a year and holds a range from 1901 to 2155.

The TIME type represents a time with a format of ‘HH:MM:SS’ and holds a range from ‘-838:59:59’ to ‘838:59:59’.

MySQL максимальный размер varchar — 255. При создании я указал длину 9000. И поместил туда текст такой длины. И он сохранился. Почему не обрезался?

RomaZveR

Спасибо за ответ! А вот эти размеры правильные? Или какие-то из них тоже поменялись?

Где можно посмотреть актуальную информацию по размерам?

RomaZveR

Вся актуальная информация по размерам в документации по каждому типу данных
https://dev.mysql.com/doc/refman/8.0/en/data-types.html
Английский все-же надо подтягивать, без него в мире разработки будет ну очень сложно. Переводите для начала хоть гуглом.

‘varbinary’ => 65535, //аналогично varchar

Rsa97

И внимание на многобайтовые кодировки.
Число в скобках у varchar — число символов. Предел же в 64 килоБАЙТа. Что далеко не всегда одно и то же. Для utf8mb4 вы гипотетически сможете записать от 16к до 65к символов — в зависимости от того, что именно пишете.

Ну и конкретно для varchar важнейшая деталь — 64кб — это не его предельный размер. Это hardcoded лимит на размер одной строки таблицы, включающий в себя все колонки этой таблицы. Невозможно иметь два varchar по 40кб

Типы данных в MySQL

В этой инструкции рассказываем про основные типы данных в MySQL и даем советы, где лучше использовать тот или иной тип.

Эта инструкция — часть курса «MySQL для новичков».

Смотреть весь курс

Введение

При создании таблиц в MySQL для каждого столбца нужно указывать тип данных. Он определяет, какие данные там могут храниться, как будут обрабатываться и сколько места будут занимать. В MySQL все типы данных делятся на несколько классов: числовые типы, символьные, дата/время и так далее. В каждом классе есть несколько типов данных, которые внешне могут быть похожи, но их поведение или принципы хранения отличаются. Важно выбрать правильный тип сразу при создании таблицы, потому что потом готовую структуру и приложения будет сложней переделать.

В этой статье мы расскажем об основных типах данных в MySQL и дадим советы, где лучше использовать тот или иной тип.

Возможности MySQL в «Облачных базах данных»

Числовые типы

Используются для хранения чисел. Бывают целочисленными, с плавающей точкой и с фиксированной точкой.

Целые числа

Хранят только целые числа, без дробной части. Делятся на signed (со знаком) и unsigned (без знака). Типы singed позволяют хранить как положительные, так и отрицательные значения. Типы unsigned хранят только положительные числа, но зато диапазон значений больше. Это может быть полезно в случаях, когда хранимые значения заведомо не могут быть отрицательным. Например, количество товара или идентификатор записи в таблице.

Тип Размер (байт) Диапазон signed Диапазон unsigned
TINYINT 1 -128 … 127 0 … 255
SMALLINT 2 -3 2768 … 32 767 0 … 65 535
MEDIUMINT 3 -8 388 608 … 8388607 0 … 16 777 215
INT 4 2 147 483 648 … 2 147 483 647 0 … 42 94 967 295
BIGINT 8 -2 63 … 2 63 -1 0 … 2 64 -1

Числа с плавающей точкой

Хранят приблизительные значения. Не резервируют определенное количество бит для целочисленной или дробной частей. Поэтому у всех значений в таблице количество до и после запятой будет разным.

Тип Размер (байт) Диапазон
FLOAT 4 -3.402823466E+38 … -1.175494351E-38 и 1.175494351E-38 … 3.402823466E+38
DOUBLE 8 -1.7976931348623157E+308 … -2.2250738585072014E-308 и2.2250738585072014E-308 … 1.7976931348623157E+308

До версии MySQL 8.0.17 эти типы данных поддерживали диапазон unsigned, но он работал не так, как с целыми числами. Беззнаковый диапазон просто запрещал сохранять отрицательные значения, при этом максимальное значение не увеличивалось. Начиная с версии 8.0.17, использование unsigned не рекомендуется и считается устаревшим. В будущих версиях MySQL поддержку беззнакового диапазона для этого типа данных могут вовсе удалить.

Числа с фиксированной точкой

Эти типы данных используются для сохранения заданной точности. Такие числа резервируют определенное количество бит для целочисленной и дробной частей. Независимо от того, насколько большое или маленькое число, оно всегда будет использовать одно и то же количество бит для сохранения каждой части. Эти типы данных подходят для случаев, когда важна точность, например, деньги.

В MySQL для хранения чисел с фиксированной точкой используются типы DECIMAL(M,D) и NUMERIC(M,D), но по факту это синонимы. Можно использовать любой из этих типов, результат будет одинаковым. В таких столбцах максимально можно хранить до 65 чисел вместе с целочисленной и дробной частями.

Символьные (строковые)

Символьные типы используются для хранения текстов. Есть два основных типа: CHAR и VARCHAR. С точки зрения пользователя они выглядят похоже, но MySQL хранит и обрабатывает их по-разному.

  • CHAR хранит строку фиксированной длины до 255 символов. Если длина вставляемой записи меньше, то MySQL автоматически дополняет значение пробелами. Например, если мы указали тип CHAR(10) и сохранили строку «Привет», то по факту в БД будет храниться строка «Привет » (обратите внимание на четыре пробела в конце строки).

Кажется, что это лишняя трата места. Но если во всех ваших записях хранятся строки примерно одной длины, то тип CHAR будет очень производительным. Например, его можно использовать для хранения хешей, у которых длина всегда одинакова.

  • VARCHAR хранит строки переменной длины до 65 535 символов. Причем в памяти хранится именно та длина, которая была указана при создании. VARCHAR занимает меньше места, чем CHAR, но подвержен фрагментации и из-за этого может проигрывать в скорости обработки данных.

Текстовые и бинарные

Текстовые (TEXT) и бинарные (BLOB) типы данных используются для хранения больших объемов текста или двоичных данных. Эти типы похожи, но отличаются по способу хранения и обработки внутри MySQL.

  • BLOB обрабатывается как двоичные данные. В нем не хранится набор символов, а операции сортировки и сравнения основаны на числовых значениях байтов.
  • TEXT обрабатывается как символьные строки. В нем хранится именно набор символов, а значения сортируются и сравниваются на основе сопоставления набора символов..

Текстовые типы отлично подходят для хранения больших текстов: статей, докладов и так далее. А бинарные типы могут хранить любые файлы или мультимедиа-контент.

Тип Размер (байт) Макс. размер символов
TINYTEXT / TINYBLOB 255 255
TEXT / BLOB 65 535 65 535
MEDIUMTEXT / MEDIUMBLOB 16 777 215 2 24 -1
LONGTEXT / LONGBLOB 4 294 967 295 2 32 -1

Кажется, что типы TINYTEXT и TEXT похожи на CHAR и VARCHAR. Но разница в том, что MySQL не умеет индексировать текстовые и бинарные типы и не может использовать индексы для сортировки.

Дата/время

Типы данных, которые позволяют работать с датой и временем.

Тип Размер (байт) Описание
DATE 3 Только дата в формате YYYY-MM-DD. Допустимые значения от 1000-01-01 до 9999-12-31
DATETIME 8 Дата и время в формате YYYY-MM-DD HH:MM:SS. Допустимые значения от 1000-01-01 00:00:00 до 9999-12-31 23:59:59
TIMESTAMP 4 Дата и время. Хранится в виде количества секунд, прошедших с 1 января 1970 года по гринвичу. Занимает в два раза меньше места, чем тип DATETIME. Но при этом диапазон ограничен значениями от 1970-01-01 00:00:01 до 2038-01-09 03:14:07
TIME 3 Только время в формате HH:MM:SS. Допустимые значения от 00:00:00 до 23:59:59
YEAR(N) 1 Только год в формате YYYY или YY. Допустимые значения от 1901 до 2155 или от 70 до 69 (1970 — 2069)

Это относительно новый тип данных, который появился в MySQL версии 5.7.8. Он позволяет нативно хранить и обрабатывать данные в JSON-формате.

В отличие от хранения объектов в виде текста, в использовании специального типа данных есть несколько преимуществ:

  1. Валидация JSON-объектов. Если попытаться сохранить неправильный JSON, MySQL сгенерирует ошибку.
  2. Возможность нативно работать с JSON, выбирать и обновлять только отдельные части объектов, а не весь объект целиком.
  3. MySQL сохраняет тип JSON в специальном внутреннем формате. Такой способ более производительный, чем работа с JSON в виде строки.

Составные типы

Строковые типы данных, которые могут хранить значения только из заранее определенного списка. Несмотря на то, что список значений состоит из строк, в самих таблицах хранятся только числа, которые ассоциированы со справочником возможных значений. Поэтому они занимают мало места.

  • ENUM может хранить только одно значение из списка, занимает 1-2 байта.
  • SET может хранить одновременно до 64 значений из списка, занимает от 1 до 8 байт.

Заключение

Мы рассмотрели основные типы данных и полей в MySQL, объяснили разницу между схожими типами. Теперь вы можете создавать свои структуры БД, используя полученные знания.

Varchar 255 сколько символов

The CHAR and VARCHAR types are similar, but differ in the way they are stored and retrieved. They also differ in maximum length and in whether trailing spaces are retained.

The CHAR and VARCHAR types are declared with a length that indicates the maximum number of characters you want to store. For example, CHAR(30) can hold up to 30 characters.

The length of a CHAR column is fixed to the length that you declare when you create the table. The length can be any value from 0 to 255. When CHAR values are stored, they are right-padded with spaces to the specified length. When CHAR values are retrieved, trailing spaces are removed unless the PAD_CHAR_TO_FULL_LENGTH SQL mode is enabled.

Values in VARCHAR columns are variable-length strings. The length can be specified as a value from 0 to 65,535. The effective maximum length of a VARCHAR is subject to the maximum row size (65,535 bytes, which is shared among all columns) and the character set used. See Section 8.4.7, “Limits on Table Column Count and Row Size”.

In contrast to CHAR , VARCHAR values are stored as a 1-byte or 2-byte length prefix plus data. The length prefix indicates the number of bytes in the value. A column uses one length byte if values require no more than 255 bytes, two length bytes if values may require more than 255 bytes.

If strict SQL mode is not enabled and you assign a value to a CHAR or VARCHAR column that exceeds the column’s maximum length, the value is truncated to fit and a warning is generated. For truncation of nonspace characters, you can cause an error to occur (rather than a warning) and suppress insertion of the value by using strict SQL mode. See Section 5.1.11, “Server SQL Modes”.

For VARCHAR columns, trailing spaces in excess of the column length are truncated prior to insertion and a warning is generated, regardless of the SQL mode in use. For CHAR columns, truncation of excess trailing spaces from inserted values is performed silently regardless of the SQL mode.

VARCHAR values are not padded when they are stored. Trailing spaces are retained when values are stored and retrieved, in conformance with standard SQL.

The following table illustrates the differences between CHAR and VARCHAR by showing the result of storing various string values into CHAR(4) and VARCHAR(4) columns (assuming that the column uses a single-byte character set such as latin1 ).

Value CHAR(4) Storage Required VARCHAR(4) Storage Required
» ‘ ‘ 4 bytes » 1 byte
‘ab’ ‘ab ‘ 4 bytes ‘ab’ 3 bytes
‘abcd’ ‘abcd’ 4 bytes ‘abcd’ 5 bytes
‘abcdefgh’ ‘abcd’ 4 bytes ‘abcd’ 5 bytes

The values shown as stored in the last row of the table apply only when not using strict SQL mode ; if strict mode is enabled, values that exceed the column length are not stored , and an error results.

InnoDB encodes fixed-length fields greater than or equal to 768 bytes in length as variable-length fields, which can be stored off-page. For example, a CHAR(255) column can exceed 768 bytes if the maximum byte length of the character set is greater than 3, as it is with utf8mb4 .

If a given value is stored into the CHAR(4) and VARCHAR(4) columns, the values retrieved from the columns are not always the same because trailing spaces are removed from CHAR columns upon retrieval. The following example illustrates this difference:

Values in CHAR , VARCHAR , and TEXT columns are sorted and compared according to the character set collation assigned to the column.

MySQL collations have a pad attribute of PAD SPACE , other than Unicode collations based on UCA 9.0.0 and higher, which have a pad attribute of NO PAD . (see Section 10.10.1, “Unicode Character Sets”).

To determine the pad attribute for a collation, use the INFORMATION_SCHEMA COLLATIONS table, which has a PAD_ATTRIBUTE column.

For nonbinary strings ( CHAR , VARCHAR , and TEXT values), the string collation pad attribute determines treatment in comparisons of trailing spaces at the end of strings. NO PAD collations treat trailing spaces as significant in comparisons, like any other character. PAD SPACE collations treat trailing spaces as insignificant in comparisons; strings are compared without regard to trailing spaces. See Trailing Space Handling in Comparisons. The server SQL mode has no effect on comparison behavior with respect to trailing spaces.

For more information about MySQL character sets and collations, see Chapter 10, Character Sets, Collations, Unicode. For additional information about storage requirements, see Section 11.7, “Data Type Storage Requirements”.

For those cases where trailing pad characters are stripped or comparisons ignore them, if a column has an index that requires unique values, inserting into the column values that differ only in number of trailing pad characters results in a duplicate-key error. For example, if a table contains ‘a’ , an attempt to store ‘a ‘ causes a duplicate-key error.

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *