Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Best practice for fixed number of strings in MySQL?

Say i have a datatype called "status" as a row in a mysql table. Status can only be a fixed number of strings, say "active", "inactive" and "pending". What datatype is best practice to use?

  • Make another table "statuses" and have an pointer id in my table?
  • Make a php array containing the different statuses and use my status-row as index for the array?
  • Simply letting status be a string containing the current status?
like image 792
Viktor Avatar asked Jan 17 '14 11:01

Viktor


People also ask

What is the best way to store an attribute of large string values in SQL?

We can use varchar(<maximum_limit>) . The maximum limit that we can pass is 65535 bytes.

What can store large string in text type?

The MEDIUMTEXT data object is useful for storing larger text strings like white papers, books, and code backup. These data objects can be as large as 16 MB (expressed as 2^24 -1) or 16,777,215 characters and require 3 bytes of overhead storage.

Can we store paragraph in MySQL?

Assuming you are using ASCII text, you will be able to store 65000 characters in a single row. If your paragraph is 1000 words with each word averaging 6 characters, that's 6000 characters. You will be able to store around 11 paragraphs. If you want to store more information, see MEDIUMTEXT or LONGTEXT .

What is data length in MySQL?

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.


2 Answers

Specifically for exactly that purpose is the ENUM type: http://dev.mysql.com/doc/refman/5.5/en/enum.html

CREATE TABLE ... (
    status ENUM('active', 'inactive', 'pending')
    ...
);
like image 99
deceze Avatar answered Sep 21 '22 12:09

deceze


If the set of statuses is fixed at development time you definitely want to use ENUM. Another case is when possible statuses can be added in runtime. In this case you want to use separated table to store them and foreign key to check that all statuses are valid.

Using simple string for this is a kind of bad practice. E.g. just a minor misspelling in status can break everything related to the particular row.

like image 31
vbo Avatar answered Sep 18 '22 12:09

vbo