changing character into timestamp - postgresql

I have two columns (date character varying, time character varying) in table VM. Now I want to merge these two columns and change the type as a timestamp. can anyone help me out to do this?
Or else
I want to separate data based on the year (2017, 2018). I used substring(date, '2018') command but it replies with 2017 data showing NULL instead of 2017 along with 2018 data.

You didn't tell us what exactly the contents of that table is, but something like this should work:
Add a new timestamp column (and please find a better name than "timestamp" or ts_column for it)
alter table the_table add ts_column timestamp;
Then you need to update the data
update the_table
set ts_column = to_timestamp(concat("date", ' ', "time"), 'yyyy-mm-dd hh24:mi:ss')
where "date" is not null;
The above assumes that the date stored in the column named "date" and the time stored in the column named "time" are formatted as ISO date and time values. If they are not, you need to adjust the parameter to the to_timestamp() function. For details on the format mask, please see the manual
Then drop the old columns:
alter table the_table drop "date", drop "time";
To extract the year from a date or timestamp column, use the extract function:
where extract(year from ts_column) = 2018
Note that the above will not be able to use an index on ts_column to speed up the query.
An alternative way of writing is:
where ts_column >= date '2018-01-01'
and ts_column < date '2019-01-01';
which would be able to use an index on ts_column

Related

How to convert varchar to timestamp in postgreSQL?

I have data as following, But the column type is Varchar:
2019-09-28T23:59:59.52Z
I assume 52 here is milli seconds, If so..
I would like to convert it as following and change the column type to timestamp:
2019-09-28 23:59:59.52
Can someone let me know how I can convert in postgreSQL?
EDIT:
I can see data in table as (since the column type is varchar):
2019-09-28T23:59:59.52Z
Instead, I want data in the table to be shown as:
2019-09-28 23:59:59 ( and may be .52, if possible)
I need to change the column type to timestamp as well, I guess, Please help with that too.
Answer:
Tim has provided a solution, You can follow that.
But, In my case, It is prod env, So, I have just changed the type using:
ALTER TABLE my_table ALTER COLUMN my_column TYPE TIMESTAMP USING my_column::timestamp without time zone;
Thanks
Your timestamp string literal is already in a format which can be directly cast in Postgres:
SELECT '2019-09-28T23:59:59.52Z'::timestamp; -- 2019-09-28 23:59:59.52
As a test, let's add one day to make sure it's working:
SELECT '2019-09-28T23:59:59.52Z'::timestamp + interval '1 day';
-- 2019-09-29 23:59:59.52
If you want to actually add a new timestamp column using string data from another column, then try:
ALTER TABLE yourTable ADD COLUMN new_ts TIMESTAMP;
UPDATE yourTable SET new_ts = old_ts::timestamp;
ALTER TABLE yourTable DROP COLUMN old_ts;
ALTER TABLE yourTable RENAME COLUMN new_ts TO old_ts; -- optional
The last ALTER statement is optional if you want the new bona fide timestamp column to bear the same name as the old text timestamp column.

how to coalesce timestamp with not null constraint postgres

insert into employee(eid,dojo) SELECT
14,coalesce(to_char(dojo,'dd-mm-yyyy'),'')
from employee;
I have to insert into table by selecting it from table,my column dojo has not null constraint and timestamp doesn't allow '' to insert please provide an alternate for this if timestamp is null from select query
Your current query has severals problems, two of which I think my answer can resolve. First, you are trying to insert an empty string '' to handle NULL values in the dojo column. This won't work, because empty string is not a valid timestamp. As others have pointed out, one solution would be to use current_timestamp as a placeholder.
Another problem you have is that you are incorrectly using to_char to format your timestamp data. The output of to_char is a string, and the way you are using it would cause Postgres to reject it. Instead, you should be using to_timestamp(), which can parse a string and return a timestamp. Something like the following is what I believe you intend to do:
insert into employee (eid, dojo)
select 14, coalesce(to_timestamp(dojo, 'DD/MM/YYYY HH:MI:SS PM'), current_timestamp)
from employee;
This assumes that your timestamp data is formatted as follows:
DD/MM/YYYY HH:MI:SS PM (e.g. 19/2/1995 12:00:00 PM)
It also is not clear to me why you are inserting back into the employee table which has non usable data, rather than inserting into a new table. If you choose to reuse employee you might want to scrub away the bad data later.
you can use some default date value like 1st jan 1900 or now()
your query should be like
insert into employee(eid,dojo) SELECT
14,coalesce(to_char(dojo,'dd-mm-yyyy'),now())
from employee;
There is no such thing as a non-null yet blank timestamp. NULL = blank.
There is literally nothing you can do but store a valid timestamp or a null. Since you have a non-null constraint your only option is to pick a default timestamp that you consider "blank".
Using a hard coded date to indicate a blank value is a terrible terrible terrible idea btw. If it is blank, remove the not null constraint, make it null and move on.
I am not trying to be condescending but I do not think you understand nulls. See here
https://en.wikipedia.org/wiki/Null_(SQL)

PostgreSQL - aggregating data by date from datetime field

I have data over time for particular users and timestamp of the form 2013-11-23 16:00:00-05 - there's by minute by minute date for each user and corresponding usage value.
So the table has values: user_ID, localminute, usage.
I am trying to aggregate usage at a day wise level, what i did so far is below s but I was looking for an easier way to do it without creating the dummy column date_event:
alter table tablename add column date_event date
update table set date_event = date(localminute)
select sum(use), date_event from tablename group by date_event
My question is about how I can extract date from timestamp and aggregate in a single query. Thanks for any help!
Just cast it to a date:
select sum(use), localminute::date
from tablename
group by localminute::date;
or using standard SQL:
select sum(use), cast(localminute as date)
from tablename
group by cast(localminute as date);

how to insert the current system date and time in oracle10g database

I have created a table with a column date_time type (varchar2 (40) ) but when i try to insert the current system date and time the doesnt work it gives error (too many values). please tell me what's wrong with the insert statement.
create table HR (type varchar2 (20), raised_by number (6), complaint varchar2 (500), date_time varchar2(40))
insert into HR values ('request',6785,'good morning',sysdate,'YYYY/MM/DD:HH:MI:SSAM')
The immediate cause of the error is that you have too many values, as the message says; that is, more elements in your values clause than there are columns. It is better to explicitly list the column names to avoid future problems and confusion, so you're really doing this:
insert into HR (type, raised_by, complaint, date_time)
values ('request',6785,'good morning',sysdate,'YYYY/MM/DD:HH:MI:SSAM')
... sp you have four columns, but five values. You're trying to insert the current date/time as a string so you would need to use the to_char() function:
insert into HR (type, raised_by, complaint, date_time)
values ('request',6785,'good morning',
to_char(sysdate,'YYYY/MM/DD:HH:MI:SSAM'))
But it is bad practice to store a date (or any other structured data, such as a number) as a string. As the documentation notes:
Each value manipulated by Oracle Database has a data type. The data
type of a value associates a fixed set of properties with the value.
These properties cause Oracle to treat values of one data type
differently from values of another. For example, you can add values of
NUMBER data type, but not values of RAW data type.
If you use a string then you can put invalid values in. If you use a proper DATE data type then you cannot accidentally put an invalid or confusing value in. Oracle will also be able to optimise the use of the column, and will be able to compare values safely and efficiently. Although the format you're using is better than some, using string comparison you still can't easily compare two values to see which is earlier, so you can't properly order by the date_time column for example.
Say you inserted two rows with values 2013/11/15:09:00:00AM and 2013/11/15:08:00:00PM - which is earlier? You need to look at the AM/PM marker to realise the first one is earlier; with a string comparison you'd get it wrong because 8 would be sorted before 9. Using HH24 instead of HH and AM avoids that, but would still be less efficient than a true date.
If you need to store a date with a time component you can use the DATE data type, which has precision down to the second; or if you need fractional seconds too then you can use TIMESTAMP. Then your table and insert would be:
create table HR (type varchar2 (20), raised_by number (6),
complaint varchar2 (500), date_time date);
insert into HR (type, raised_by, complaint, date_time)
values ('request',6785,'good morning',sysdate);
You can still get the value in the format you wanted for display purposes as part of a query:
select type, raised_by, complaint,
to_char(date_time, 'YYYY/MM/DD:HH:MI:SSAM') as date_time
from HR
order by date_time;
TYPE RAISED_BY COMPLAINT DATE_TIME
-------------------- ---------- -------------------- ---------------------
request 6785 good morning 2013/11/15:08:44:35AM
Only treat a date as a string for display.
You can use TO_DATE() or TO_TIMESTAMP or To_char() function,
insert into HR values ('request',6785,'good morning',TO_DATE(sysdate, 'yyyy/mm/dd hh24:mi:ss'))
insert into HR values ('request',6785,'good morning',TO_TIMESTAMP(systimestamp, 'yyyy/mm/dd hh24:mi:ss'))
sysdate - It will give date with time.
systimestamp - It will give datetime with milliseconds.
To_date() - Used to convert string to date.
To_char() - Used to convert date to string.
Probably here you have to use To_char() because your table definition have varchar type for date_time column.
Use TIMESTAMP datatype for date_time. And while inserting use the current timestamp.
create table HR (type varchar2(20), raised_by number(6), complaint varchar2(500), date_time timestamp);
insert into HR values ('request',6785,'good morning', systimestamp);
For other options: http://psoug.org/reference/timestamp.html

how to insert a time in oracle 10g database

I want to insert date and time in oracle database, I have created the table with columns
create table myadmin
( employe_id number(5),
supervisor Varchar2(20),
department Varchar2(20),
action Varchar2(20),
sdate date,
stime date)
While inserting the values below it gives an error. Please tell me how to insert the time ?
insert into myadmin
( employe_id,supervisor,department,action,sdate,stime) values
(83,'gaurav','helpdesk','pick','23-jan-2013','09:43:00');
You have to use keyword to_date for date insert in oracle like this.
to_date('23-01-2013','dd-mm-yyyy')
Basically you have to use keyword to_date('your date','your date format').
You can also add date and time together if you want and it would be something like this
to_date('23-01-2013 09:43:00','dd-mm-yyyy hh24:mi:ss')
A date in Oracle always has a date part and a time part. Having date and time in two separate columns only makes sense, if it can occur that date is null and time is not. (And still, you could set date to an improbable value like 1.1.0001 then.)
However, if you want to stick to those two separate fields, then make your string a datetime with the to_date function specifying the format used:
insert into myadmin
( employe_id,supervisor,department,action,sdate,stime) values
(83,'gaurav','helpdesk','pick',to_date('23-01-2013','dd-mm-yyyy'), to_date('09:43:00', 'hh24:mi:ss'));