SQL Date and Conversion Functions Guide
SQL Date and Conversion Functions Guide
To calculate how many days each employee has worked till today, the DATEDIFF() function can be used. It calculates the difference in days between two dates — the current date (CURDATE()) and the joining_date of each employee. The query is: SELECT name, DATEDIFF(CURDATE(), joining_date) AS days_worked FROM employees;
To round a float to the nearest integer and then convert it to an integer type in SQL, you can use the ROUND() function together with CAST(). For example, to round 45.8973 and convert it, the query is: SELECT CAST(ROUND(45.8973) AS SIGNED) AS rounded_integer;
To retrieve the year each employee joined the company, you can use the YEAR() function in SQL to extract the year from the joining_date column in the employees table. The query would be: SELECT name, YEAR(joining_date) AS joining_year FROM employees;
First, you can convert a string to uppercase using the UPPER() function and then convert it to an unsigned integer using CAST(). For example, to convert '12345', the query is: SELECT CAST(UPPER('12345') AS UNSIGNED) AS numeric_conversion;
To convert a decimal number to a string in SQL, you can use the CAST() function. For example, to convert the decimal 123.456 to a string, the query would be: SELECT CAST(123.456 AS CHAR) AS string_value;
Identifying employees whose birthday falls in the current month can be achieved using the MONTH() function to compare the month part of the birth_date column with the current month from CURDATE(). The query is: SELECT name, birth_date FROM employees WHERE MONTH(birth_date) = MONTH(CURDATE())
To calculate the average of student marks when they are stored as VARCHAR, you need to convert these VARCHAR values to UNSIGNED (or INTEGER) first using CAST(). Then, use the AVG() function to calculate the average. The query would be: SELECT AVG(CAST(marks AS UNSIGNED)) AS average_marks FROM students;
To calculate the difference in days between two dates, January 1, 2025, and December 31, 2025, you can use the DATEDIFF() function in SQL. The query is: SELECT DATEDIFF('2025-12-31', '2025-01-01') AS days_difference;
Using the DATE_ADD() function in SQL allows you to add a specified interval to a date. To add 30 days to the date '2025-06-19', you can use the query: SELECT DATE_ADD('2025-06-19', INTERVAL 30 DAY) AS new_date;
You can use the CONVERT() function in SQL to extract either the date or the time from a DATETIME value. To get only the date, use CONVERT(NOW(), DATE), and to get only the time, use CONVERT(NOW(), TIME). The query is: SELECT CONVERT(NOW(), DATE) AS only_date, CONVERT(NOW(), TIME) AS only_time;