UNIT-3
UNIT-3
Date and time functions in SQL are used to manipulate and retrieve date/time values.
Examples include:
o GETDATE() (returns the current date and time)
o DATEADD(interval, value, date) (adds a specific interval to a date)
o DATEDIFF(interval, start_date, end_date) (calculates the difference
between two dates)
o FORMAT(date, format) (formats a date in a specific style)
2. Define string functions and provide examples.
String functions in SQL are used to manipulate text data. Examples:
o UPPER('hello') → returns 'HELLO'
o LOWER('WORLD') → returns 'world'
o LEN('hello') → returns 5 (length of the string)
o SUBSTRING('database', 2, 4) → returns 'atab'
o CONCAT('SQL', ' Server') → returns 'SQL Server'
3. What is the difference between UNION, INTERSECT, and EXCEPT operators?
o UNION combines results from two queries and removes duplicates.
o INTERSECT returns only the common records between two queries.
o EXCEPT returns records from the first query that are not in the second query.
4. Explain the concept of self-joins in SQL.
A self-join occurs when a table is joined with itself. It is useful when comparing rows
within the same table. Example:
This finds employees earning more than the average salary in their department.
This calculates the average salary per department without collapsing rows.
A subquery is a query nested inside another query. It is useful in data analysis for:
FROM employees
SELECT
COUNT(*) AS total_sales,
AVG(amount) AS avg_sale,
MIN(amount) AS min_sale,
MAX(amount) AS max_sale
FROM sales;
3. EXISTS Operator
The EXISTS operator checks if a subquery returns any rows. It’s commonly used for existence
checks in related tables.
SELECT name
FROM customers c
WHERE EXISTS (
);
This retrieves all employees and all departments, even if there’s no match.
Window functions allow aggregations without collapsing rows, useful for rankings, running
totals, etc.