Home Blog Page 5

Common Table Expressions (CTEs) in SQL: Modular and Reusable Query Blocks

0
sql course

Table of Contents

  1. Introduction
  2. What is a Common Table Expression (CTE)?
  3. Why Use CTEs?
  4. Syntax of a CTE
  5. CTE vs Subquery vs View
  6. Multiple CTEs in a Query
  7. Using CTEs with Aggregation
  8. Recursive CTEs – Introduction
  9. Syntax of Recursive CTEs
  10. Recursive CTE Real-World Example: Hierarchies
  11. CTEs with JOIN and GROUP BY
  12. Filtering Data within CTEs
  13. Nested CTEs
  14. CTEs with INSERT, UPDATE, DELETE
  15. Performance Considerations
  16. Readability and Debugging with CTEs
  17. Common Errors and Troubleshooting
  18. Best Practices for Writing CTEs
  19. Real-World Use Cases for CTEs
  20. Summary and What’s Next

1. Introduction

Common Table Expressions (CTEs) offer a way to define temporary result sets that exist only during the execution of a query. They allow for cleaner, more readable, and modular SQL code — especially in complex logic involving recursion, filtering, and aggregation.


2. What is a Common Table Expression (CTE)?

A CTE is a temporary named result set that you define using the WITH clause. It can be referred to just like a table or subquery within the main query.


3. Why Use CTEs?

  • Improves readability of complex queries
  • Encourages query modularity and reuse
  • Enables recursive queries (e.g., hierarchies, graph traversal)
  • Simplifies debugging and testing
  • Supports multi-step transformations

4. Syntax of a CTE

sqlCopyEditWITH cte_name AS (
  SELECT column1, column2
  FROM table_name
  WHERE condition
)
SELECT * FROM cte_name;

CTEs are defined first and then used like a virtual table.


5. CTE vs Subquery vs View

FeatureCTESubqueryView
TemporaryYes (per query)YesNo (persistent)
ReusableYes (in same query)NoYes
SyntaxWITH clauseInside FROM, WHERE, etc.CREATE VIEW
Use caseModular, recursive, readableSimple conditions or filtersReuse logic, access control

6. Multiple CTEs in a Query

You can define multiple CTEs in a single query:

sqlCopyEditWITH sales AS (
  SELECT * FROM orders WHERE status = 'completed'
),
top_customers AS (
  SELECT customer_id, SUM(total) AS total_spent
  FROM sales
  GROUP BY customer_id
)
SELECT * FROM top_customers WHERE total_spent > 5000;

7. Using CTEs with Aggregation

sqlCopyEditWITH department_salary AS (
  SELECT department, AVG(salary) AS avg_salary
  FROM employees
  GROUP BY department
)
SELECT * FROM department_salary WHERE avg_salary > 70000;

This breaks down logic and makes complex queries easier to manage.


8. Recursive CTEs – Introduction

Recursive CTEs allow you to reference the CTE inside itself. They are used for:

  • Traversing hierarchies (e.g., org charts)
  • Generating sequences
  • Working with tree-structured data

9. Syntax of Recursive CTEs

sqlCopyEditWITH RECURSIVE cte_name (columns) AS (
  -- Anchor member
  SELECT ...
  FROM ...
  WHERE ...

  UNION ALL

  -- Recursive member
  SELECT ...
  FROM table
  JOIN cte_name ON ...
)
SELECT * FROM cte_name;

10. Recursive CTE Real-World Example: Hierarchies

employees table:

idnamemanager_id
1RaviNULL
2Sneha1
3Ankit2
sqlCopyEditWITH RECURSIVE employee_hierarchy AS (
  SELECT id, name, manager_id, 1 AS level
  FROM employees
  WHERE manager_id IS NULL

  UNION ALL

  SELECT e.id, e.name, e.manager_id, h.level + 1
  FROM employees e
  JOIN employee_hierarchy h ON e.manager_id = h.id
)
SELECT * FROM employee_hierarchy;

11. CTEs with JOIN and GROUP BY

sqlCopyEditWITH active_orders AS (
  SELECT * FROM orders WHERE status = 'active'
)
SELECT c.name, COUNT(o.id) AS order_count
FROM customers c
JOIN active_orders o ON c.id = o.customer_id
GROUP BY c.name;

12. Filtering Data within CTEs

Apply WHERE clauses inside or outside the CTE, depending on logic needs.

sqlCopyEditWITH sales_2024 AS (
  SELECT * FROM orders WHERE order_date >= '2024-01-01'
)
SELECT * FROM sales_2024 WHERE total > 500;

13. Nested CTEs

CTEs can refer to other CTEs defined earlier:

sqlCopyEditWITH first_cte AS (
  SELECT id, salary FROM employees
),
second_cte AS (
  SELECT id FROM first_cte WHERE salary > 80000
)
SELECT * FROM second_cte;

14. CTEs with INSERT, UPDATE, DELETE

PostgreSQL and SQL Server allow CTEs in DML:

sqlCopyEditWITH recent_orders AS (
  SELECT id FROM orders WHERE order_date >= CURRENT_DATE - INTERVAL '30 days'
)
DELETE FROM orders WHERE id IN (SELECT id FROM recent_orders);

15. Performance Considerations

  • Not all CTEs are materialized; depends on the DBMS
  • Some engines inline CTEs (like subqueries)
  • For large queries, test CTE vs subquery performance
  • Recursive CTEs can be expensive — consider setting depth limits

16. Readability and Debugging with CTEs

CTEs help:

  • Break logic into logical blocks
  • Test individual pieces
  • Reuse temporary results in joins and filters
  • Keep the final query focused and readable

17. Common Errors and Troubleshooting

IssueReason
Invalid reference to CTECTE must be declared before it’s used
Infinite recursion in recursive CTEMissing anchor or stopping condition
Ambiguous columnsAlways alias CTE columns explicitly

18. Best Practices for Writing CTEs

  • Use meaningful CTE names (monthly_sales, latest_orders, etc.)
  • Don’t over-nest — two to three CTEs are ideal for clarity
  • Separate business logic into layers
  • Consider performance tradeoffs on large datasets
  • Use recursive CTEs with depth limits or base case checks

19. Real-World Use Cases for CTEs

  • Organization charts
  • Breadcrumb navigation (categories, menus)
  • Paginated result construction
  • Building step-by-step reporting metrics
  • Reusing filtered datasets across complex joins

20. Summary and What’s Next

Common Table Expressions (CTEs) make your SQL more modular, readable, and maintainable. They’re perfect for breaking down logic and handling hierarchical or recursive data structures — a must-have tool for any serious SQL developer.

Views in SQL: Creating and Querying Virtual Tables

0
sql course

Table of Contents

  1. Introduction
  2. What is a View in SQL?
  3. Benefits of Using Views
  4. Syntax for Creating a View
  5. Querying Data from a View
  6. Updating a View
  7. Rules and Limitations of Updatable Views
  8. Modifying an Existing View
  9. Dropping a View
  10. Using WITH CHECK OPTION
  11. Views vs Tables
  12. Views vs CTEs
  13. Security and Access Control via Views
  14. Performance Considerations
  15. Materialized Views (vs Regular Views)
  16. Real-World Example: Simplifying Joins
  17. Real-World Example: Department-Level Reporting
  18. Best Practices for Working with Views
  19. Common Errors and Troubleshooting
  20. Summary and What’s Next

1. Introduction

SQL views are virtual tables built from queries. They allow you to simplify complex logic, encapsulate business rules, and present data in a structured way — without duplicating actual data.


2. What is a View in SQL?

A view is a saved SQL query that acts like a virtual table. When you select from a view, it runs the underlying query and returns the result set as if you queried a real table.


3. Benefits of Using Views

  • Simplify complex queries
  • Enforce business logic
  • Control user access
  • Reuse logic across applications
  • Improve readability and maintainability

4. Syntax for Creating a View

sqlCopyEditCREATE VIEW view_name AS
SELECT column1, column2
FROM table_name
WHERE condition;

Example:

sqlCopyEditCREATE VIEW active_customers AS
SELECT id, name, email
FROM customers
WHERE status = 'active';

5. Querying Data from a View

sqlCopyEditSELECT * FROM active_customers;

You can use a view just like a table in SELECT, JOIN, WHERE, etc.


6. Updating a View

sqlCopyEditCREATE OR REPLACE VIEW active_customers AS
SELECT id, name
FROM customers
WHERE is_active = 1;

