Postgres - Move the records from one table to another based on condition - sql

I have two tables with millions of rows in postgres. I wanted to move records from one table to another.
Table name - event
List of columns:
"id"
"url"
"parent_id"
"created"
"created_by"
"last_modified"
"last_modified_by"
"tags"
"type"
"sub_type"
"category"
"name"
"preference"
Table name - preference
List of columns:
"id" - If the entity_type is event, id column in the event table goes here
"entity_type" // event or slot.
"preference"
"created"
"created_by"
"last_modified"
"last_modified_by"
"parent_entity_id"
And these tables are already populated with millions of data. And I have added a new column named preference in the event table, which does not have any data.
Now, I wanted to move the
preference table preference column data to the event table preference column.
Condition:
Migrating the data from the preference column (In preference table) to the preference column (In event table) only when the entity_type is an event. And the insert should
happen with the corresponding row in the event table.
I tried this query, but this seems to be incorrect. And Postgres throws a syntax error.
insert into <schema_name>.event a (preference) where a.id = '<eventId goes here>' (select preference from <schema_name>.preference where entity_id = '<eventId goes here>'
and entity_type = 'event')

You should use update instead of insert, because the table is already populated with data.
update event e
set preference = (select preference from preference p where p.entity_id = e.id and entity_type = 'event')

Related

Updating a column in a table from another table using postgreSQL

I have table named ´cities´ with 3 columns named:
state, name, pop
And a table cities1 with:
state, name
The columns state and name are common for both tables. I want the column pop alone from cities to be inserted in cities1 table.
How this can be done using postgreSQL?
First you need to add a column pop of specific type to your cities1 table, and then fill it.
ALTER TABLE cities1 ADD COLUMN pop [datatype here]
Update pop column in table cities1 with values from cities where state,name are the common columns.
UPDATE cities1
SET pop = cities.pop
FROM cities
WHERE cities1.state = cities.state
AND cities1.name = cities.name

Copying dates to a column from another table with criteria

