Assignment: Date Functions &
Conversion Functions in SQL
🔶 Part A: Date Functions
Q1. Display the current date and time:
```sql
SELECT NOW() AS current_datetime;
```
Q2. Insert employee records and perform date-based operations:
```sql
CREATE TABLE employees (
id INT,
name VARCHAR(50),
joining_date DATE,
birth_date DATE
);
INSERT INTO employees VALUES
(1, 'Ali', '2021-05-10', '1998-06-15'),
(2, 'Sara', '2020-08-20', '1997-08-25'),
(3, 'Ahmed', '2023-01-12', '2000-01-05'),
(4, 'Ayesha', '2019-11-30', '1995-06-20'),
(5, 'Bilal', '2022-03-01', '1999-03-10');
```
a) Retrieve the year of joining:
```sql
SELECT name, YEAR(joining_date) AS joining_year FROM employees;
```
b) Calculate how many days each employee has been working till today:
```sql
SELECT name, DATEDIFF(CURDATE(), joining_date) AS days_worked FROM employees;
```
Q3. Employees whose birthday is in the current month:
```sql
SELECT name, birth_date
FROM employees
WHERE MONTH(birth_date) = MONTH(CURDATE());
```
Q4. Difference in days between two dates using DATEDIFF():
```sql
SELECT DATEDIFF('2025-12-31', '2025-01-01') AS days_difference;
```
Q5. Add 30 days to a given date using DATE_ADD():
```sql
SELECT DATE_ADD('2025-06-19', INTERVAL 30 DAY) AS new_date;
```
🔶 Part B: Conversion Functions
Q6. Create table students and convert marks to INTEGER:
```sql
CREATE TABLE students (
id INT,
name VARCHAR(50),
marks VARCHAR(10)
);
INSERT INTO students VALUES
(1, 'Junaid', '85'),
(2, 'Fatima', '90'),
(3, 'Kashif', '78'),
(4, 'Hira', '88'),
(5, 'Zain', '92');
-- a) Convert marks to INTEGER and calculate average
SELECT AVG(CAST(marks AS UNSIGNED)) AS average_marks FROM students;
```
Q7. Convert a decimal number into string using CAST():
```sql
SELECT CAST(123.456 AS CHAR) AS string_value;
```
Q8. Use CONVERT() to get only date or time from a DATETIME:
```sql
SELECT
CONVERT(NOW(), DATE) AS only_date,
CONVERT(NOW(), TIME) AS only_time;
```
Q9. Use CAST() to round a float to integer:
```sql
SELECT CAST(ROUND(45.8973) AS SIGNED) AS rounded_integer;
```
Q10. Convert string to uppercase and then to another data type:
```sql
SELECT
CAST(UPPER('hello world') AS CHAR) AS uppercase_string,
CAST(UPPER('12345') AS UNSIGNED) AS numeric_conversion;
```