user1544337
user1544337

Reputation:

Get age from the birthday field with type date using SQL

I have a table in a MySQL database with a field of the type date. Herein the birthday of a user is stored. Is there a pure SQL way to select the age in years from the field?

Upvotes: 0

Views: 1088

Answers (2)

Amit Singh
Amit Singh

Reputation: 8109

Try like this...

SELECT
    id,
    Name,
    DateofBirth,
    ((DATEDIFF(Cast((Select Now()) as Date),
    Cast(DateofBirth as Date)))/365) AS DiffDate
from TABEL1

Edit Considereing Fact from Transact Charlie....

 SELECT
        id,
        Name,
        DateofBirth,
        TIMESTAMPDIFF(Year, Cast(DateofBirth as Date),
        Cast((Select Now()) as Date)) AS DiffDate
    from TABEL1

Upvotes: 2

Keren Caelen
Keren Caelen

Reputation: 1466

Stored Proc example:

DATEDIFF(datepart, startdate, enddate)

Easier:

-- Declare Two DateTime Variable
Declare @Date1 datetime 
Declare @Date2 datetime 
-- Set @Date1 with Current Date
set @Date1 = (SELECT GETDATE());
-- Set @Date2 with 5 days more than @Date1
set @Date2 = (SELECT DATEADD(day, 5,@Date1 ))
-- Get The Date Difference
SELECT DATEDIFF(day, @Date1, @Date2) AS DifferenceOfDay

Upvotes: 2

Related Questions