Most SQL dialects support CREATE OR REPLACE to update a view’s definition.


7. Rules and Limitations of Updatable Views

Some views allow updates (INSERT, UPDATE, DELETE) if:

  • Based on a single table
  • No GROUP BY, DISTINCT, or aggregate functions
  • No subqueries or joins

If these rules are violated, the view becomes read-only.


8. Modifying an Existing View

In MySQL and PostgreSQL:

sqlCopyEditCREATE OR REPLACE VIEW view_name AS
-- new query here

In SQL Server:

sqlCopyEditALTER VIEW view_name AS
-- new query here

9. Dropping a View

sqlCopyEditDROP VIEW view_name;

This removes the virtual table from the schema (not the underlying data).


10. Using WITH CHECK OPTION

Prevents updates through a view that would violate its conditions:

sqlCopyEditCREATE VIEW high_salary_employees AS
SELECT * FROM employees
WHERE salary > 100000
WITH CHECK OPTION;

Now, you cannot insert or update a row through this view unless it satisfies salary > 100000.


11. Views vs Tables

FeatureTableView (Virtual Table)
Stores dataYesNo (except materialized views)
ModifiableYesSometimes (updatable views)
Physical storageOn diskNot stored; computed on access
Refresh neededNoNo (unless materialized)

12. Views vs CTEs

FeatureViewCTE (WITH)
PersistentYesNo (temporary for one query)
ReusableAcross queriesOnly in the current query
PerformanceMay benefit from indexingTypically not cached
Ideal forReusable logicTemporary intermediate logic

13. Security and Access Control via Views

Views can limit access to sensitive data:

sqlCopyEditCREATE VIEW employee_public AS
SELECT name, department
FROM employees;

You can grant access to this view without exposing the full table:

sqlCopyEditGRANT SELECT ON employee_public TO analyst_role;

14. Performance Considerations

  • Views don’t store data — each access reruns the query
  • Complex views with joins and filters may slow down queries
  • You can index base tables, but not views
  • Consider materialized views for performance-sensitive cases

15. Materialized Views (vs Regular Views)

Materialized views store data physically:

FeatureRegular ViewMaterialized View
Data storedNoYes
Always freshYes (computed live)No (requires manual/auto refresh)
PerformanceSlowerFaster for large static datasets

16. Real-World Example: Simplifying Joins

sqlCopyEditCREATE VIEW order_summary AS
SELECT o.id, c.name, o.total
FROM orders o
JOIN customers c ON o.customer_id = c.id;

Now query reports using:

sqlCopyEditSELECT * FROM order_summary WHERE total > 500;

17. Real-World Example: Department-Level Reporting

sqlCopyEditCREATE VIEW department_sales AS
SELECT d.name AS department, SUM(o.total) AS total_sales
FROM orders o
JOIN employees e ON o.employee_id = e.id
JOIN departments d ON e.department_id = d.id
GROUP BY d.name;

Use for dashboards or monthly summaries.


18. Best Practices for Working with Views

  • Name views meaningfully (active_users, monthly_sales, etc.)
  • Use WITH CHECK OPTION if enforcing integrity
  • Avoid overly complex views with multiple nested joins
  • Document views as part of schema design
  • Don’t use views as a substitute for indexing or denormalization

19. Common Errors and Troubleshooting

IssueSolution
View not updatingCheck if base table changed or not
Cannot modify data in viewEnsure it’s not based on join/grouped data
Performance is slowSimplify view query or use materialized view
Invalid column in queryUpdate view definition using CREATE OR REPLACE

20. Summary and What’s Next

Views in SQL act as virtual tables, helping you simplify complex logic, protect sensitive data, and write cleaner, reusable queries. Mastering views is essential for maintaining scalable and secure SQL systems.

Using DISTINCT to Remove Duplicates in SQL

0
sql course

