MySQL numeric functions
MySQL string functions
MySQL Date/Time functions
MySQL aggregate functions
MySQL flow control functions
The YEAR()
function in MySQL is used to return the year of a specified date.
Here's a step-by-step guide on how to use the YEAR()
function:
Step 1: Connect to MySQL.
Connect to your MySQL server using the MySQL command-line client or any other MySQL interface you prefer. Here is a basic command to connect to MySQL from the command line:
mysql -u root -p
Step 2: Select the database.
Once you're logged in, select the database where you want to use the YEAR()
function:
USE mydatabase;
Replace mydatabase
with the name of your database.
Step 3: Use the YEAR()
function.
The basic syntax of the YEAR()
function is as follows:
YEAR(date)
Here, date
is the date from which to extract the year.
For example, to get the year of a specific date:
SELECT YEAR('2023-05-14');
This will return the year of the date '2023-05-14'. The result will be an integer representing the year, in this case, 2023.
Step 4: Exit MySQL.
When you're done, you can exit the MySQL interface by typing exit
at the MySQL prompt and then pressing Enter
.
That's it! You now know how to use the YEAR()
function in MySQL. This function is particularly useful when you need to group, filter, or sort data by year.
How to use YEAR function in MySQL:
YEAR
function in MySQL is used to extract the year from a date or datetime expression.YEAR(date_expression);
Get year from date in MySQL:
YEAR
function allows you to obtain the year from a specific date.SELECT YEAR('2023-01-15') AS extracted_year;
MySQL YEAR function examples:
YEAR
function in MySQL to extract years from different dates.SELECT YEAR('2023-01-15') AS extracted_year; -- Returns 2023 SELECT YEAR('2023-02-28') AS extracted_year; -- Returns 2023
Extracting the year from a datetime field in MySQL:
YEAR
function can also be used to extract the year from a datetime field.SELECT YEAR('2023-01-15 14:30:00') AS extracted_year;
Handling NULL values with MySQL YEAR function:
YEAR
function may return NULL for certain date expressions. You can handle NULL values using the COALESCE
function.SELECT COALESCE(YEAR('2023-01-15'), 0) AS extracted_year;
MySQL YEAR function with date calculations:
YEAR
function allows for more complex operations.SELECT YEAR(NOW()) - YEAR('1990-01-01') AS years_since_1990;
Formatting year in MySQL queries:
SELECT CONCAT('Year: ', YEAR('2023-01-15')) AS formatted_result;
Extracting only the last two digits of the year in MySQL:
RIGHT
function.SELECT RIGHT(YEAR('2023-01-15'), 2) AS last_two_digits;
MySQL YEAR vs EXTRACT differences:
YEAR
function extracts the year from a date or datetime expression, while EXTRACT
allows more flexibility by extracting various components (e.g., year, month, day) based on a specified unit.SELECT EXTRACT(YEAR FROM '2023-01-15') AS extracted_year;