views:

248

answers:

3

We have a table which has a DATE column d.

I'd like to get all the rows where the d column is greater / lower than some value, regardless of the date.

For example

|       d          |
-------------------
|2009/11/1 15:55:23|
--------------------
|2009/11/2 15:55:23|
--------------------
|2009/11/3 15:55:23|
--------------------
|2009/11/3 17:55:23|
--------------------

For example, If I want all the records marked after 5 PM:

select d 
 from my_table 
where extract( hour from d ) > TO_DATE ('17:00:00','HH24:MI:SS') 

This should return only one record

|2009/11/3 17:55:23|

I don't know if this is the best way to do it, but I get an error on the extract function:

ORA-30076: invalid extract field for extract source 
Cause: The extract source does not contain the specified extract field.

Is there a better way to do this? Whats up with that error? extract only available for sysdate, as in all examples i've found?

Thanks in advance

+2  A: 

Try this:

select d from my_table 
where (d-trunc(d)) > 16/24; 
ar
+2  A: 

How about this?

select d 
from my_table
where to_char(d,'HH24') > '16';
exiter2000
By the way, 'hour' only supported for timestamp type based on google search. Is performance matter for this case? Just curious.
exiter2000
Yes, performance is an issue
Tom
Consider a function-based index on the expression above: `CREATE INDEX my_table_fbi01 on my_table (to_char(date_col, 'HH24'));` However, given your example, performance would probably still be unoptimal. Assuming no variance in the hourly pattern of your date column, you'd still be getting 1/3 of the data back, so an index wouldn't help you there.
Adam Musch
A: 

Don't have an Oracle database to test with at the moment but I think the following should work:

SELECT *
  FROM MY_TABLE t
  WHERE EXTRACT(HOUR FROM CAST(t.D AS TIMESTAMP)) > 16;

But I don't understand why the CAST would be needed as this page says that HOUR is a valid field in a DATE.

Share and enjoy.

Bob Jarvis