Table of Contents

  1. Introduction
  2. What is the DISTINCT Keyword?
  3. Why and When to Use DISTINCT
  4. Syntax of DISTINCT
  5. How DISTINCT Works Internally
  6. DISTINCT on a Single Column
  7. DISTINCT on Multiple Columns
  8. DISTINCT vs GROUP BY
  9. Using DISTINCT with COUNT()
  10. Combining DISTINCT with ORDER BY
  11. Filtering Results After DISTINCT
  12. Case Sensitivity in DISTINCT
  13. Null Values and DISTINCT
  14. Performance Considerations
  15. Real-World Example: Removing Duplicate Emails
  16. Real-World Example: Unique Customer Locations
  17. Common Mistakes to Avoid
  18. Alternatives to DISTINCT
  19. Best Practices for Removing Duplicates
  20. Summary and What’s Next

1. Introduction

When retrieving data from databases, you often encounter duplicate rows — especially when joining tables or aggregating data. SQL’s DISTINCT keyword is a simple yet powerful tool to eliminate duplicates and return only unique values.


2. What is the DISTINCT Keyword?

The DISTINCT keyword in SQL ensures that the result set returns only unique rows by eliminating all duplicates based on the specified columns.


3. Why and When to Use DISTINCT

Use DISTINCT when:

  • You want to remove repeated rows
  • You need a list of unique values from one or more columns
  • You’re avoiding redundancy in dropdowns, reports, or exports
  • You’ve performed a join or union that introduced duplicates

4. Syntax of DISTINCT

sqlCopyEditSELECT DISTINCT column1, column2, ...
FROM table_name;

You can apply it to one or multiple columns.


5. How DISTINCT Works Internally

Under the hood, SQL compares rows after projection (SELECT clause) and removes duplicate rows. The remaining result set is sorted or hashed to identify and eliminate redundancy.


6. DISTINCT on a Single Column

sqlCopyEditSELECT DISTINCT country
FROM customers;

Returns a list of unique countries from the customers table.


7. DISTINCT on Multiple Columns

sqlCopyEditSELECT DISTINCT city, state
FROM customers;

Returns unique city + state combinations.
Rows with the same city but different states are not treated as duplicates.


8. DISTINCT vs GROUP BY

FeatureDISTINCTGROUP BY
PurposeRemove duplicate rowsGroup rows for aggregation
AggregationNot requiredTypically used with aggregation functions
OutputOnly unique rowsOne row per group

Example:

sqlCopyEdit-- DISTINCT
SELECT DISTINCT department FROM employees;

-- GROUP BY
SELECT department FROM employees GROUP BY department;

Both yield similar output — but use GROUP BY for summaries, not deduplication.


9. Using DISTINCT with COUNT()

sqlCopyEditSELECT COUNT(DISTINCT department) FROM employees;

Returns number of unique departments.


10. Combining DISTINCT with ORDER BY

sqlCopyEditSELECT DISTINCT name FROM customers
ORDER BY name;

You can sort results after deduplication.
Note: ORDER BY is applied after DISTINCT.


11. Filtering Results After DISTINCT

You can use WHERE to filter rows before applying DISTINCT:

sqlCopyEditSELECT DISTINCT country FROM customers
WHERE active = 1;

Filters active customers first, then selects distinct countries.


12. Case Sensitivity in DISTINCT

  • In PostgreSQL, DISTINCT is case-sensitive: 'India''india'
  • In MySQL, depends on collation (utf8_general_ci is case-insensitive)

Always be aware of your DBMS collation and character set.


13. Null Values and DISTINCT

  • NULL is treated as a distinct value
  • Multiple NULLs are considered duplicates for deduplication
sqlCopyEditSELECT DISTINCT department FROM employees;

If 3 rows have NULL department, only one NULL is returned.


14. Performance Considerations

  • DISTINCT can be expensive on large datasets
  • Consider indexing columns involved
  • Avoid SELECT DISTINCT * — it scans all columns and rows
  • Use GROUP BY with aggregates if more appropriate

15. Real-World Example: Removing Duplicate Emails

sqlCopyEditSELECT DISTINCT email FROM users;

Removes any repeated email addresses.


16. Real-World Example: Unique Customer Locations

sqlCopyEditSELECT DISTINCT city, state
FROM customers
WHERE country = 'India';

Returns all unique city+state combinations for Indian customers.


17. Common Mistakes to Avoid

MistakeWhy It’s a Problem
DISTINCT with *Expensive, returns unique rows based on all columns
Expecting column-wise deduplicationDISTINCT works row-wise, not per column
Not using aliases in complex queriesCan lead to confusion and redundancy

18. Alternatives to DISTINCT

  • Use GROUP BY if summarizing
  • Use ROW_NUMBER() or RANK() for first/last row per group
  • Use EXISTS or IN in subqueries for presence checks
  • Create temporary tables or views for deduped sets

19. Best Practices for Removing Duplicates

  • Be specific with column selection
  • Apply filters (WHERE) before using DISTINCT
  • Add ORDER BY if result sequence matters
  • Use COUNT(DISTINCT column) for summaries
  • Benchmark performance on large result sets

20. Summary and What’s Next

The DISTINCT keyword in SQL is a simple yet powerful tool to eliminate duplicates from your result set. Whether used on a single column or multiple, it ensures that your output is clean, lean, and logically precise.

Mathematical Functions in SQL: ROUND(), CEIL(), FLOOR(), MOD() and More

0
sql course

Table of Contents

  1. Introduction
  2. Why Mathematical Functions Matter in SQL
  3. Overview of Common SQL Math Functions
  4. ROUND() – Round Numbers
  5. CEIL() or CEILING() – Round Up
  6. FLOOR() – Round Down
  7. MOD() – Modulo (Remainder)
  8. ABS() – Absolute Value
  9. POWER() – Raise to Power
  10. SQRT() – Square Root
  11. EXP() – Exponential
  12. LOG() and LN() – Logarithmic Values
  13. PI() – Return Value of π
  14. RAND() – Generate Random Number
  15. SIGN() – Determine Sign of a Number
  16. TRUNC() – Truncate Decimal Digits (DBMS Specific)
  17. Math Function Nesting (Using Multiple Together)
  18. Real-World Use Case: Financial Rounding
  19. Best Practices for Numeric Calculations in SQL
  20. Summary and What’s Next

1. Introduction

Mathematical functions in SQL enable you to perform numeric operations directly inside queries. Whether you’re calculating tax, rounding prices, or generating random values for sampling, these functions are essential for data analysis and reporting.


2. Why Mathematical Functions Matter in SQL

SQL isn’t just about retrieving data — it’s also about transforming it. Math functions help:

  • Clean and normalize numeric data
  • Create financial calculations
  • Perform statistical analysis
  • Randomize records or simulate data

3. Overview of Common SQL Math Functions

FunctionPurpose
ROUND()Round number to nearest digit
CEIL()Round up
FLOOR()Round down
MOD()Find remainder
ABS()Get absolute value
POWER()Raise to exponent
SQRT()Find square root
RAND()Generate random float

4. ROUND() – Round Numbers

sqlCopyEditSELECT ROUND(123.4567, 2); -- Output: 123.46
SELECT ROUND(123.4567);    -- Output: 123

Syntax: ROUND(number, decimal_places)


5. CEIL() or CEILING() – Round Up

sqlCopyEditSELECT CEIL(4.2); -- Output: 5
SELECT CEILING(-1.3); -- Output: -1

Always rounds up to the next whole number.


6. FLOOR() – Round Down

sqlCopyEditSELECT FLOOR(4.9); -- Output: 4
SELECT FLOOR(-4.9); -- Output: -5

Always rounds down (toward negative infinity).


7. MOD() – Modulo (Remainder)

sqlCopyEditSELECT MOD(10, 3); -- Output: 1
SELECT MOD(-10, 3); -- Output: -1

Used to check divisibility, alternating logic, etc.


8. ABS() – Absolute Value

sqlCopyEditSELECT ABS(-123); -- Output: 123

Removes the sign from the number.


9. POWER() – Raise to Power

sqlCopyEditSELECT POWER(2, 3); -- Output: 8

Calculates base raised to exponent (like ).


10. SQRT() – Square Root

sqlCopyEditSELECT SQRT(25); -- Output: 5

May return NULL or error for negative inputs depending on DBMS.


11. EXP() – Exponential (e^x)

sqlCopyEditSELECT EXP(1); -- Output: ~2.718281828

Useful in scientific or statistical queries.


12. LOG() and LN() – Logarithmic Functions

sqlCopyEditSELECT LOG(100);    -- MySQL: base 10
SELECT LN(100);     -- Natural log (base e)

Logarithmic values are commonly used in scoring systems, ranking, and scientific calculations.


13. PI() – Value of π

sqlCopyEditSELECT PI(); -- Output: 3.14159265358979

