They are calculated columns. These columns should not be updated by you, they will always have the value defined based on the data of the other columns. It is a facilitator to access a certain information that is used frequently and would always need to have an expression to get it.
It is possible that she is virtual and the value will be calculated every time you access it. Or it can be stored, where the calculation is done whenever one of the columns used in its formula is updated. Obviously it is faster to access, but it takes up more disk space and memory, since the calculated value gets stored. Each case has a better use.
It is very easy to abuse it. It is useful, but you can live without, always gave.
CREATE TABLE venda (
nome VARCHAR(30),
preco DECIMAL(10, 2),
qtde INT,
total DECIMAL(10, 2) AS (preco * qtde)); //tem seu valor gerado por esta fórmula
I put in the Github for future reference.
It can be very useful for use in indexes that need to be an expression. Documentation (secondary school).
In case any of them are not set (price or Qtde). Does it give any error? Or is it better to set a defualt value for that column?
– Miguel
It gives error, of course, it has to exist. It has no reason and can not put a value default.
– Maniero
Haa ok, I didn’t know, I see the use of it. Thank you
– Miguel
But what’s the difference for a view? We can apply the same formula Qtde*price in a total column . Correct?
– zwitterion
It’s similar, but this is already on the table. A view is for other things too, can make things more complex. Not always need the view, It can be a cannon to kill bird in many cases. If it is stored (don’t ask me why it can’t be virtual, Mysql stuff) you can use the column in an index or other places that the view cannot be applied.
– Maniero