How to calculate age in SQL [duplicate]
When attempting to calculate age of teacher I’m receiving an error ‘CURDATE’ is not a recognized built-in function name., I’m new to SQL and learning on my own so i can’t quite figure out where I’m going wrong with this query. any hints would be appreciated. SAMPLE DATA HERE
SELECT t.TeacherID, t.TeacherFName, t.TeacherLName,DOB FROM TEACHER t INNER JOIN CLASS c ON t.TeacherID = c.TeacherID WHERE TIMESTAMPDIFF(YEAR, DOB, CURDATE())>=60;
-Question example A program coordinator is interested in knowing the age of their teachers who teach all classes, and to find this info he needs the teacherID, teachers first and last name -Table below
CREATE TABLE TEACHER ( teacherNo int primary key, teacherFName varchar (25) NOT NULL, teacherLName varchar (25) NOT NULL, teacherPhone nvarchar (10), DOB datetime, Salary money ) CREATE TABLE CLASS ( classNo int primary key, classDay date, teacherID int, NoOfStudents int, )
Also add what database are you usingSome Sql commands are no commons to different databases, for example: MySQL uses CURDATE(), PostgresSQL CURRENT_DATE(), SQLLite DATE(‘now’) and SQL Server GETDATE() Source: datacamp.com/community/blog/sql-differences
3 Answers 3
The first problem with your query is that TIMESTAMPDIFF() is a MySQL function, not a SQL Server function. And so is CURDATE() . It is tempting to replace it with DATEDIFF() , but they do different things.
The correct logic for what you want is:
That is, the date of birth is before today minus 60 years.
Why doesn’t DATEDIFF() work? It counts the number of year boundaries between two dates. This year is 2021. So anyone born in 1961 would evaluate to 60. However, today is May 23rd, so only people born on or before May 23rd, 1961 are really 60 years old.
As a note: TIMESTAMPDIFF() works a bit differently in MySQL so it is better for calculating ages correctly. However, I still recommend the simple date comparison approach, even in that database.
In SQL Server you should use DATEDIFF() function.
SELECT t.TeacherID, t.TeacherFName, t.TeacherLName, DATEDIFF(year, t.DOB, getdate()) AS Age FROM TEACHER t INNER JOIN CLASS c ON t.TeacherID = c.TeacherID
If I was born on the 31st December 2021 and today’s date was 1st January 2022 your query would say I was 1 year old rather than 1 day
In sql server you need to use getdate() or CURRENT_TIMESTAMP instead of curdate() and datediff instead of timestampdiff
SELECT t.TeacherID, t.TeacherFName, t.TeacherLName,DOB FROM TEACHER t INNER JOIN CLASS c ON t.TeacherID = c.TeacherID WHERE datediff(YEAR, DOB, getdate())>=60;
datediff(YEAR, DOB, getdate()) counts a year if year is changed. That means datediff(YEAR, ’31 dec 2020′, ‘1 jan 2021’) will return 1. So above query will consider any teacher born in 1961 as 60 years old. If you want to calculate exact 60 years, that means if you are executing the query today and only teachers born in 23-may-1961 at exactly same time or earlier should be considered as 60 and above then as Gordon suggested please use below query.
SELECT t.TeacherID, t.TeacherFName, t.TeacherLName,DOB FROM TEACHER t INNER JOIN CLASS c ON t.TeacherID = c.TeacherID WHERE dob<=DATEADD(YEAR, -60, GETDATE())
Above query will subtract exactly 60 years from current date with exact time to calculate 60 years. If you want to compare date only regardless of born time then you can consider below query.
SELECT t.TeacherID, t.TeacherFName, t.TeacherLName,DOB FROM TEACHER t INNER JOIN CLASS c ON t.TeacherID = c.TeacherID WHERE dob<=dateadd(YEAR, -60, cast(getdate()as date))
SQL Підручник
SQL - це стандартна мова для зберігання, обробки та отримання даних в базах даних.
Наш підручник по SQL навчить вас використовувати SQL в: MySQL, SQL Server, MS Access, Oracle, Sybase, Informix, Postgres та інших системах баз даних.
Приклади в кожному розділі
За допомогою нашого онлайн-редактора SQL ви можете редагувати SQL інструкції і натискати кнопку, щоб переглянути результат.
Приклад
Клікніть на кнопку "Спробуйте самі", щоб побачити, як вона працює.
SQL Вправи
SQL Приклади
Вчіться на прикладах! Цей підручник доповнює всі пояснення пояснюючими прикладами.
SQL Перевірочна Вікторина
Перевірте ваші SQL навички на W3Schools!
SQL Довідники
На нашому сайті W3Schools українською ви знайдете повний довідник по ключовим словам і функціям:
SQL Типи даних
Типи і діапазони даних для Microsoft Access, MySQL та SQL Server.
Пройдіть SQL іспит - отримайте свій Сертифікат!
Онлайн Сертифікація W3Schools
Ідеальне рішення для професіоналів, яким необхідно збалансувати роботу, сім’ю та кар’єру.
Більше 25 000 сертифікатів уже видано!
ПАЛІТРА КОЛЬОРІВ
НА СЕРВЕРІ
Зв’язок з адміном
Якщо ви хочете повідомити про помилку, а також внести пропозиції про роботу сайту, додати оголошення, рекламу на сайт і т.п., відправте адміну електронного листа на email:
Підручники
Довідники
Приклади
Вебсертифікати
Цей сайт оптимізований для навчання і тестування. Приклади можуть бути спрощені для поліпшення читання і базового розуміння. Навчальні посібники, посилання і приклади постійно переглядаються, щоб уникнути помилок, але ми не можемо гарантувати повну правильність і працездатність всього контенту. Використовуючи цей сайт, ви погоджуєтеся з тим, що прочитали й прийняли умови використання, cookie і політику конфіденційності.
Також доступна версія сайту W3Schools англійською мовою.
Copyright 1999-2024 by Refsnes Data. All Rights Reserved.
Сайт створений і працює на фреймворку W3.CSS.
Ви можете використовувати інші авторитетні ресурси по навчанню веб-розробці та програмуванню:
W3Schools | MDNWebDocs | Udemy | Codecademy | Coursera | edX | Khan Academy | Skillshare | FreeCodeCamp | MicrosoftLearn | HyperSkill | Udacity | Code.org | SoloLearn | IBMDeveloper | CodeWars | WHATWG | W3C | Prometheus | Ed-Era
SQL Tutorial
SQL is a standard language for storing, manipulating and retrieving data in databases.
Our SQL tutorial will teach you how to use SQL in: MySQL, SQL Server, MS Access, Oracle, Sybase, Informix, Postgres, and other database systems.
Examples in Each Chapter
With our online SQL editor, you can edit the SQL statements, and click on a button to view the result.
Example
Click on the "Try it Yourself" button to see how it works.
SQL Exercises
SQL Examples
Learn by examples! This tutorial supplements all explanations with clarifying examples.
SQL Quiz Test
Test your SQL skills at W3Schools!
My Learning
Track your progress with the free "My Learning" program here at W3Schools.
Log in to your account, and start earning points!
This is an optional feature. You can study at W3Schools without using My Learning.
SQL References
At W3Schools you will find a complete reference for keywords and function:
SQL Data Types
Data types and ranges for Microsoft Access, MySQL and SQL Server.
SQL Exam - Get Your Diploma!
Kickstart your career
Get certified by completing the course
COLOR PICKER
Report Error
If you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail:
Top Tutorials
Top References
Top Examples
Get Certified
W3Schools is optimized for learning and training. Examples might be simplified to improve reading and learning.
Tutorials, references, and examples are constantly reviewed to avoid errors, but we cannot warrant full correctness
of all content. While using W3Schools, you agree to have read and accepted our terms of use, cookie and privacy policy.