简体   繁体   中英

How to display orders from a specific month and year in SQL (Oracle SqlDeveloper)

I need to display the orders that were in February of 2012.

The date is a DATE data type and I can only figure out how to get it to display it by putting in the full date like 08-FEB-2012.

This is a very small database and is a beginner class. We just started last week.

What I have is:

SELECT cust_id
FROM orders
WHERE order_date = '08-FEB-2012'

There are three orders from February, and I need to display all three of those.

Thanks

The simplest way is to compare the year and month to your desired period:

SELECT cust_id
FROM orders
WHERE TO_CHAR(order_date, 'YYYY-MM') = '2012-02'

In general, though, this precludes the use of indexes. So, it is better to use comparisons with no functions, if performance is at all an issue:

SELECT cust_id
FROM orders
WHERE order_date >= DATE '2012-02-01' AND
      order_date < DATE '2012-03-01';

Notice that this does not use between . In the event that the order date has a time component, the above will work. Using between often means that you will miss times on the last day of the month. In other words, this version works regardless of whether or not order_date has a time component.

select * 
from orders
where order_date between to_date('02/01/2012','MM/DD/YYYY') 
      and to_date('02/29/2012','MM/DD/YYYY') 

FYI, never assume the default date format. It could vary from system to system. Always specify it.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM