What is the correct way to choose the types of columns? [closed]

1

I always see tables as follows. Ex:

CREATE TABLE posts (
    id int(11) NOT NULL,
    titulo varchar(255) NOT NULL,
    autor varchar(255) NOT NULL,
    conteudo text NOT NULL,
    data varchar(11) NULL,
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

Why this? Putting VARCHAR at all is safer than putting the type corresponding to the field?

    
asked by anonymous 18.12.2016 / 14:13

2 answers

4

Every type of column in a table should be as suitable as possible to the need.

If you have a date, you probably need to use a type that has date semantics. If you are going to use quantities, you must use a numeric type. If you are going to just describe an information, no matter how it is composed, it will use a text type. And so on.

In fact varchar is usually preferred because the bulk of the information in a database is usually only descriptive.

In the example if you use varchar instead of date or something similar, you will have difficulty sorting the data in chronological order, depending on the format, you may have difficulty presenting, it will be an extreme complication to make calculations with this date (calculate expiration, days of delay, data range, etc.

If what you want to know is because people's codes are usually varchar , I'd say it's because today most people who decide to develop software have no idea what they're doing. They do not know what to do, and linearize everything . Because they do not know what to use when, they use one thing that "works". He does not even notice the confusion he's going to cause later.

And worse, often these people end up teaching others to do wrong too. So you should be wary of everything you read on the internet. It may seem like the right thing in the world and be wrong, after all who is looking for information in general does not know if it is right.

This kind of thing happens because people try to learn from top to bottom (they usually never get down there). It does not work! The right thing to do is to learn from the bottom up, like in school. You will learn a more basic concept, and from it goes to more complex ones that depend on the previous concepts.

And they often continue to do wrong because of the effect Dunning-Kruger . >

    
18.12.2016 / 14:49
1

The "right way" is the one that corresponds to the purpose you give the storage. It is recommended to use numeric types for numbers, and varchar for string and text. Understand: If you store everything in varchar and then need to do cross-data calculations you may have an unpleasant surprise, or an inaccurate answer. See this .

    
18.12.2016 / 14:46