Skip to content
Advertisement

Calculating age derived from current date and DOB

I’m trying to calculate the age of a user based on the current year and his year of birth, but something in my syntax appears to be incorrect and I can’t spot it.

Why is this incorrect?

Advertisement

Answer

Use AS:

Generated columns in MySQL

< type> [ GENERATED ALWAYS ] AS ( < expression> ) [ VIRTUAL|STORED ] [ UNIQUE [KEY] ] [ [PRIMARY] KEY ] [ NOT NULL ]
[ COMMENT ]

If you are using SQL Server there is no need for datatype in computed columns:

LiveDemo

EDIT:

For calculating age better use:

Your code for 2014-12-31 and 2015-01-01 will return 1 year, but really it has 0.

User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement