Create new column derived from current columns - sql

The question is: how to create a new column in Postgres SQL based on existing columns.
A work around was to create of a unique row identifier and create a parallel table with the row identifier, compute the desired update, and then replace row_3 with the update based on the unique row identifier. This is manual and not very efficient.
Assume the table structure is:
create table tab (
row_1 integer
, row_2 integer
, row_3 integer);
Assume the table has 1000 entries and row_1 and row_2 have legitimate values.
The question is: How can row_3 be updated to reflect the sum of row_1 and row_2 for the entire table. This should work for an arbitrary table.

If you want the "new" column to be up-to-date, then I would recommend using a view:
create view v_tab as
select tab.*, (col1 + col2) as col3
from tabl;
(I experience cognitive dissonance when columns are referred to as "row". ;)
This will do the calculation when the table is queried, so the results are always consistent.
If you just want a one-time change to the values, then use update.

ALTER TABLE tab ADD COLUMN row_3 INTEGER;
UPDATE tab SET row_3 = row_1+row_2;
If you want a 'NOT NULL' constraint on column 'row_3' then add it after the UPDATE.

Related

How to delete all columns except first five?

I have a table with approximately 90 columns and want to delete all after the 5th. How to delete all columns except first five?
Given that you only want to keep a few columns, the option with least code would be to make a new table with those columns only. You should do this in a transaction to avoid losing data.
Example with two columns:
ALTER TABLE TableName RENAME TO TmpTableName;
CREATE TABLE TableName(Col1 INTEGER, Col2 INTEGER);
INSERT INTO TableName(Col1, Col2) SELECT Col1, Col2 FROM TmpTableName;
DROP TABLE TmpTableName;
Before version 3.35.0, SQLite did not support removing columns, so this was the only possible option.

UPDATE two columns with new value under large size table

We have table like :
mytable (pid, string_value, int_value)
This table has more than 20M rows in total. Now we have a feature try to mark all the rows from this tables as invalid. So we need update the table columns: string_Value = NULL and int_value = 0 which indicate this is invalid row ( we still want to keep the pid as it is important to us)
So what is the best way?
I use the following SQL:
UPDATE Mytable
SET string_value = NULL,
int_value = 0;
but this query takes more than 4 minutes in my test env. Is there any better way we can improve it?
Updating all the rows can be quite expensive. Often, it is faster to empty the table and reload it.
In generic SQL this looks like:
create table mytable_temp as
select pid
from mytable;
truncate table mytable; -- back it up first!
insert into mytable (pid, string_value, int_value)
select pid, null, 0
from mytable_temp;
The creation of the temporary table may use different syntax, depending on our database.
Updates can take time to complete. Another way of achieving this is to follow the following steps:
Add new columns with the values you need set as the default value
Drop the original columns
Rename the new columns with the names of the original columns.
You can then drop the default values on the new columns.
This needs to be tested as different DBMSs allow different levels of table alters (i.e. not all DMBSs allow a drop default or a drop column).

How to update multiple records in a table?

I need to update the column B in a table, which has a column A as the primary key, with the a different value for each value in column A. There are about 50,000 rows to be updated in the table, which makes it impossible to do this manually. Is there any other way to update it?
Of all the records in the table, I want to update just 50000. For each record among these 50,000, the value to be updated is different. How can I update the table without having to write 50,000 update queries?
Column A. Column B
One. 1
Two 2
Three 3
I want to update one=4, two=5 and so on for about 50,000 rows.
Thanks in advance guys!
I don't know whether I got your requirement properly but i have written a below working snippet to replicate the scenario. Let me know if this helps
--Drop any existing table if present with same name
DROP TABLE SIMPLE_UPDATE;
--Create new table
CREATE TABLE SIMPLE_UPDATE
(
COL1 NUMBER,
COL2 VARCHAR2(2000 CHAR)
);
-- Inserting random test data
INSERT INTO SIMPLE_UPDATE
SELECT LEVEL,TO_CHAR(TO_DATE(LEVEL,'J'),'JSP') FROM DUAL
CONNECT BY LEVEL < 500;
-- Updating the col2 value assuming thta the increment is adding 3 to each number and updating the col2 with the same.
UPDATE SIMPLE_UPDATE
SET COL2 = COL1+3
WHERE <COL_NAME> = <CONDITON>;
COMMIT;

INSERT a new column into an existing SQL table

I have a "source data" table with columns A,B,C,D,E,F
I use this table to populate a live table by using
INSERT INTO LIVETABLE
SELECT *
FROM SOURCEDATATABLE
Recently, a new column (C1) was added to the LIVETABLE
All I want to do is insert a C1 column into my SOURCEDATATABLE between C and D so that it now is A,B,C,C1,D,E,F. There is no need to populate with data as the LIVETABLE accepts NULLs
Is there any easy solution?
EDIT - MISSING INFORMATION
This table is one of many and my approach to using the INSERT INTO is due to having to use dynamic SQL (for various other reasons) so I cannot specify the column names
There is a reason for the Mantra "I shall not use SELECT *" and you ran straight into it. Add the column to SOURCEDATATABLE (if necessary) and enumerate the columns in the SELECT clause using NULL for the new one.
The only way to insert a new column between two columns is to create a new table with the columns in the order you want, copy the data into it, drop the old table and rename the new table with the old name. Make sure you remove primary key identities to maintain the identity column.

Database: Oracle Add new column but not the last column (sequence)? [duplicate]

This question already has answers here:
How to insert a column in a specific position in oracle without dropping and recreating the table?
(4 answers)
Is there a way to add column at a specified position in Oracle table? [duplicate]
(1 answer)
Closed 9 years ago.
One question
Database: Oracle
This is the stmt (Desc.: chnage type VARCHAR to CLOB)
ALTER TABLE XX
ADD (TEMP_Value CLOB);
UPDATE XX SET TEMP_Value=Value;
COMMIT;
ALTER TABLE XX DROP COLUMN Value;
ALTER TABLE XX
RENAME COLUMN TEMP_Value TO Value;
the problem:
The new clob-column is the last column in the XX table (normally).
If value second was now is the last column, How to change the sequence
I know the following solution and that is not very smart for several of columns, so I want to find a other solution.
create newtable as
select Value, X, XX,..
drop table XX;
rename newtable to XX;
Discussed here
Oracle does not support adding columns in the middle of a table, only adding them to the end, unlike MYSQL ALTER TABLE TABLENAME ADD COL1 AFTER COL2 command. Your database design and app functionality should not depend on the order of columns in the database schema. You can always specify an order in your select statement, after all, which would be best practice.
SELECT * FROM TABLE is not a good practice.
However if for some reason you simply must have a new column in the middle of your table there is a work around.
CREATE TABLE TAB1NEW
AS
SELECT
0 AS COL1,
COL1 AS COL2
FROM
TAB1;
DROP TABLE TAB1 PURGE;
RENAME TAB1NEW TO TAB1;
Where the SELECT 0 AS col1 is your new column and then you specify other columns as needed from your original table. Put the SELECT 0 AS col1 at the appropriate place in the order you want.
Afterwards you may want to run an alter table statement on the column to make sure it's the data type you desire. Remember to put back your constraints, indexes, partition... and whatever as per the original table