I'm trying to do the following:
One table in the database is called service_state_history, that table has three columns:
service_id - which refers to the id of the service that the service_state is related to. (it's nor foreign key because the relation is done in the JPA code in this case).
state_started column which has DATETIME values, that indicate whenever the state on that row has started.
state column which describes the state of that history entry and has following VARCHAR-values: (STANDBY, IN PROGRESS, DONE)
The other table in the database is called services, that table has two relevant columns:
id BIGINT
done_date DATETIME
Now, what I'm supposed to do is update the done_date column in services from the service_state_history table's column state_started, when the state column's value in the row is DONE and the service_id value in matches id in services.
How does that translate into SQL?
So to get all the records that will be updating the destination table, you will use the results generated from:
SELECT service_id, state_started, state
FROM service_state_history
WHERE state = 'DONE'
To perform the UPDATE you will need to JOIN this result set to the destination table on the identity column and use the state_started in the update. Something like:
UPDATE s
SET s.done_date = ssh.state_started
FROM services s
INNER JOIN service_state_history ssh ON ssh.service_id = s.id
WHERE ssh.state = 'DONE'

Update single entry based on lookup in multiple sql tables

I'm trying to update entries in a table to reflect what I have stored in another table, based on which category an item is in yet another table. Oh, and my items are keyed by both an alphabetic key (AKey) and numeric key (NKey).
So far I have
update itmHistory
set ithLocation = storLocation from items, storage
where ithAKey in (select storAKey from storage)
and ithNKey in (select storNKey from storage)
and storCategoryName = itmCategoryName;
What ends up happening is each instance of itmLocation in the items table is set to the very last entry where the storCategoryName = itmCategoryName.
Any ideas to make each update as it's found?
EDIT: Table information:
itmHistory: ithAKey varchar(3) PK
ithNKey int PK
ithStart timestamp PK
ithEnd timestamp
ithLocation text
items: itmAKey varchar(3) PK
itmNKey int PK
itmCategoryName text
storage: storName text PK
storCategoryName text
storLocation text
(PK = Primary Key)
Based on your table information, how about this one?
UPDATE ih
SET ih.ithLocation = s.storLocation
FROM itmHistory ih
JOIN items i ON ih.ithAKey = i.itmAkey AND ih.ithNKey=i.itmNKey
JOIN Storage s ON i.itemCategoryName = s.storCategoryName

Replace data in column with foreign key to same data in other table

Hopefully you guys can help me figure out how to do something I haven't come across before.
I have a table, call it TableA, with many columns. One of them is 'state', with entries such as:
state
'MA'
'NJ'
'HI'
and so forth. I would like to create some sort of way to pull these values out into a new foreign-keyed table, call it StateTable, which would have columns state_key and state.
For example, here's how I envision it proceeding row-by-row:
Row 1: Value in 'state' column in TableA is 'MA'. Check to see if StateTable has an entry where the 'state' column is 'MA'. If so, get the state_key for that row, and replace the entry in TableA with the foreign key, so that row now has a FK to 'MA' instead of storing that value directly. If StateTable has no 'MA' entry, insert it, and do the same with the new FK. And so on, for each row.
So the end result would be two tables:
TableA
state
1
2
3
StateTable
state_key state
1 'MA'
2 'NJ'
3 'HI'
There shouldn't be any hard-coded stuffs going on because I'll need to do this for other columns as well, like state, that have a somewhat small number of finite values.
tl;dr a way to preserve data in a column while turning the column into a FK'd table.
Any ideas? Thanks!!
Create the state table with an auto-enumeration field "state_key", use SELECT DISTINCT ... INTO to fill it, and use something like
UPDATE TableA SET TableA.state=
(SELECT state_key FROM StateTable where TableA.state=StateTable.state)
to get the values into it.
My suggestion would be to do the following
Create your new state table (either manually or using an insert into statement)
if manually creating your state table, insert unique records into it from TableA
Create a new column in TableA (StateID) foreign key column, linked to your new state table
Insert value into your new StateID column by matching TableA state to the state in your state table and pulling the ID from that table.
If you need a hand with the queries, let me know.

Can't get SQL statement to update from 2 Tables?

I currently have a database with two tables in it one hold lets say job details and the other company details. The "company_name" exists in the "Jobs" table which will have a matching entry in the "Companies" table under the field of "name". I want to basically set the field in the "Companies" table of "comp_id" to be the value of the field "id" in the "Jobs" table, WHERE the "name" in the "Companies" table is equals to the "company_name" in the "Jobs" table.
I have create the query below which i believed should work however it returns no rows affected?? can anyone please help me with this?
UPDATE `jobs`, `companies`
SET `comp_id` = 'companies.id'
WHERE ('companies.name' = 'jobs.company_name')
Thanks
This condition:
WHERE ('companies.name' = 'jobs.company_name')
is one problem (unless this is a copy & paste error during posting)
You are comparing two string literals there (and of course as they are not the same, you will never update anything).
The reason is you are using single quotes which denote a string literal. To quote column names you either need to use double quotes or the backticks you had used before (assuming you are on MySQL).
Reading your question you are only updating one table not two?
I want to basically set the field in
the "Companies" table of "comp_id" to
be the value of the field "id" in the
"Jobs" table, WHERE the "name" in the
"Companies" table is equals to the
"company_name" in the "Jobs" table.
All you want to do is set the comp_id column in the companies table to the value of the id column in the jobs table where the name and company_name columns are the same?
To do this using MSSQL you would do something like this:
Update c
Set c.comp_id = j.Id
From dbo.Companies c
Join dbo.Jobs j on c.Name = j.Company_Name
You can update only 1 table in an UPDATE statement in SQL Server. To update multiple tables at once you have the following options:
Use Stored procs
Create a View of the select statement and delete from the view
Use triggers.