How to add column to database with default - sql

I have a database that I'm trying to add a column to. This column should hold information of the type timestamp, and I want every row to have the same timestamp (the current time) when I'm done.
I currently have tried:
cursor.execute('''ALTER TABLE my_table ADD COLUMN time timestamp DEFAULT ?''', (datetime.datetime.utcnow(),))
Which results in sqlite3.OperationalError: near "?": syntax error.
So then I tried:
cursor.execute(f'''ALTER TABLE my_table ADD COLUMN time timestamp DEFAULT {datetime.datetime.utcnow()}''')
Which results in sqlite3.OperationalError: near "-": syntax error.
Also, doing
cursor.execute(f'''ALTER TABLE my_table ADD COLUMN time timestamp DEFAULT CURRENT_TIMESTAMP''')
results in sqlite3.OperationalError: Cannot add a column with non-constant default.
How can I add the new column and set the values in that column? (Either through DEFAULT, or some other mechanism.)

SQLite does not allow adding a new column with a non-constant value. So this:
alter table my_table add column my_time timestamp default current_timestamp;
... generates error:
Cannot add a column with non-constant default
A simple option would be to recreate the table. Assuming that you have single column called id, that would look like:
create table my_table_new(
id int primary key,
my_time timestamp default current_timestamp
);
insert into my_table_new(id) select id from my_table;
drop table my_table; -- back it up first !
alter table my_table_new rename to my_table;

You can first add the new column and then update every existing row in the table to the desired value:
ALTER TABLE my_table ADD COLUMN time;
UPDATE my_table SET time = CURRENT_TIMESTAMP;

Related

Recreate table from a select and add an extra datetime default column (Snowflake)

I'm having problems creating a table that should be pretty straightforward. The SQL code (Snowflake) is:
create or replace table bank_raw as
select
*,
created_at datetime default current_timestamp()
from bank_raw;
My error is: Syntax error: unexpected 'DEFAULT'. (line 12).
I don't know how I can recreate this table and add this default timestamp column. By the way, I have already created multiple tables from scratch with created_at DateTime default current_timestamp().
Any ideas?
It is possible to define column list definition when using CTAS:
Sample data:
CREATE TABLE bank_raw(id INT, col TEXT);
INSERT INTO bank_raw(id, col) VALUES (1, 'a'), (2,'b');
Query:
CREATE OR REPLACE TABLE bank_raw(id INT,
col TEXT,
created_at datetime default current_timestamp())
AS
SELECT
id, col, CURRENT_TIMESTAMP()
FROM bank_raw;
Output:
SELECT * FROM bank_raw;
DESCRIBE TABLE bank_raw;
Since this is a DML operation not a DDL operation, the default keyword does not apply. You can simply remove it and instead project the column and name it:
create or replace table bank_raw as
select
*,
current_timestamp() as created_at
from bank_raw;
Edit: To enforce a default, you cannot alter a table to add a column with a default value except for sequences. So you'd need to do something like this:
select get_ddl('table','BLANK_RAW');
-- Copy and paste the DDL. Rename the new table,
-- and add the default timestamp:
create or replace table A
(
-- Existing columns here then:
created_at timestamp default current_timestamp
);
You can then do an insert from a select on the table BLANK_RAW. You'll need to specify a column list and omit the CREATED_AT column.

Add a column with the current timestamp to a table in Hive

I'm trying to add a column called tstamp to a table that I've created. The column is to have the current timestamp in the format 'yyyy-MM-dd' populating each row.
I initially created the table from another table (table1) using the statement:
create location2.table2
as (select *
from location1.table1
);
I then used the alter table statement to add a field called tstamp to table2 using the code:
alter table location2.table2
add columns (tstamp date)
and I can see that this has successfully added a column to table2 named tstamp and populated each row of this table as null. I am now trying to insert the current date into every row in the field tstamp but am struggling to do so. I've tried using the insert into statement as:
insert into location2.table2 (tstamp)
values (to_date(current_timestamp()))
but get the error "Expression of type TOK_FUNCTION not supported in insert/values". I then also tried to add just a string and replaced the function with '2019-07-25'. Doing this added a new row to my table with null values in every column except tstamp which had a value '2019-07-25'. I'm now confused as it appears my approach was not the right one for the problem and am unsure where to go from here. Any help would be greatly appreciated.
create location2.table2 as (select current_date as tstamp,* from location1.table1 );

Alter column of type timestamp

I want to update an empty table , which has a column of type timestamp to varbinary(8)
I used the following command
ALTER TABLE Notification ALTER COLUMN RowRevisionID varbinary(8)
and I get and an error
Cannot alter column 'RowRevisionID' because it is 'timestamp'.
How can I change a timestamp column type?
I do not wish to drop the column an add a new one , because that will create a column at the end , and I wish to preserve column order to use this table in an INSERT INTO
You unfortunately cannot make a change to a timestamp column, as the error implies; you are stuck with what you have. Also, each table can only have one timestamp column, so you cannot duplicate the column in any solution.
Your best bet (depending on the size of the table) might be to copy the data into a staging table (using SELECT * INTO MyTempTable FROM OriginalTable syntax to preserve the timestamp values), then drop and recreate the original table with the desired columns in the desired order and reinsert the data, or you could add a new VARBINARY(8) column to the existing table and drop the timestamp column, preserving the original table. There are probably other solutions along the same lines as these, but all will require a new column, rather than an ALTER COLUMN script.
You are looking for:
ALTER TABLE Notification DROP RowRevisionID;
and
ALTER TABLE Notification ADD RowRevisionID varbinary(8) AFTER myOtherColumn;

