Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Oracle Sql get only month and year in date datatype

Tags:

oracle11g

I want to store only the month and the year in oracle data type.

I have a date like '01-FEB-2010' stored in a column called time_period.

To get only the month and year i wrote a query like

select to_char(time_period,'MON-YYYY') from fact_table;

I go the result as 'FEB-2010' which is fine but the only problem is that it is in varchar datatype.

So I did like

select to_date(to_char(time_period,'MON-YYYY'),'MON-YYYY') from fact_table

and I get 01-FEB-2010. Is it not possible to store only FEB-2010 in the date datatype

like image 886
Anand Sunderraman Avatar asked Jul 21 '11 18:07

Anand Sunderraman


People also ask

How can I get month from date column in SQL?

Use the MONTH() function to retrieve a month from a date/datetime/timestamp column in MySQL. This function takes only one argument – either an expression which returns a date/datetime/ timestamp value or the name of a date/datetime/timestamp column. (In our example, we use the start_date column of date data type).

How do I display a date in YYYY MM DD format in Oracle?

Just use: select to_date(date_value, 'yyyy-mm-dd') as date_value from table; To convert to a date. That's it!

Is there a year function in Oracle?

The YEAR function returns the year part of a value. The argument must be a date, timestamp, or a valid character string representation of a date or timestamp. The result of the function is an integer between 1 and 9 999.


1 Answers

Easiest solution is to create the column using the correct data type: DATE

For example:

  1. Create table:

    create table test_date (mydate date);

  2. Insert row:

    insert into test_date values (to_date('01-01-2011','dd-mm-yyyy'));

To get the month and year, do as follows:

select to_char(mydate, 'MM-YYYY') from test_date;

Your result will be as follows: 01-2011

Another cool function to use is "EXTRACT"

select extract(year from mydate) from test_date;

This will return: 2011

like image 127
davidsr Avatar answered Sep 17 '22 15:09

davidsr