Check for existing row before doing insert - sql

Table1 columns:
clinic_code, schedule_date, schedule_time, source_id
Table2 columns:
clinic_code, schedule_date, schedule_time
There is a stored procedure that does:
1. Delete all records in Table1 where clinic_code='ABC' AND schedule_date=xyz
2. INSERT all records from table2 where table2.clinic_code='ABC' AND table2.schedule_date=xyz into table1.
I want to make a change in step 2.
*2. INSERT all records from table2 where table2.clinic_code='ABC' AND table2.schedule_date=xyz, but don't overwrite those rows in table1 where source_id=2.
Here's the original insert statement in step 2:
INSERT INTO table1 (col1, col2, col3)
SELECT table2.col1, table3.col2, table2.col3
FROM table2
INNER JOIN table3 ON table2.col3 = table3.col5 AND etc...
Table names, and additional columns have been left out, if it would be helpful, I can put the exact number of columns.

I'm not sure I follow completely, because if you're inserting the rows into table1, table1.col3 won't have a value for those rows yet. If you just want to avoid having table1.col3 = 2, you could use a where clause like this:
INSERT INTO table1 (col1, col2, col3)
SELECT table2.col1, table3.col2, table2.col3
FROM table2
INNER JOIN table3 ON table2.col3 = table3.col5 AND etc...
WHERE table2.col3 <> 2
Which would avoid inserting the value 2 into table1.col3, since table2.col3 is where you're pulling that from. If I'm missing the point here let me know, but that should do it.
EDIT - given that you've said the records between table1 and table2 are similar, and assuming there's a column you could join on between the two tables, you could do something like this:
INSERT INTO table1 (col1, col2, col3)
SELECT table2.col1, table3.col2, table2.col3
FROM table2
INNER JOIN table3 ON table2.col3 = table3.col5 AND etc...
LEFT OUTER JOIN table1 t1 ON tl.colX = table2.colX
WHERE table1.col3 <> 2
The idea being that you've now included table1 in your SELECT and as such can also include it in your WHERE clause. (Forgive me if the aliasing syntax is off for other SQL flavors, I'm mostly experienced in T-SQL.)

Well I don't know which SQL you are using so here is a standard SQL script:
BEGIN TRANSACTION ;
IF NOT EXISTS ( SELECT * FROM dbo.table1 WHERE col3 = 2 )
BEGIN ;
...your insert goes here
END ;
COMMIT ;

Related

SQL how to insert from another table based on same row values?

I have two tables with similar column values for columns "name" and "regis". One table is already filled with values, the other has only values for "name". How do i get "regis" values from table1 into table2 based on same column values?
I tried something like this
INSERT INTO table2 (regis)
SELECT table1 (regis)
WHERE table2.name = table1.name
Please try:
update table2 set regis = (select regis from table1 where table1.name=table2.name);
see the whole sample on:
https://www.db-fiddle.com/f/3jC8PGeZZEuty3XVq8gdzz/9
I think, what you are after is insert when name not found in table2 or update if its found in both tables.
INSERT INTO TABLE2 (regis)
SELECT t1.REGIS FROM TABLE1 as t1
LEFT OUTER JOIN TABLE2 as t2 on t2.name = t1.name
WHERE t2.name is null
You can update table2 using the statement like below:
update t2
set t2.regis = t1.regis
from table2 as t2
inner join table1 as t1 on t1.name = t2.name
If you are using SQL Server, then you can use merge statement to either insert or update in one step.
You need to use table2 as join in your select statement.
INSERT INTO table2 (regis)
SELECT table1.regis FROM Table1 INNER JOIN Table2 on table1.name = table2.name

How to join two tables, by looking up values from three tables?

I want to create a new table from 3 tables:
table1 is source table
table2 is subset of tabl1 except with one extra column
table3 has different columns.
All these tables are linked by ID column.
I know I will need a vertical join (UNION).
Query:
I need to join all records in table2 and look up values from table2.field1 and get the record set from table1 where field1 in table2 is in table1.id
I need to subset table3 where table3.date >= '2010-10-01' and use table3.id to get the record set from table1 where table3.id = table1.id
How do I use the UNION join to look up values, from table1 and keep all records from table2?
You could use:
--CREATE VIEW my_view AS
SELECT sub.id, sub.col1, sub.col2, table3.col1, ...
-- INTO #temp_table -- alternatively
FROM (SELECT id,col1, col2, ... -- only common column list, drag and drop from
FROM table1 -- object explorer
UNION
SELECT id, col1, col2, ...
FROM table2) sub
JOIN table3 ON table3.id = sub.id
WHERE table3.date >= '2010-10-01'

copy a table into a new table and add a new column on SQL server 2008