Great for geometry-based calculations (e.g., circles, spheres).


14. RAND() – Generate Random Number

sqlCopyEditSELECT RAND(); -- Output: 0.739573 (random float between 0 and 1)

In PostgreSQL: use RANDOM()

sqlCopyEditSELECT RANDOM(); -- Output: random float [0,1)

You can generate a range:

sqlCopyEditSELECT FLOOR(RAND() * 100) AS random_0_to_99;

15. SIGN() – Determine Sign of a Number

sqlCopyEditSELECT SIGN(-10); -- Output: -1
SELECT SIGN(0);   -- Output: 0
SELECT SIGN(10);  -- Output: 1

Useful for categorizing positive, negative, or zero values.


16. TRUNC() – Truncate Decimal Digits

In Oracle and PostgreSQL:

sqlCopyEditSELECT TRUNC(123.4567, 2); -- Output: 123.45

Unlike ROUND(), TRUNC() chops off digits instead of rounding.


17. Math Function Nesting (Using Multiple Together)

sqlCopyEditSELECT ABS(ROUND(-12.345, 1)); -- Output: 12.3

Combining functions gives flexibility in formatting and logic.


18. Real-World Use Case: Financial Rounding

sqlCopyEditSELECT order_id, ROUND(total_amount * 0.18, 2) AS tax_amount
FROM orders;

Calculates 18% tax rounded to 2 decimal places.


19. Best Practices for Numeric Calculations in SQL

  • Always round monetary values to the required precision
  • Use ABS() to guard against negative entries when needed
  • Prefer ROUND() over TRUNC() unless truncation is required
  • Avoid using RAND() without limits in production (for reproducibility)
  • Validate edge cases (e.g., SQRT() of negative, LOG(0)) to avoid errors

20. Summary and What’s Next

Mathematical functions bring power and precision to SQL. Whether you’re rounding prices, calculating scientific values, or generating random data, these functions make numeric manipulation seamless and efficient.

Date & Time Functions in SQL: NOW(), DATEDIFF(), EXTRACT() and More

0
sql course

Table of Contents

  1. Introduction
  2. Importance of Date and Time Functions
  3. Common Use Cases
  4. NOW() – Get Current Date and Time
  5. CURRENT_DATE and CURRENT_TIME
  6. DATEDIFF() – Difference Between Dates
  7. TIMESTAMPDIFF() in MySQL
  8. EXTRACT() – Pull Out Parts of Date/Time
  9. DATE_PART() in PostgreSQL
  10. DATE_ADD() and DATE_SUB()
  11. INTERVAL Keyword Explained
  12. DATE_TRUNC() – Truncate to Granularity
  13. TO_CHAR() – Format Date into String
  14. TO_DATE() – Convert String to Date
  15. AGE() in PostgreSQL
  16. Real-World Example: Calculate Age
  17. Real-World Example: User Signups This Month
  18. Best Practices for Handling Date/Time
  19. Common Errors and Gotchas
  20. Summary and What’s Next

1. Introduction

Working with date and time values is a crucial part of SQL development. Whether it’s filtering records by date, computing durations, or formatting timestamps for reports, SQL offers a rich set of functions for handling temporal data.


2. Importance of Date and Time Functions

These functions allow you to:

  • Calculate age, durations, or due dates
  • Extract specific parts of a date (year, month, etc.)
  • Format date outputs for reports
  • Filter rows using dynamic timestamps

3. Common Use Cases

  • Find all orders in the last 30 days
  • Calculate how many days a user has been active
  • Format YYYY-MM-DD into human-readable form
  • Compare two timestamps or dates

4. NOW() – Get Current Date and Time

sqlCopyEditSELECT NOW(); -- Returns current date and time

Returns a TIMESTAMP including date and time.

Related Functions:

sqlCopyEditSELECT CURRENT_DATE; -- Only the date
SELECT CURRENT_TIME; -- Only the time

5. CURRENT_DATE and CURRENT_TIME

sqlCopyEditSELECT CURRENT_DATE;  -- Example: '2025-05-12'
SELECT CURRENT_TIME;  -- Example: '14:25:34.000000'

These return server time, not the client’s local time.


6. DATEDIFF() – Difference Between Dates

