I'm trying to extract the year of a date in order to calculate the age of user. The 'birthday' is a string format in YYYY-MM-DD.
Here is my code
SELECT username, birthday, CURRENT_DATE(),
EXTRACT(YEAR FROM CURRENT_DATE()) - EXTRACT(YEAR FROM birthday) as age ,
FROM
`user`;
My SQL table 'user':
username | birthday |
---|---|
Name1 | 1999-05-11 |
Name2 | 1999-05-11 |
But the "EXTRACT(YEAR FROM birthday)" don't work and I don't find where is the problem.
The complete error :
No matching signature for function EXTRACT for argument types: DATE_TIME_PART FROM STRING. Supported signatures: EXTRACT(DATE_TIME_PART FROM DATE); EXTRACT(DATE_TIME_PART FROM TIMESTAMP [AT TIME ZONE STRING]); EXTRACT(DATE_TIME_PART FROM DATETIME); EXTRACT(DATE_TIME_PART FROM TIME); EXTRACT(DATE_TIME_PART FROM INTERVAL) at [2:41]
CodePudding user response:
Use below
select username, birthday, current_date(),
extract(year from current_date()) - extract(year from date(birthday)) as age ,
from `user`;
Note date(birthday)
to fix a "problem"