MySQL Forums
Forum List  »  Newbie

Re: CREATE TABLE does not get updated
Posted by: Phillip Ward
Date: February 07, 2023 08:16AM

Barry is correct.
Your second create table is failing (because the table already exists), so the insert is happening against the original table definition, which has only three columns.

create table birthday_1 (id integer primary key, name text, birth_year year); -- OK
insert into birthday_1 values (1, "Rathon" , 1963);                           -- OK 
select * from birthday_1                                                      -- OK 

The above is working fine. Then I add a new Column to the table called "Age") as shown below:

create table birthday_1 (id integer primary key, name text, birth_year year, age int); -- FAILS - Table already exists 
insert into birthday_1 values (1, "Rathon", 1963, 35);                                 -- FAILS - Column count mismatch 
select * from birthday_1                                                               -- OK - but from the original table.

Now to my point ...

Quote

... add a new Column to the table called "Age"

Don't do this.
As a rule, do not store data that can be derived from other data that you already have, especially if it is Date related.

Store the date of birth (which doesn't change) and calculate the age, as and when you need it.

create table birthday_1 
( id integer primary key 
, name varchar( 100 ) 
, date_of_birth date
); 

insert into birthday_1 values ( 1, 'Rathon' , '1963-01-01'); 

create view birthdays_v 
as 
select 
  id
, name
, int( now() - date_of_birth ) age 
from birthday_1 
order by ... 
; 

+----+--------+-----+
| id | name   | age | 
+----+--------+-----+
|  1 | Rathon |  60 | 
+----+--------+-----+

If you try to store the age, then you have to run something that updates it (for everyone that has a birthday) each and every day, without fail and nothing, not even computers, are reliable enough to do that with absolute certainty. The calculation never gets it wrong.

Regards, Phill W.

Options: ReplyQuote


Subject
Written By
Posted
February 06, 2023 12:55PM
Re: CREATE TABLE does not get updated
February 07, 2023 08:16AM


Sorry, you can't reply to this topic. It has been closed.

Content reproduced on this site is the property of the respective copyright holders. It is not reviewed in advance by Oracle and does not necessarily represent the opinion of Oracle or any other party.