Changing the data type "varchar'' of a column to "DATE" in SQL/ORACLE

I have a table in a database created in oracle 10G. It contains a column of type 'VARCHAR' and stores date as string in this format-> 'dd-mon-yyyy' eg: '12-aug-2008'. Now I want to change the datatype of this column from VARCHAR to DATE. but when i perfrom this query->
ALTER TABLE sales_order
MODIFY COLUMN delivery_date DATE;
I get following error
ORA-00905: missing keyword
I have also tried :
ALTER TABLE sales_order
ALTER COLUMN delivery_date DATE;
I got the error :
ORA-01735: invalid ALTER TABLE option
However when i try to add a fresh column with DATE datatype it works fine.
example :
ALTER TABLE sales_order
ADD delivery DATE;
So, can anybody suggest me a way to change the datatype without deleting the column and its data.
It's the first one, with a slight modification:
ALTER TABLE sales_order MODIFY (delivery_date DATE);
But I'm not sure that will work for those particular datatypes and it also may not work depending on the current data.
You may find it necessary in that case to:
create a new column X of date type.
populate X based on the old column (may need several passes of data fix-ups to work).
delete old column.
rename X to old column name.
Although its a pretty old question, I'll put my solution here for people seeking for a solution:
Here's my solution and it works perfectly.
ALTER TABLE `sales_order` CHANGE `delivery_date` `delivery_date` DATE;
Thank you
modify a column then syntax is:-
alter table table_name modify column_name datatype;
but when you modify the column datatype column must be empty
Thanks for the hints! This got it for me.
alter table Table_Name
Alter column Column_Name datatype
GO
I too was needing to change from a VARCHAR to a date. I am working in SQL 2008 R2. I have found that if I bring in dates as a char or varchar and then change the type to date or datetime, I can catch time/date problems more easily.
THIS STATEMENT WILL FAIL IF YOUR DATA HAS ANY BAD DATES. (I break the date down into sections to find the bad date so I can correct and then I can alter the column type.)
Alternatively, you could create a new column, in which the data type is DATE. then pass the data in your varchar as a date .then drop your initial column and finally rename your new column to what it was initially...code below.
ALTER TABLE my_table ADD (new_col DATE);
UPDATE my_table SET new_col=TO_DATE(old_col,'MM/DD/YYYY');
ALTER TABLE my_table DROP (old_col);
ALTER TABLE my_table RENAME COLUMN new_col TO old_col;
alter table employee add (DOB varchar(10));
if you add a column with datatype varchar and if you want to modify the datatype of DOB then you can use this command ->
alter table employee modify(DOB date);
Now the table is modified.

mysql automatically store record creation timestamp

Is there some way mysql can store timestamp automatically in a record row whenever that it is created. I was trying to use timestamp(data type) with current_timestamp as default value but then realised this will get updated everytime the record is updated. I just need something that will store create timestamp.
Thanks
Set the DEFAULT constraint to use CURRENT_TIMESTAMP:
CREATE TABLE ...
your_date_column DATETIME DEFAULT CURRENT_TIMESTAMP
...
For an existing table, use the ALTER TABLE statement:
ALTER TABLE your_table
ALTER COLUMN date_column SET DEFAULT CURRENT_TIMESTAMP
Unless you specify a value to for the date_column, the default will be the date & time the INSERT statement was run. NULL and DEFAULT or valid values to use the default constraint otherwise, assuming the column is nullable.
You can get the full details on timestamps in MySQL at https://dev.mysql.com/doc/refman/5.0/en/timestamp-initialization.html.
The point that you care about is that if you define a timestamp column as DEFAULT CURRENT_TIMESTAMP clause and don't have an ON UPDATE clause, the column has the current timestamp for its default value but is not automatically updated.
But be warned. The obvious thing to want to do is to have two timestamp columns, one being the creation time and the other being the last update time. Unfortunately it is a documented MySQL limitation that MySQL does not support this. I have no idea why MySQL has such an odd limitation - no other major database has problems with this common use case.
FYI = "Datetime" is date and time fixed. "Timestamp" is variable date and time-- system time.
So, Have two columns. One Create Col, One Update Col.
The following command will create a hello table
1. id integer
2. create_at with current time.
create table hello (id int, created_at datetime DEFAULT CURRENT_TIMESTAMP);
Create Table myTableName
(
userId int primary key
userJoiningDate TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);
https://www.mysqltutorial.org/mysql-timestamp.aspx
Here is how you can create a column in which the time stamp is recorded when it is created. If you want to know How to update timeStamp each time that row is changed/updated, Check the above link.
SELECT * FROM test WHERE timestamp >= CURDATE() AND timestamp < CURDATE() + INTERVAL 1 DAY ORDER BY timestamp;