Skip to content

Instantly share code, notes, and snippets.

@abenevaut
Last active June 22, 2024 12:13
Show Gist options
  • Save abenevaut/4f48d4e849f469b65b47 to your computer and use it in GitHub Desktop.
Save abenevaut/4f48d4e849f469b65b47 to your computer and use it in GitHub Desktop.
Get age of user
-- Not enough precise /!\
DATEDIFF(CURRENT_DATE, `users`.`birthday`)/365 AS age
-- Working fine
DATE_FORMAT(FROM_DAYS(DATEDIFF(NOW(), `users`.`birthday`)), "%Y")+0 AS age
@abenevaut
Copy link
Author

abenevaut commented Jun 22, 2024

create table users(
  id int primary key,
  username text,
  birthday DATE
);

insert into users 
  values
    (1,'Taniya','1994-12-01'),
    (2,'Bernard','1995-06-01'),
    (3,'JL','1996-10-01'),
    (4,'Seb','1997-09-01'),
    (5,'Lucie','1998-07-01'),
    (6,'Joyce','1999-08-01'),
    (7,'Chloe','2000-01-01'),
    (8,'Nathan','2001-03-01')
;

select  
  DATEDIFF(CURRENT_DATE, `users`.`birthday`)/365 AS age1,
  DATE_FORMAT(FROM_DAYS(DATEDIFF(NOW(), `users`.`birthday`)), "%Y")+0 AS  age2
  from  users;

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment