본문 바로가기
Issue Note

DATE - [SQL}

by jhleeatl 2024. 4. 1.

While using SQL, I've always found myself confused about date formats when solving problems related to dates. In the content below, I need to filter data for January, but the function I wasn't the best way.

 

 

 

 

SELECT category, sum(sales) 'Total_sales'
from book b inner join book_sales s on b.book_id = s.book_id
WHERE sales_Date BETWEEN '2022-01-01' AND '2022-01-31'
group by 1
order by category

 

 

When entering date functions, I achieved the desired results by using 'where between' function from January 1st to January 31st. However, the code looked messy. Was there any way to make it clear and simple?

 

- Yes there was a way to make it simple

 

SELECT category, sum(sales) 'Total_sales'
from book b inner join book_sales s on b.book_id = s.book_id
where month(sales_date) = 1
group by 1
order by category

 

Using 'Where + month(column) = 1'

 

The expression `WHERE + MONTH(column) = 1` is used to filter records based on the month component of a date column. 

Here's a breakdown of how it works:

- `MONTH(column)`: This is a SQL function that extracts the month from the specified date column.

 

For example, `MONTH('2022-01-15')` would return `1` because it corresponds to January.


- `= 1`: This comparison checks if the month extracted from the column is equal to `1`, indicating January.