how to embed a function to column in PostgreSQL - sql

I'm new to SQL and PostgreSQL and I'm trying to find a way to create a new table in database where a column will automatically calculate a pre-defined function with data from other columns.
Specifically I want a LOG table with
TIME_IN | TIME_OUT | DURATION columns
where the DURATION column shows the result of (=TIME_OUT - TIME_IN)
Of course this can be done with running a query but I'm trying to figure out if it's possible
to have it pre-defined so whenever running SELECT * FROM log
the table will load up with duration value already calculated according to updated data in IN / OUT columns.

This can be done using a generated column, e.g.:
create table log
(
id integer primary key generated always as identity,
time_in timestamp,
time_out timestamp,
duration interval generated always as (time_out - time_in) stored
);
Another option would be to create a view:
create view log_with_duration
as
select id,
time_in,
time_out,
time_out - time_in as duration
from log;

Related

SQLite how to add a new column into existing table with conditionn

I am doing Google Analysis Certification. I have a problem which I prefer to solve with SQL.
I am calculated the ride_length here.
SELECT
ride_id,
round((julianday(ended_at) - julianday(started_at)) * 1440) as ride_length
FROM
all_divvy_tripdata
I want to join the ride_length back into the 'all_divvy_tripdata' table. at the same time, ride_id must match.
What can I do? I have tried this for a day, and still not able to figure it out.
I have tired 'insert into', but it will just add more row into the table
I suggest actually not storing this derived result in your original table. This is because should the underlying data change, the calculation could be invalidated and would have to be recomputed. I suggest using a generated column here:
CREATE TABLE all_divvy_tripdata (
ride_id INTEGER PRIMARY KEY,
started_at TEXT,
ended_at TEXT,
ride_length INT GENERATED ALWAYS AS (round(1440*(julianday(ended_at) - julianday(started_at)))) VIRTUAL,
-- other columns here
);
If you really wanted to persist the ride_length, you would have to create a new column and then update:
UPDATE all_divvy_tripdata
SET ride_length = round(1440*(julianday(ended_at) - julianday(started_at)));

Partition key failing error for postgres table

ERROR: no partition of relation "test_table" found for row DETAIL:
Partition key of the failing row contains (start_time) = (2021-04-25
00:00:00). SQL state: 23514
I am inserting a data where i have a column start time (2021-04-25 00:00:00)
This is my Schema
CREATE TABLE test_table (
start_time timestamp NULL,
)
PARTITION BY RANGE (start_time);
This sounds as if you have no partition-tables defined for this table.
You might need something like this:
CREATE TABLE test_table_2021 PARTITION OF test_table
FOR VALUES FROM ('2021-01-01') TO ('2022-01-01');
After you defined this partition for your partitioned table, you should be able to insert the data (as long as start_time is anywhen in 2021).
See the docs: https://www.postgresql.org/docs/current/ddl-partitioning.html

SQL - Multiple fields are updated instead of one

I have four columns: ID, STARTTIME, ENDINGTIME and DURATION.
The table is created with:
CREATE TABLE tableName (
ID INTEGER NOT NULL PRIMARY KEY AUTO_INCREMENT,
STARTTIME TIMESTAMP,
ENDINGTIME TIMESTAMP,
DURATION TIME);
The ID is an auto_increment column. Then I've the code for inserting a new STARTTIME:
INSERT INTO tableName(STARTTIME) VALUES(CURRENT_TIMESTAMP);
Secondly I've the code for updating the row with the biggest ID to set the ENDINGTIME:
SET #latestInsertID = (SELECT MAX(ID) FROM tableName);
UPDATE tableName SET ENDINGTIME=(CURRENT_TIMESTAMP) WHERE ID=#latestInsertID;
Now I can execute both (all three) queries without getting an exception and the first query works totally fine (as I expected). But the last query updates (from the row I wanted to update) the ENDINGTIME as well as the STARTTIME. Why doesn't it just update the ENDINGTIME?
Thank you for every solution!
Use DATETIME instead of TIMESTAMP (MWE)
Here's why:
The timestamp field is generally used to define at which moment in time a row was added or updated and by default will automatically be assigned the current datetime when a record is inserted or updated. The automatic properties only apply to the first TIMESTAMP in the record; subsequent TIMESTAMP columns will not be changed.
Educated guess. Column is defined as:
CREATE TABLE tablename(
-- ...
STARTTIME TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
);
Or there is underlying trigger that perfroms same logic.

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 );

How do I get the current date in SQL when entering data to a microsoft database?

I am using Microsoft SQL Server and SQL Server Management Studio.
I have a column called dateApplied which has a constraint like this:
[dateApplied] >= getDate()
When I enter a row the date is automatically added the row.
My problem is when I use the SELECT function, the dateApplied column is automatically changed to the current date and time in which the SELECT statement is called.
How do I prevent this from happening?
Thanks
Peter
I suppose you're using a computed column, like:
create table t1
(
id int
, date_col as getdate()
)
Try a default constraint instead:
create table t1
(
id int
, date_col datetime constraint DF_T1_DateCol default getdate() not null
)
A computed column is calculated whenever you run a query. A default constraint is only generated when the row is first inserted.