Create SQL table with the data from another table - sql

How do I create a table using data which is already present in another table (copy of table)?

The most portable means of copying a table is to:
Create the new table with a CREATE TABLE statement
Use INSERT based on a SELECT from the old table:
INSERT INTO new_table
SELECT * FROM old_table
In SQL Server, I'd use the INTO syntax:
SELECT *
INTO new_table
FROM old_table
...because in SQL Server, the INTO clause creates a table that doesn't already exist.

If you are using MySQL, you may want to use the CREATE TABLE ... AS SELECT syntax to create a table defined by the columns and data types of another result set:
CREATE TABLE new_table AS
SELECT *
FROM old_table;
Example:
CREATE TABLE old_table (id int, value int);
INSERT INTO old_table VALUES (1, 100), (2, 200), (3, 300), (4, 400);
CREATE TABLE new_table AS
SELECT *
FROM old_table;
SELECT * FROM new_table;
+------+-------+
| id | value |
+------+-------+
| 1 | 100 |
| 2 | 200 |
| 3 | 300 |
| 4 | 400 |
+------+-------+
4 rows in set (0.00 sec)
DESCRIBE new_table;
+-------+---------+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra |
+-------+---------+------+-----+---------+-------+
| id | int(11) | YES | | NULL | |
| value | int(11) | YES | | NULL | |
+-------+---------+------+-----+---------+-------+
2 rows in set (0.03 sec)
For other DBMSes, that do not support this syntax, you may want to check out #OMG Ponies' answer for a more portable solution.

For SQL Server
SELECT *
INTO NewTable
FROM OldTable

For Sql server:
Create new table from existing table :
CREATE TABLE new_table_name AS
SELECT [col1,col2,...coln] FROM existing_table_name [WHERE condition];
Insert values into existing table form another existing table using Select command :
SELECT * INTO destination_table FROM source_table [WHERE conditions];
SELECT *
INTO newtable [IN externaldb]
FROM oldtable
[ WHERE condition ];
Insert values into existing table form another existing table using
Insert command :
INSERT INTO table2 (column1, column2, column3, ...)
SELECT column1,column2, column3, ... FROM table1 [WHERE condition];

if u want exact schema of existing table to new table and all values of existing table want to be inserted into your new table then execute below two queries :
create table new_table_name like Old_table_name;
select * into new_table_name from Old_table_name;
LIKE works only for base tables, not for views.
If the original table is a TEMPORARY table, CREATE TABLE ... LIKE does not preserve TEMPORARY. To create a TEMPORARY destination table, use CREATE TEMPORARY TABLE ... LIKE.
for more details click here

Related

Find difference between two table in SQL and append back result to source table & update column values only for newly inserted rows

I am new to SQL Server. I want to create a procedure which should check difference between master table & quarterly table and insert the different rows back to the master table and update the corresponding column values.
Master table is like:
|PID | Release_date | Retired_date
|loc12|202108 |
|loc34|202108 |
Quaterly table is like:
|PID | Address | Post_code
|loc12| Srinagar | 5678
|loc34| Girinagar | 6789
|loc45| RRnagar | 7890
|loc56| Bnagar | 9012
Resultant Master table should be like:
|PID | Release_date | Retired_date
|loc12|202108 |
|loc34|202108 |
|loc45|202111 |
|loc56|202111 |
I have tried except but I'm not able to update the master table after inserting the difference. My code is
insert into master(select PID from Master
except
select PID from Quaterly)
update master
set Release_date = '202111'
where PID in (select PID from Master
except
select PID from Quaterly)
TIA
You could do everything in one query, no need to use UPDATE:
INSERT INTO Master(PID, Release_date)
SELECT q.PID, '202111'
FROM Quaterly q
WHERE q.PID NOT IN (SELECT PID FROM Master)
Other approach you can use by leveraging SQL JOINs:
INSERT INTO MASTER
SELECT q2.PID, '202111'
FROM Quaterly q1
LEFT JOIN Quaterly q2
ON q1.PID = q2.PID
WHERE q1.PID IS NULL

SQL Server: Insert row into table, for all id's not existing yet

I have three tables in MS SQL Server, one with addresses, one with addresstypes and one with assignments of addresstypes:
Address:
IdAddress | Name | ...
1 | xyz
2 | abc |
...
AddressTypes
IdAddresstype | Caption
1 | Customer
2 | Supplier
...
Address2AddressType
IdAddress2AddressType | IdAddress | IdAddressType
1 | 1 | 2
3 | 3 | 2
Now I want to insert a row into Address2AddressType for each address, which is not assigned yet / not emerging in this table with the Addresstype Customer.
So to select those addresses, I use this query:
SELECT adresses.IdAddress
FROM [dbo].[Address] AS adresses
WHERE adresses.IdAddress NOT IN (SELECT adresstypeassignment.IdAddress
FROM [dbo].[Address2AddressType] AS adresstypeassignment)
Now I need to find a way to loop through all those results to insert like this:
INSERT INTO (Address2AddressType (IdAddress, IdAddresstype)
VALUES (<IdAddress from result>, 1)
Can anybody help, please?
Thanks in advance.
Regards
Lars
Use insert . . . select:
INSERT INTO Address2AddressType (IdAddress, IdAddresstype)
SELECT a.IdAddress, 1
FROM [dbo].[Address] a
WHERE a.IdAddress NOT IN (SELECT ata.IdAddress FROM [dbo].Address2AddressType ata);
I also simplified the table aliases.
Note: I don't recommend NOT IN for this purpose, because it does not handle NULLs the way you expect (if any values returned by the subquery are NULL no rows at all will be inserted). I recommend NOT EXISTS instead:
INSERT INTO Address2AddressType (IdAddress, IdAddresstype)
SELECT a.IdAddress, 1
FROM [dbo].[Address] a
WHERE NOT EXISTS (SELECT 1
FROM [dbo].Address2AddressType ata
WHERE ata.IdAddress = a.IdAddress
);

Temp table creation issue in postgresql 11.6

In a PostgreSQL function I am creating a temp table named table1 in a loop.
To check if the table already exist in other iterations I use the query select * from pg_tables where tablename = '..'.
But if the table does not exist during iteration (dropped in between) it still says the table exist. Is there any way to check if the table exist in a query rather than the mentioned query?
Query sample
db=# select * from pg_tables where tablename = 'table1';
schemaname | tablename | tableowner | tablespace | hasindexes | hasrules | hastriggers |rowsecurity
------------+-----------+------------+------------+------------+----------+-------------+-------------
pg_temp_3 | table1 | user1 |user1 _data1 | t | f | f | f
(1 row)
db=# \d table1
Did not find any relation named "table1".
This issue raises after the function is interrupted by an exception. Any suggestions or findings?

Oracle PLSQL validate a row and insert each cell value of row as a new row with validation results in another table oracl

I am very much new to the DB world, so wanted to review whether I am following right approach or not.
I have two tables,
table A --> is a table with 40 columns
table B --> is a table with the 2 columns (each column of table A is represented as row in this table.)
Example:
A:
column_1 | column_2 | column_3 ......... | column_40
-----------------------------------------------------------
value1_1 | value1_2 | value1_3...... | value1_40
B:
column_name |column_value | column_errorKey
----------------------------------------------------
column_1 | value1_1 | value1_1_errorKey
column_2 | value1_2 | value1_2_errorKey
What am I doing?
Validate each value of a row from table A and insert into the table B with
its value, error key and corresponding column name.
My PL SQL code is as below for, (Note: SQL code has considered only two columns to minimize the code here)
INSERT WHEN (LENGTH(column_1) <=7) THEN
into table_B values(
'column_1',column_1,'NoError')
WHEN (LENGTH(column_1) >7) THEN
into table_B values(
'column_1',column_1,'invalidLength')
WHEN (LENGTH(column_2) <= 75) THEN
into table_B values(
'column_2',column_2,'NoError')
WHEN (LENGTH(column_2) > 75) THEN
into table_B values(
'column_2',column_2,'invalidLength')
( select column_1,column_2,...,column_40
from table_A );
The validation that is happening within When the condition has only one validation but we have more validation like this for the value of each cell. I wanted to know is I am in the right approach or is another better way we have.
As suggested by APC, the best approach is to change your DB design.
You could probably use UNPIVOT and a single INSERT INTO SELECT .
The select statement would look like something below.
SQL Fiddle
Oracle 11g R2 Schema Setup:
CREATE TABLE TableA(
column_1 VARCHAR(13)
,column_2 VARCHAR(25)
,column_3 VARCHAR(22)
,column_4 VARCHAR(11)
);
INSERT INTO TableA(column_1,column_2,column_3,column_4) VALUES ('value1_1','value1_2','value1_3','value1_40');
Query 1:
SELECT column_name
,column_value
,CASE
WHEN LENGTH(COLUMN_VALUE) <= 7
THEN 'NoError'
ELSE 'invalidLength'
END AS column_errorKey
FROM TableA
UNPIVOT(column_value FOR column_name IN (
COLUMN_1
,COLUMN_2
,COLUMN_3
,COLUMN_4
))
Results:
| COLUMN_NAME | COLUMN_VALUE | COLUMN_ERRORKEY |
|-------------|--------------|-----------------|
| COLUMN_1 | value1_1 | invalidLength |
| COLUMN_2 | value1_2 | invalidLength |
| COLUMN_3 | value1_3 | invalidLength |
| COLUMN_4 | value1_40 | invalidLength |

INSERT if NOT EXISTS, But DELETE if it EXISTS

I have the following query to update a table record setting new foreignKey if that foreignKey and foreignKey2 did not already exist. This should work great, however, how can I modify to delete that particular pkID record if it DOES exist?
table structure:
+----------------+
| table |
+----------------+
| pkID |
| foreignKey |
| foreignKey2 |
+----------------+
query:
UPDATE table a
SET a.foreignKey = 2
WHERE a.pkID = 1234
AND NOT EXISTS (
SELECT 1
FROM table b
WHERE b.foreignKey = 2
AND b.foreignKey2 = a.foreignKey2
)
You can delete if it exists, and only insert (instead of update since the record doesn't exist to be deleted) otherwise. But it is not clear what the 3rd value should be.
DELETE tbl where pkID = 1234;
if ##ROWCOUNT = 0
INSERT tbl(foreignKey, pkID, foreignKey2)
VALUES (2, 1234, ??)
You need MERGE. Take a look here(there is an example with the same task)