How to use if not exists in sql - sql

I am trying to use if exists statement but having some issues. I am checking if LOCATION and NAME exist in my NEWTABLE, if they don't exist then i want to insert them into my NewTable. So basically i am trying to find Location and Names where records exist in the OldTable but not in the newTable. thanks
Here is my sql
INSERT INTO NewTable(Location, Name)
SELECT Location, Name
FROM OldTable
WHERE Location and Name NOT IN (select Location, Name from NewTable)

You would use not exists for this:
INSERT INTO NewTable(Location, Name)
SELECT Location, Name
FROM OldTable ot
WHERE NOT EXISTS (select 1
from NewTable nt
where nt.LOCATION = ot.LOCATION and nt.NAME = ot.NAME
);
You can also enforce this constraint by building a unique index:
create unique index NewTable_Location_Name on NewTable(Location, Name);
Note that this would cause an error when duplicates are encountered (without the additional check).

Related

Inserting data into a table(mutliple columns) which has primary key from another data which has data except primary key

I have a table that has 3 columns ID(Primary Key), Name, City.
I need to import data from another table that has only Name and City.
I can write insert into table 1(Name, City) select Name, City from table2.
But then I need ID in table 1 which needs to be inserted using a sequence.
I tried this:
insert into table1(ID, Name,City) values(seq.nextval, select distinct name, city from table2). But I am receiving an error saying an insufficient number of values.
I am trying it in SQL Oracle. Can someone please help me with this?
You are mixing the insert ... values and insert ... select syntax.
You edited your question to include distinct, implying you have duplicate name/city pairs that you want to suppress; but neither version gets the error you reported. If you don't have duplicates then you can just do:
insert into table1(ID, Name,City)
select seq.nextval, name, city from table2;
If you do have duplicates then you can't just add the distinct keyword, but you can use a subquery:
insert into table1 (id, name, city)
select seq.nextval, name, city
from (
select distinct name, city
from table2
);
db<>fiddle
You could also set the ID via a trigger. If you we're on a recent version you could use an identity column instead - but you tagged the question with Oracle 11g, where those are not available.

Conditionally insert multiple data rows into multiple Postgres tables

I have multiple rows of data. And this is just some made up data in order to make an easy example.
The data has name, age and location.
I want to insert the data into two tables, persons and locations, where locations has a FK to persons.
Nothing should be inserted if there already is a person with that name, or if the age is below 18.
I need to use COPY (in my real world example I'm using NPQSQL for .NET and I think that's the fastest way of inserting a lot of data).
So I'll do the following in a transaction (not 100% sure on the syntax, not on my computer right now):
-- Create a temp table
DROP TABLE IF EXISTS tmp_x;
CREATE TEMPORARY TABLE tmp_x
(
name TEXT,
age INTEGER,
location TEXT
);
-- Read the data into the temp table
COPY tmp_x (name, age) FROM STDIN (FORMAT BINARY);
-- Conditionally insert the data into persons
WITH insertedPersons AS (
INSERT INTO persons (name, age)
SELECT name, age
FROM tmp_x tmp
LEFT JOIN persons p ON p.name = tmp.name
WHERE
p IS NULL
AND tmp.age >= 18
RETURNING id, name
),
-- Use the generated ids to insert the relational data into locations
WITH insertedLocations AS (
INSERT INTO locations (personid, location)
SELECT ip.id, tmp.location
FROM tmp_x tmp
INNER JOIN insertedPersons ip ON ip.name = tmp.name
),
DROP TABLE tmp_x;
Is there a better/easier/more efficient way to do this?
Is there a better way to "link" the inserts instead of INNER JOIN insertedPersons ip ON ip.name = tmp.name. What if name wasn't unique? Can I update tmp_x with the new person ids and use that?

Oracle - using nested table column in where clause

I have a staging table (table_B) with columns using nested table data types:
CREATE OR REPLACE TYPE nested_column_type AS OBJECT
(
abc_1 VARCHAR2(100),
abc_2 VARCHAR2(100),
col_id VARCHAR2(100),
tbl_id NUMBER
);
CREATE OR REPLACE TYPE nested_column_tab AS TABLE OF nested_column_type;
CREATE TABLE table_B
(col_id NUMBER,
nested_column NESTED_COLUMN_TAB)
NESTED TABLE nested_column STORE AS column_nested);
I want to use nested_column in the where clause of a delete statement like this:
DELETE FROM table_A a
WHERE tbl_id = v_tbl_id
AND NOT EXISTS (SELECT col_id
FROM TABLE(SELECT b.nested_column
FROM table_B b
WHERE tbl_id = v_tbl_id)
WHERE col_id = a.col_id);
Table_A is my target table. My goal is to delete records from table_A where table_A.col_id NOT EXISTS in table_B.nested_column.col_id and tbl_id = v_tbl_id.
Adding more on what #Ted mentioned,
you need to understand object name resolution steps and must use a table alias. This is mentioned here.
To avoid inner capture and similar problems resolving references,
Oracle Database requires you to use a table alias to qualify any
dot-notational reference to subprograms or attributes of objects.
In your case the query becomes:
DELETE FROM table_A a
WHERE tbl_id = v_tbl_id
AND a.col_id NOT IN (SELECT b.col_id
FROM table_B b
WHERE (SELECT tb.tbl_id
FROM TABLE (b.nested_column) tb) =a.tbl_id);
I think the below will put you in the right path:
select t.primary_id, nt.*
from table_b t, table (t.nested_column) nt
For any further clarifications please don't hesitate to contact me again here.
Ted

SQL Server : updating one column and inserting if not exist

I have a table TableKats that looks like this:
ID - int
Name - varchar
KatID - int
What I want to do is to update the column Name from another table, and if there is a name in the other table that doesn't exist in TableKats, it should insert it and give KatID a 0
Does anybody know a way to do that? Thanks
you can do it using MERGE, as your other table schema is not known assuming Name as the column in other table too
MERGE TableKats T
USING ( SELECT * from TableB) AS S
ON T.Name = S.Name
WHEN NOT MATCHED THEN
INSERT ( Name, KatID)
VALUES ( S.Name, 0)
WHEN MATCHED THEN
UDPATE -- Not clear what needs to be updated.

SQL 'simple' query syntax error - help!

My query returns a syntax error:
Invalid object name 'table.clientinfo'.
Here is my query:
INSERT table.clientinfo (name, addr, entry, affiliate )
SELECT name, addr, entry, affiliate FROM table.clientinfo WHERE product = 5
Is the error due to the insert function not finding 'clientinfo' as it does not exist.
Can anybody give me the correct syntax to create the table first before populating it from the select function?
You want CREATE TABLE
CREATE TABLE clientinfo (
name VARCHAR(100)
addr VARCHAR(100)
entry VARCHAR(100)
affiliate VARCHAR(100)
);
with specific types/sizes for your app. You might want to indicate foriegn and primary keys, constraints etc too
In SQL Server, if you want to select and insert into a new table, use this syntax:
SELECT name, addr, entry, affiliate
INTO (new table name)
FROM [table.clientinfo]
WHERE product = 5
You need to SELECT .... INTO and you need to make sure to use proper table names.
If you table name really has a dot in it (really really bad practice!), then you MUST put that table name in square brackets: FROM [table.clientinfo]
Also, when doing SELECT .. INTO ... you cannot select from an existing table and insert into the same existing table - you need to use a new table name for your destination table.
You should use
INSERT INTO [tablename] (field1, field2, ... , fieldx)
SELECT ...
Or if you want to create the other data directly:
SELECT field1, field2, ... , fieldx
INTO newTable
FROM oldtable
WHERE ....