Fetching column values based on SYSDATE

I have a table wchih has 2 columns. The definition is

CREATE TABLE LOGGING_T
(
  TSTAMP  DATE,
  LINE    VARCHAR2(300)
)
TABLESPACE OPERATIONS
MONITORING
/

The colulmn TSTAMP has values like 30-NOV-11, 29-NOV-11 ... and so on. Now i am doing this query

select * from LOGGING_T where TSTAMP >= (SYSDATE - 1)

The current system date is 01-DEC-11. Ideally, the above statement should return records which has TSTAMP = 30-NOV-11 since i am doing SYSDATE-1 which would be 30-NOV-11. But it isn't fetching those records. Why?

However, if i do this query

select * from LOGGING_T where TSTAMP >= (SYSDATE - 2)

Then it fetches records who TSTAMP is 30-NOV-11. Am i doing something wrong in this simple date operation?

Answers


A DATE contains time of day as well as the date.

If SYSDATE was 2011-12-01 1:18:00 PM then SYSDATE-1 would be 2011-11-30 1:18:00 PM.

Are the rows you are expecting to find from November 30th before or after the time element?

If you don't care about the time, and only want to filter based on the date, you can use TRUNC():

select * 
  from LOGGING_T 
 where TRUNC(TSTAMP) >= TRUNC(SYSDATE - 1);

You'll may or may not want to make sure both sides of your comparison operator are TRUNC()ed because TRUNC() will just force the time element of the date to be midnight.

select to_char(trunc(sysdate), 'YYYY-MM-DD HH:MI:SS PM') 
  from dual;

NOW
----------------------
2011-12-01 12:00:00 AM

The value SYSDATE has the time component as well. Most probably the date in your database also has the time component.

Change your query to :

select * from LOGGING_T where TSTAMP >= TRUNC(SYSDATE - 1)

to see all records which were logged from 00:00 yesterday.

To see the actual timecomponents, use to char.

SQL> select sysdate from dual;

SYSDATE
---------
01-DEC-11

  1* select to_char(sysdate,'DD-Mon-YYYY HH24:MI:SS') date1 from dual
SQL> /

DATE1
--------------------
01-Dec-2011 16:29:01

Need Your Help

Is using the reference to a control in a background worker thread safe?

c# winforms thread-safety backgroundworker

Let's say that I have a dictionary of controls and strings. If I run a background worker, is it thread safe to use the control reference to access the string corresponding to the control?

how to test a method of models with rspec and factory

ruby-on-rails testing rspec factory-girl shoulda

I'm newbie on rails and I have to write tests for existing rails apps with 'Rspec','shoulda' and 'factory girl' gems. I can test non specific tests like validates_presence_of: something with 'sholda'

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.