Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between storing integer or string in database table

I'm concern about performance, engineering and readability. Let's say I have a blog, and every post has its status: published (4), pending review (2), draft (1). What is the recommended to store these information in the status column?

status        <======= storing status as string
========
pending
published
draft

status        <======= storing status as integer
========
2
4
1

Also, if we should store integer, should we refrain from storing running integer: 1, 2, 3, 4, 5, as opposed to storing a ^2 integer: 2, 4, 8, 16, 32?

Many thanks.

like image 931
Victor Avatar asked Nov 09 '11 12:11

Victor


People also ask

Should database IDS be string or int?

You are doing the right thing - identity field should be numeric and not string based, both for space saving and for performance reasons (matching keys on strings is slower than matching on integers).

How are strings stored in database?

To store strings in a database, use OpenROAD to add them to a table. OpenROAD automatically creates a special string storage table, called ii_stored_strings.

What type of data should not store in database?

Finally, you shouldn't store credit card information in your database unless you absolutely need to. This includes credit card owner names, numbers, CVV numbers, and expiration dates.

Should the database store a postal code as an integer?

ZIP codes should not be stored as integers. If you were going to incorrectly store a ZIP code as an integer, you'd store the value 7601 and then need to know when you display it that you need to add in the leading 0.


2 Answers

I think your best bet for faster performance, less storage space, and readability is to use CHAR(1)--(p)ublished, pending (r)eview, and (d)raft. You can validate that data with either a CHECK constraint or a foreign key reference.

CHAR(1) takes substantially less space than an integer. It's directly readable by humans, so it doesn't need a join to understand it. Since it's both smaller and immediately readable, you'll get faster retrieval than a join on an integer even on a table of tens of millions of rows.

like image 110
Mike Sherrill 'Cat Recall' Avatar answered Oct 22 '22 09:10

Mike Sherrill 'Cat Recall'


Storing as a string:

  • wastes space
  • takes longer to read/write
  • is more difficult to index/search
  • makes it more difficult to guarantee validity (there's nothing to prevent someone inserting arbitrary strings)

Ideally, you should use an enum type for this sort of thing, if your database supports it.

like image 37
Oliver Charlesworth Avatar answered Oct 22 '22 09:10

Oliver Charlesworth