What is difference between char and varchar - mysql

CREATE TABLE IF NOT EXISTS `test` (
`id` bigint(20) NOT NULL AUTO_INCREMENT,
`country` varchar(5) NOT NULL,
`state` char(5) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=1 ;
I tried following query to insert data
INSERT INTO `test`.`test` (`id` ,`country` ,`state`)
VALUES (NULL , 'south-india', 'Gujarat');
When I execute above query It will shows following warning
Warning: #1265 Data truncated for column 'country' at row 1
Warning: #1265 Data truncated for column 'state' at row 1
I found Reference that VARCHAR is variable-length.CHAR is fixed length.
Then what you mean by
VARCHAR is variable-length.
CHAR is fixed length.

VARCHAR(5) will use at most 5 characters of storage, while CHAR(5) will always use exactly 5.
For a field holding a person's name, for example, you'd want to use a VARCHAR, because while on average someone's name is usually short, you still want to cope with the few people with very long names, without having to have that space wasted for the majority of your database rows.

As you said varchar is variable-length and char is fixed. But the main difference is the byte it uses.
Example.
column: username
type: char(10)
if you have data on column username which is 'test', it will use 10 bytes. and it will have space.
'test______'
Hence the varchar column will only uses the byte you use. for 'test' it will only use 4 bytes. and your data will be
'test'
THanks.

As you mentioned VARCHAR is variable-length. CHAR is fixed length.
when you say
Varchar(5) and if the data you store in it is of length 1, The
remaining 4 byte memory space will be used by others. example: "t"
on the other hand
Char(5) and if the data you store in it is of length 1, The remaining
4 byte memory space cant be used. The 4 byte will end up not used by
any other data. example: "t____" here ____ is the unused space.

Related

limit length of string, set max length of string column

I want to limit usernames to 16 characters long.
I thought this would work:
create table user(id int unsigned auto_increment not null, username tinytext(16) not null, primary key (id));
but it doesn't
You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '(16) not null, primary key (id))' at line 1
That is what varchar() is for:
create table user(
id int unsigned auto_increment not null,
username varchar(16) not null,
primary key (id)
);
Review syntax of data types here: https://dev.mysql.com/doc/refman/5.7/en/string-type-overview.html
TINYTEXT does not accept a length argument.
TEXT does accept a length argument, but it doesn't do what you think it does. It just changes the data type to one of the flavors of TEXT that is the smallest type that will allow at least the length you request.
As stated in the manual page:
An optional length M can be given for this type. If this is done, MySQL creates the column as the smallest TEXT type large enough to hold values M characters long.
So TEXT(16) will create the column as TINYTEXT because that's the least of the family of TEXT types that will hold strings of length 16. Another example is if you specify TEXT(2000000), it would promote the column to MEDIUMTEXT.
mysql> create table t ( t1 text(16), t2 text(2000000) );
Query OK, 0 rows affected (0.04 sec)
mysql> show create table t\G
*************************** 1. row ***************************
Table: t
Create Table: CREATE TABLE `t` (
`t1` tinytext,
`t2` mediumtext
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4
Notice the columns have automatically been changed, and they no longer have length specifiers.
This means the TINYTEXT column will still allow up to 255 bytes, and the MEDIUMTEXT column will allow up to 16MB. The text length specified is not a limit, but a guideline for which type is needed.
If you really want to limit inputs to 16 characters, then use VARCHAR(16).

MYSQL not accepting whitespaces

I have created a table in mysql as:
CREATE TABLE `test1` (
`age` int(12) NOT NULL DEFAULT '0',
`name` varchar(20) NOT NULL DEFAULT '',
`gender` varchar(10) DEFAULT NULL,
PRIMARY KEY (`age`,`name`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
I am inserting 2 rows in this table as:
insert into test1 values(1,'user1','m');
insert into test1 values(1,'user1 ','m');
In the second row insertion, I want my 'name' filed to have white space.
But when I run the second query it gives error of primary key violation.
Is there a way I can insert white spaces in the table having primary key also?
Values in VARCHAR columns are variable-length strings. You can declare
a VARCHAR column to be any length between 1 and 255, just as for CHAR
columns. However, in contrast to CHAR, VARCHAR values are stored using
only as many characters as are needed, plus one byte to record the
length. Values are not padded; instead, trailing spaces are removed
when values are stored. (This space removal differs from the SQL-99
specification.)
You probably want lpad, rpad, or space
If you are developing for html you can replace the white space with a different character and once you query the you replace the character with the white space, you can even use " " that will insert an empty space into your html browser
If you need to insert the values with white spaces you can use name nvarchar(20) instead of varchar(20)
Note :
The exact problem is that for SQL norm if you compare two string with different lengths the first thing done by SQL is to make them to the same length by adding trailing spaces.
So, if your query compares string1 'a' and string2 'a ', string1 is first converted to 'a ' then compared to string2, and now the two string are the same.
Finally and fortunately, if the field is a UNIQUE INDEX or Primary key it is not possible to have 'a' and 'a ' in two different rows. If it is not a UNIQUE INDEX or primary key field, then you will have to use RTRIM, LTRIM and LEN function with an extra character like LEN('a'+'#')=2 and LEN('a '+'#')=3.
Len('a') and len('a ') give ...1
What you must keep in mind is :
Remove trailing spaces before insertion ! It will be the better option
I have seen character or string primary key systems speeded up radically when converted to Integer.

What does size limit on MySQL index mean?

I have a table created like so:
CREATE TABLE `my_table` (
`id` int(10) unsigned NOT NULL AUTO_INCREMENT,
`info` varchar(50) DEFAULT NULL,
`some_more_info` smallint(5) unsigned NOT NULL
PRIMARY KEY (`id`),
KEY `my_index` (`some_more_info`,`info`(24)),
) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8
My question is about the second key called my_index. What does the "(24)" size limit mean? The actual size of the column is 50, but the index is only 24 characters.
Does this mean that MySQL indexes only the first 24 characters of the column info?
In short, yes, the first 24 characters are taken into consideration to build the BTree index. Indexing limits are assigned to text types such as varchar and text, as they don't affect numeric precision.
Yes.
The entire description about the index length can be found here:
http://dev.mysql.com/doc/refman/5.0/en/create-index.html
Prefix lengths are given in characters for nonbinary string types and
in bytes for binary string types. That is, index entries consist of
the first length characters of each column value for CHAR, VARCHAR,
and TEXT columns, and the first length bytes of each column value for
BINARY, VARBINARY, and BLOB columns.
Also you create query has/had some extra ,'s.

Is there any point in using CHAR if you have a VARCHAR in the same table?

I just read the accepted answer of this question, which left me with this question.
Here's a quote from that answer:
"But since you tagged this question with MySQL, I'll mention a MySQL-specific tip: when your query implicitly generates a temporary table, for instance while sorting or GROUP BY, VARCHAR fields are converted to CHAR to gain the advantage of working with fixed-width rows. If you use a lot of VARCHAR(255) fields for data that doesn't need to be that long, this can make the temporary table very large."
As I understand it, the advantage of CHAR is that you get fixed-width rows, so doesn't a VARCHAR in the same table mess that up? Are there any advantages of using CHAR when you have a VARCHAR in the same table?
Here's an example:
Table with CHAR:
CREATE TABLE address (
id INT UNSIGNED NOT NULL AUTO_INCREMENT,
street VARCHAR(100) NOT NULL,
postcode CHAR(8) NOT NULL,
PRIMARY KEY (id)
);
Table without CHAR:
CREATE TABLE address (
id INT UNSIGNED NOT NULL AUTO_INCREMENT,
street VARCHAR(100) NOT NULL,
postcode VARCHAR(8) NOT NULL,
PRIMARY KEY (id)
);
Will the table with CHAR perform any better than the table without CHAR, and if so, in what situations?
"VARCHAR" basically sets a maximum length for the field and only stores the data that is entered into it, thus saving on space. The "CHAR" type has a fixed length, so if you set "CHAR(100)", 100 character worth of space will be used regardless of what the contents are.
The only time you will gain a speed advantage is if you have no variable length fields in your record ("VARCHAR", "TEXT", etc.). You may notice that Internally all your "CHAR" fields are changed to "VARCHAR" as soon as a variable length field type is added, by MySQL.
Also "CHAR" is less efficient from a space storage point of view, but more efficient for searching and adding. It's faster because the database only has to read an offset value to get a record rather than reading parts until it finds the end of a record. And fixed length records will minimize fragmentation, since deleted record space can be reused for new records.
Hope it helps.

What's wrong with my MySQL code here in varchar(max) line?

create table snippet(
id int not null auto_increment,
primary key(id),
idlanguage int not null,
foreign key(idlanguage) references language(id),
iduser int not null,
foreign key(iduser) references user(id),
title varchar(200) not null,
content varchar(max) not null,
rating int,
creationdate datetime
);
I'm getting an error at line 9 near 'max)' according to PHPMyAdmin.
VARCHAR(MAX) is an MS SQL Server extension to the SQL language -- it does not exist in mysql. Put a number there and you will be golden.
I don't think that "max" is a valid value for the maximum number of character that can be put in your content column : you should specify a numerical value.
But note that varchar has a limited maximum length (see the varchar page in the MYSQL's manual for the details) -- which means it might not be the best data-type for a "content" column.
A possibibly better solution might be to use one of the TEXT data-type :
...
content TEXT not null,
...
TEXT columns can contain strings that are a lot longer than varchar ; for more informations, see 10.4.3. The BLOB and TEXT Types.