sqlCopyEditSELECT DATEDIFF('2025-05-12', '2025-04-01'); -- Output: 41

Returns number of days between two dates (MySQL).
In SQL Server: DATEDIFF(unit, start_date, end_date)

sqlCopyEditSELECT DATEDIFF(DAY, '2025-04-01', '2025-05-12'); -- Output: 41

7. TIMESTAMPDIFF() in MySQL

Allows unit-based difference:

sqlCopyEditSELECT TIMESTAMPDIFF(YEAR, '2000-01-01', CURDATE()); -- Age in years
SELECT TIMESTAMPDIFF(MONTH, '2024-01-01', '2025-05-01'); -- Output: 16

8. EXTRACT() – Pull Out Parts of Date/Time

sqlCopyEditSELECT EXTRACT(YEAR FROM order_date) AS order_year
FROM orders;

Other fields: MONTH, DAY, HOUR, MINUTE, SECOND, WEEK, DOW (day of week)


9. DATE_PART() in PostgreSQL

Equivalent to EXTRACT():

sqlCopyEditSELECT DATE_PART('month', CURRENT_DATE); -- Output: 5

10. DATE_ADD() and DATE_SUB()

MySQL Example:

sqlCopyEditSELECT DATE_ADD('2025-01-01', INTERVAL 30 DAY);  -- Output: '2025-01-31'
SELECT DATE_SUB(NOW(), INTERVAL 1 MONTH);       -- Output: one month ago

Used for date arithmetic.


11. INTERVAL Keyword Explained

Used to specify a unit of time:

sqlCopyEditSELECT NOW() + INTERVAL 1 DAY;    -- Tomorrow
SELECT NOW() - INTERVAL 7 HOUR;   -- 7 hours ago

Units: SECOND, MINUTE, HOUR, DAY, MONTH, YEAR, etc.


12. DATE_TRUNC() – Truncate to Granularity

(PostgreSQL)

sqlCopyEditSELECT DATE_TRUNC('month', NOW()); -- Returns first day of current month

Useful for monthly or weekly grouping.


13. TO_CHAR() – Format Date into String

(PostgreSQL)

sqlCopyEditSELECT TO_CHAR(NOW(), 'YYYY-MM-DD');   -- '2025-05-12'
SELECT TO_CHAR(NOW(), 'Month DD, YYYY'); -- 'May     12, 2025'

Enables human-friendly date formatting.


14. TO_DATE() – Convert String to Date

sqlCopyEditSELECT TO_DATE('2025-05-12', 'YYYY-MM-DD');

Use when storing or comparing string-based dates.


15. AGE() in PostgreSQL

Calculates age or duration between two timestamps:

sqlCopyEditSELECT AGE(NOW(), '1990-01-01'); -- Output: '35 years 4 months 11 days'

16. Real-World Example: Calculate Age

sqlCopyEditSELECT name,
  TIMESTAMPDIFF(YEAR, birthdate, CURDATE()) AS age
FROM users;

For PostgreSQL:

sqlCopyEditSELECT name, AGE(NOW(), birthdate) AS age
FROM users;

17. Real-World Example: User Signups This Month

sqlCopyEditSELECT COUNT(*) 
FROM users 
WHERE signup_date BETWEEN DATE_TRUNC('month', CURRENT_DATE)
                      AND CURRENT_DATE;

In MySQL:

sqlCopyEditSELECT COUNT(*)
FROM users
WHERE signup_date >= DATE_FORMAT(NOW(), '%Y-%m-01');

18. Best Practices for Handling Date/Time

  • Always store timestamps in UTC if possible
  • Avoid mixing data types (e.g., comparing date with string)
  • Use appropriate functions for timezone-aware systems
  • Use indexes on timestamp columns for performance
  • Beware of timezone drift if comparing across systems

19. Common Errors and Gotchas

IssueSolution
Comparing string with dateUse CAST() or store as date properly
Using NOW() inside index filterAvoid in indexed queries — may not optimize
DATEDIFF() returns negative valueFlip argument order
Wrong granularity in groupingUse DATE_TRUNC() or FORMAT() properly

20. Summary and What’s Next

SQL provides powerful functions for working with date and time values. From calculating differences to formatting and extracting parts of a date, mastering these tools is essential for writing intelligent, time-aware queries.