I need to copy a table into a new table on SQL server 2008.
Also, add a new column into the new table.
The values of the new column depends on the compare result between the new table and another table.
Example,
Table1:
col1 col2 col3
abc 346 6546
hth 549 974
Expected Table1_new:
col1 col2 col3 col4
abc 346 6546 1
hth 549 974 0
Table2:
col1
abc
sfsdf
If Table2's col1 appear in Table1 col1, mark col4 as 1 in Table1_new, else mark as 0.
The code does not work
SELECT *,
(
SELECT 1 as col4
FROM Table2 as a
INNER JOIN Table1 as b
on b.col1 = a.col1
SELECT 0 as col4
FROM Table2 as a
INNER JOIN Table1 as b
on b.col1 <> a.col1 # I do not know how to do this !!!
)
INTO table1_new
FROM table1
Any help would be appreciated.
You could use an outer join:
SELECT table1.col1, col2, col3,
CASE WHEN table2.col1 IS NULL THEN 0 ELSE 1 END AS col4
INTO table1_new
FROM table1
LEFT OUTER JOIN table2 ON table1.col1 = table2.col1
You can do this in several ways. The following uses an exists clause in a case statement:
insert into table1_new(col1, col2, col3, col4)
select col1, col2, col3,
(case when exists (select 1 from table2 t2 where t2.col1 = t1.col1)
then 1 else 0
end)
from table1 t1;
You can also do this with a left outer join, but you run the risk of duplicates if t2 has duplicates.
INSERT INTO T2
SELECT COL1,COL2,COL3, (COL1+COL2) FROM T1
Note that instead of the (COL1+COL2) section you could run other expressions or possibly even a function.
Try something like this using CASE
SELECT
CASE
WHEN b.col1 = a.col1 THEN 1
ELSE 0
END as col4
FROM Table1 as a
LEFT JOIN Table2 as b
on b.col1 = a.col1
EDIT: Table1 should be the left table as mentioned in #Muerniks answer.
In addition to what the others already suggested: If you can't solve the problem in one step, try to make smaller steps. E.g. first initialize Table1.col4 with zero:
INSERT INTO Table1_new (col1,col2,col3,col4)
SELECT col1,col2,col3,0
FROM Table1
After that you will only need to identify the records which have matching partners in Table2 which is a classical inner join:
UPDATE t1 SET col4=1
FROM Table1_new t1
JOIN Table2 t2 ON t2.col1=t1.col1

Cleaning up and simplifying a nested SQL statement

I'm trying to determine if there is a better way to do this in SQL. My goal is to run one query which returns two values that are to be used for another query. See below
select *
from table2
where col1 =
( select col1
from table1
where id = 123 )
and col2 =
( select col2
from table1
where id = 123 );
Is there a way to simplify this code by either doing a where clause that checks both values against one nested query, or by running the first querying and somehow setting the values of col1 and col2 to variables that I can use in the second query?
You can do
select *
from table2
where (col1, col2) = (select col1, col2
from table1
where id = 123)
SELECT DISTINCT a.*
FROM table2 a
INNER JOIN table1 b
ON a.col1 = b.col1
AND a.col2 = b.col2
WHERE b.id = 123
you can simply use query as below
select t2.* from table2 t2,table1 t1 where t1.col1=t2.col1 and
t1.col2=t2.col2 and t1.id=123
Seems like you've got it backwards. Since you know exactly what you want from table1 (so, presumably, the query is smaller), you should start by getting the data from table1, then join the releveant rows from table2:
select table2.*
from table1
inner join table2
on table2.col1 = table1.col1
and table2.col2 = table1.col2
where table1.id = 123

SQL: Update a column with multiple values with single query

I have an update query like following:
update table TABLE1 set COL1 = 'X' where COL2 = 'Y' ---1
Support the values 'X' and 'Y' are fetched from database now TABLE2. E.g.
select COL1, COL2 from TABLE2. ----2
I want to update table TABLE1 with values from TABLE2.
Just to make it more clear, assume that TABLE2 has following values:
Can you please help me in doing this in a single query!
I am using Oracle 11g.
For Oracle, this is the most basic way to do it:
update TABLE1
set COL1 = (select TABLE2.COL1 from TABLE2 where TABLE2.COL2 = TABLE1.COL2)
where COL2 IN (select TABLE2.COL2 from TABLE2);
This can be inefficient in some cases since it could execute a subquery for every row in TABLE1.
Depending on the declaration of primary key or unique constraints on both tables, you may be able to use the updateable inline-view method, which is probably more efficient:
update
(select TABLE1.COL1 as T1C1, TABLE1.COL2 as T1C2, TABLE2.COL1 as T2C1
from TABLE1 join TABLE2 on TABLE2.COL2 = TABLE1.COL2
)
set T1C1 = T2C1;
#Dave Costa's answer is correct, if you limit yourself to update statements. However, I've found that using a merge statement in these situations allows me to do this in a more straightforward manner:
merge into TABLE1
using TABLE2
on (TABLE2.COL2 = TABLE1.COL2)
when matched then
update set TABLE1.COL1 = TABLE2.COL1;
update TABLE1
set TABLE1.COL1 = TABLE2.COL1
from TABLE1
join TABLE2 on TABLE1.COL2 = TABLE2.COL2
(this would work on Sql Server)
for oracle:
UPDATE Table1 t1
SET (X,Y) = (SELECT X,Y from Table2 WHERE ...YourConditions...)
WHERE ... Another Conditions ...
for mysql, sql-server
UPDATE t1
SET t1.X = t2, t2.Y = t2.Y
FROM Table1 t1, Table2 t2
WHERE t1.Something = t2.Something