search
Search
Login
Unlock 100+ guides
menu
menu
web
search toc
close
Outline
Comments
Log in or sign up
Cancel
Post
account_circle
Profile
exit_to_app
Sign out
What does this mean?
Why is this true?
Give me some examples!
search
keyboard_voice
close
Searching Tips
Search for a recipe:
"Creating a table in MySQL"
Search for an API documentation: "@append"
Search for code: "!dataframe"
Apply a tag filter: "#python"
Useful Shortcuts
/ to open search panel
Esc to close search panel
to navigate between search results
d to clear all current filters
Enter to expand content preview
icon_star
Doc Search
icon_star
Code Search Beta
SORRY NOTHING FOUND!
mic
Start speaking...
Voice search is only supported in Safari and Chrome.
Navigate to

When to use INT or STRING in MySQL

schedule Aug 12, 2023
Last updated
local_offer
MySQL
Tags
tocTable of Contents
expand_more
mode_heat
Master the mathematics behind data science with 100+ top-tier guides
Start your free 7-days trial now!

When you need to select a data type for what appears to be a number, always think about whether you would need to do any computations with them. For instance, suppose we are deciding whether to make our ZIP code a number or a string.

Sample ZIP Code: 010-1613

Since we do not need to do any arithmetic with the ZIP Code, we can simply choose the data type to be string.

NOTE

In particular, when our ZIP code starts with a 0, MySQL will drop the leading 0 when treating it as an INT. By using a string, we make sure that the 0 in the front remains!

Example

To create a table that stores ZIP code and specify data type of zip_code as VARCHAR:

CREATE TABLE address (
id INT UNSIGNED AUTO_INCREMENT,
zip_code VARCHAR(8),
PRIMARY KEY (id)
);
INSERT INTO address (zip_code) VALUES ('01016');
SELECT * FROM address;
+----+----------+
| id | zip_code |
+----+----------+
| 1 | 01016 |
+----+----------+

If we had specified data type of zip_code as INT:

CREATE TABLE address (
id INT UNSIGNED AUTO_INCREMENT,
zip_code INT,
PRIMARY KEY (id)
);
INSERT INTO address (zip_code) VALUES (01016);
SELECT * FROM address;
+----+----------+
| id | zip_code |
+----+----------+
| 1 | 1016 |
+----+----------+

Notice that the 0 at the start of the ZIP code is dropped.

robocat
Published by Arthur Yanagisawa
Edited by 0 others
Did you find this page useful?
thumb_up
thumb_down
Comment
Citation
Ask a question or leave a feedback...
thumb_up
0
thumb_down
0
chat_bubble_outline
0
settings
Enjoy our search
Hit / to insta-search docs and recipes!