Is This Year a Leap Year? A SQL Solution

Building Logic In SQL

Rahul Beniwal
2 min readJun 8, 2024

Hello Everyone,

I have been working with SQL since the beginning of my backend journey, so I decided to improve both my and your SQL skills by solving simple problems, just as we used to do when learning programming languages like Python and others.

I will use small SQL snippets, run them to show you the output, and then combine all parts to create a complete solution.

Step 1 -> Extracting Current Year

select date_trunc('year',current_date)::date;
2024-01-01

Step 2 -> Extract First Date of Feb and March

select
(date_trunc('year',current_date) + interval '2 month')::date as march_date,
(date_trunc('year',current_date) + interval '1 month')::date as feb_date;
 march_date |  feb_date  
------------+------------
2024-03-01 | 2024-02-01

Step 3 -> Substract Feb 1 from March 1 to get Interval of Days

select march_date - feb_date as days from (
select
(date_trunc('year',current_date) + interval '2 month')::date as march_date,
(date_trunc('year',current_date) + interval '1 month')::date as feb_date
)X ;
 days 
------
29

Step 4-> Use Case When to decide Leap Or Not.

select case 
when ( march_date - feb_date ) = 29
then 'Leap Year'
else 'Non Leap Year'
end from (
select
(date_trunc('year',current_date) + interval '2 month')::date as march_date,
(date_trunc('year',current_date) + interval '1 month')::date as feb_date
)X ;
Leap Year

Conclusion

In this exercise, we’ve demonstrated how to determine if the current year is a leap year using a series of SQL queries. By breaking down the problem into smaller steps, we were able to:

  1. Extract the current year.
  2. Calculate the first dates of February and March.
  3. Determine the number of days between these dates.
  4. Use a CASE statement to decide if the year is a leap year.

You can follow Rahul Beniwal for upcoming articles because I am Planning to post such logic builders daily.

You can also check my other articles.

Decoding Python Magic

17 stories

Beginner Friendly Django

6 stories

Advance Django Tips

11 stories

--

--

Rahul Beniwal
Rahul Beniwal

Written by Rahul Beniwal

I can help you master Python | Backend | System Design | Django | Rust | Computer Science | Databases | Making complex concepts clear and accessible with code

No responses yet