Monday, August 16, 2010

Oracle 11g: Using Date Functions

select last_name, (sysdate-hire_date)/7 as weeks
from employees
where department_id=90

Results:
LAST_NAME                 WEEKS                 
------------------------- ----------------------
King                      1208.871435185185185185185185185185185185
Kochhar                   1090.728578042328042328042328042328042328
De Haan                   917.871435185185185185185185185185185185

===> Other queries

select months_between('10-SEP-1980','13-AUG-1980')
from dual

SELECT ADD_MONTHS('10-SEP-1980',6)
FROM DUAL

SELECT NEXT_DAY('10-SEP-1980','FRIDAY')
FROM DUAL

SELECT LAST_DAY('10-SEP-1980')
FROM DUAL

RESULTS:

MONTHS_BETWEEN('10-SEP-1980','13-AUG-1980')
-------------------------------------------
0.9032258064516129032258064516129032258065 

1 rows selected

ADD_MONTHS('10-SEP-1980',6)
-------------------------
10-MAR-81                

1 rows selected

NEXT_DAY('10-SEP-1980','FRIDAY')
-------------------------
12-SEP-80                

1 rows selected

LAST_DAY('10-SEP-1980')  
-------------------------
30-SEP-80                

1 rows selected


===>  SQL Queries ROUND and TRUNC

select round(sysdate,'MONTH')
from dual;

select round(sysdate,'year')
from dual;

select trunc(sysdate,'month')
from dual;

select trunc(sysdate,'year')
from dual;

Note:  Assuming sysdate = '16-AUG-2010'

Results:

ROUND(SYSDATE,'MONTH')   
-------------------------
01-SEP-10                

1 rows selected

ROUND(SYSDATE,'YEAR')    
-------------------------
01-JAN-11                

1 rows selected

TRUNC(SYSDATE,'MONTH')   
-------------------------
01-AUG-10                

1 rows selected

TRUNC(SYSDATE,'YEAR')    
-------------------------
01-JAN-10                

1 rows selected

No comments: