SQL table with a field that contains null values - sql

A table called table1 has a field called field1 with null values in it. This query does not return any rows:
SELECT *
FROM table1
WHERE field1 NOT IN
(
SELECT field1
FROM table1
)
I know there are better ways of writing this query. What causes this behaviour i.e. using not in with a field that contains null values.

OK, I might be missing the point here, but one way to rephrase your query is:
Step 1: Take all values of table1.field1.
Step 2: Return all table1 rows whose field1's value isn't among the values obtained in Step 1.
Surely this always returns the empty set?

In assumption that there is primary key field exists in table, you may use this script:
select
t1.*
from
dbo.Table1 as t1
where
t1.field1 = 'Value1'
and not exists( select 1 from Table1 as t2 where t1.ID != t2.ID and t2.field1 = 'Value2')

Related

How to copy an sql column based on foreign key?

How do I run the following query
INSERT INTO table1
SELECT sourceId
FROM table2
WHERE table2.id = table1.productId
given that table2 has an id column and a sourceId column (and few others) and table1 already contains productId and I want to copy the sourceId column into the table as well?
The error message I'm getting with this query is simply "Unknown column 'table1.productId' in where clause", but if I include table1.productId in the SELECT and table1 on the FROM row, I get the "Column count doesn't match value count at row 1" error.
Any idea how to fix up the query?
when you are inserting into a table, you have to specify what to insert in all columns of that table. Should look like this:
INSERT INTO table1 (column1, column2, column3, ...)
SELECT value1, value2, value3, ...
FROM table2
WHERE ...;
But in your case since you said table1 already contains productId, you probably should do an UPDATE and not an INSERT
UPDATE table1 t1
SET t1.sourceId =
(SELECT sourceId
FROM table2
WHERE table2.id = t1.productId);
If this works for you, you can improve on it with JOINs
The select part is supposed to work stand-alone, so you must select from table1 in that part, if you want to refer to its rows.
INSERT INTO table1
SELECT sourceId
FROM table2
WHERE table2.id IN (SELECT productId FROM table1);

ORA-01427 Subquery returns more then one row..Oracle Update Statement

How do you write a update statement with a Sub-Select in an Oracle Environment (SQL Developer)?
Example: UPDATE table SET column = (SELECT....)
Every time I try this it gives me ORA-01427 "Sub select returns more then one row" even if there is no WHERE clause..
Based on the understanding of your question I'd suggest use Merge statement.
Merge into Table1
Using
(SELECT * from table2 where condition) Temp
On (Table1.columname condition Temp.columname)
When matched Then update Set Table1.column_name = Temp.column_name;
Table1 is the table where you want to update the records.
Table2 is the table from which you want to get the data (The sub query which you are talking about )
Using this merge statement you will be able to update n number of rows.
If you want to update multiple rows, you can either use a MERGE statement (as in #jackkds7's answer above) or you can use a filter on your subselect:
UPDATE table t1
SET column = ( SELECT column FROM table2 t2 WHERE t2.key = t1.key );
If there aren't matches in table2 for all the records in table then column will be set to NULL for the non-matches. To avoid that, add a WHERE EXISTS clause:
UPDATE table t1
SET column = ( SELECT column FROM table2 t2 WHERE t2.key = t1.key )
WHERE EXISTS ( SELECT 1 FROM table2 t2 WHERE t2.key = t1.key );
Oh and in the event that key is not unique for table2, you can aggregate (up to you to figure out which function would be best):
UPDATE table t1
SET column = ( SELECT MAX(column) FROM table2 t2 WHERE t2.key = t1.key )
WHERE EXISTS ( SELECT 1 FROM table2 t2 WHERE t2.key = t1.key );
Hope this helps.
I think it would help if you posted your actual query.
In essence, the "inner" select would be executed for each row that would be updated. This inner select query is called a correlated subquery:
UPDATE table t SET t.column = (
select ot.othercolumn from othertable ot
where ot.fk = t.id --This is the correlation part, that finds
--he right value for the row you are currently updating
)
You must ensure the subquery you use will always return just a single row and a single column for every time it runs (that is, for every row that is going to be updated). If needed, you can use MAX(), or ROWNUM to ensure you always only get 1 value
More examples:
Using Correlated Subqueries

How to Get matching records using Exists statement along with a condition on the main table

I have a problem regarding sql 'exists' statement and I will highly appreciate any kind of help.
Let me explain you what I need to accomplish.
I have two tables where I would like to get matching records from table1 which also exits in table2. Till this, it is simple. However, I also want to get those records from table1 along with matching records which has a particular column NULL in Table1. In other words I need to get those records from Table1 either they exist in Table2 or they have a specific column NULL. I wrote the following query to accomplish this.
CREATE TABLE #Table1(ID INT, Column2 INT NULL)
CREATE TABLE #Table2(ID INT)
INSERT INTO #Table1 VALUES(1, NULL)
INSERT INTO #Table2 VALUES(2)
select * from #Table1
WHERE EXISTS (SELECT NULL from #Table2 where #Table2.ID = #Table1.ID OR #Table1.Column2 IS NULL)
DROP TABLE #Table1;
DROP TABLE #Table2;
This query works when Table2 is not empty. However, if Table2 is empty then IS NULL condition does not work.
In order to resolve this I also tried adding a dummy record in case Table2 is empty by adding a union, but it does not resolve my problem either because there will always a record when I should get 0 records.
Like this
select * from #Table1
WHERE EXISTS (SELECT ID WHERE NOT EXISTS (SELECT * FROM #Table2)
UNION
SELECT NULL from #Table2 where #Table2.ID = #Table1.ID OR #Table1.Column2 IS NULL)
Note: I know this can be solved using joins but I would like to solve it using Exists statement because this is the part of a large system which simply cannot be converted to joins. I have given the above as a simple scenario.
Any kind of help would be highly appreciated.
Will this work?
WHERE EXISTS (SELECT 1 from #Table2 where #Table2.ID = #Table1.ID) OR #Table1.Column2 IS NULL
Move the condition outside the EXISTS. It is closer to how you describe the problem anyway:
select t1.*
from #Table1 t1.
WHERE t1.Column2 IS NULL OR
EXISTS (SELECT 1 from #Table2 t2 where t2.ID = t1.ID);
Notes:
Although EXISTS (SELECT NULL . . . ) is allowed an works, I find it highly misleading. In practice, NULL often represents missing values so the result is a bit of cognitive dissonance. Besides, SELECT 1 is easier to type.
I recommend table aliases; they make the query easier to write and to read.

How to select a value that can come from two different tables?

First, SQL is not my strength. So I need help with the following problem. I'll simplify the table contents to describe the problem.
Let's start with three tables : table1 with columns id_1 and value, table2 with columns id_2 and value, and table3 with columns id_3 and value. As you'll notice, a field value appears in all three tables, while ids have different column names. Modifying column names is not an option because they are used by Java legacy code.
I need to set table3.value using table1.value or table2.value according to the fields table1.id_1, table2.id_2 and table3.id_3.
My last attempt, which describes what I try to do, is the following:
UPDATE table3
SET value=(IF ((SELECT COUNT(\*) FROM table1 t1 WHERE t1.id_1=id_3) > 0)
SELECT value FROM table1 t1 WHERE t1.id_1=id_3
ELSE IF ((SELECT COUNT(\*) FROM table2 t2 WHERE t2.id_2=id_3)) > 0)
SELECT value FROM table2 t2 WHERE t2.id_2=id_3)
Here are some informations about the tables and the update.
This update will be included in an XML file used by Liquibase.
It must work with Oracle or SQL Server.
An id from table3.id_3 can be found at most once in table1.id_1 or in table2.id_2, but not in both tables simultaneously.
If table3.id_3 is not found in table1.id_1 nor in table2.id_2, table3.value remains null.
As you can imagine, my last attempt failed. In that case, the IF command was not recognized during the Liquibase update. If anyone has any ideas how to deal with this, I'd appreciate. Thanks in advance.
I don't know Oracle very well, but a SQL Server approach would be the following using COALESCE() and OUTER JOINs.
Update T3
Set Value = Coalesce(T1.Value, T2.Value)
From Table3 T3
Left Join Table2 T2 On T3.Id_3 = T2.Id_2
Left Join Table1 T1 On T3.Id_3 = T1.Id_1
The COALESCE() will return the first non-NULL value from the LEFT JOIN to tables 1 and 2, and if a record was not found in either, it would be set to NULL.
It is Siyual's UPDATE written with MERGE operator.
MERGE into table_1
USING (
SELECT COALESCE(t2.value, t3.value) as value, t1.id_1 as id
FROM table_1 t1, table_2 t2, table_3 t3
WHERE t2.id_2 = t3.id_3 and t1.id_1 = t2.id_2
) t on (table_1.id_1 = t.id)
WHEN MATCHED THEN
UPDATE SET table_1.value = t.value
This should work in Oracle.
In Oracle
UPDATE table3 t
SET value=COALESCE((SELECT value FROM table1 t1 WHERE t1.id_1=t.id_3),
(SELECT value FROM table2 t2 WHERE t2.id_2=t.id_3))
Given your assumption #3, you can use union all to put together tables 1 and 2 without running the risk of duplicating information (at least for the id's of interest). So a simple merge solution like the one below should work (in all DB products that implement the merge operation).
merge into table3
using (
select id_2 as id, value from table2
union all
select id_3, value from table 3
) t
on table3.id_3 = t.id
when matched
then update set table3.value = t.value;
You may want to test the various solutions and see which is most effective for your specific tables.
(Note: merge should be more efficient than the update solution using coalesce, at least when relatively few of the id's in table3 have a match in the other tables. This is because the update solution will re-insert NULL where NULL was already stored when there is no match. The merge solution avoids this unnecessary activity.)

sql oracle using update

I need to take data from one table to add to another table.
I got two SQL's:
SQL1:
select * from table1;
SQL2:
select * from table2 where coloumn1 = table1.coloumn6 (number)
table1 looks like:
For better understanding we call each coloumn coloumn1, coloumn2, ... coloumn9
table2 looks like:
For better understanding we call each coloumn coloumn1, coloumn2, ... coloumn13
What should happen in text
My SQL has to take the value from table1.coloumn6 (number) - checking if this value is given in table2.coloumn1
select * from table2 where coloumn1 = table1.coloumn6 (SQL2)
If yes it should update the data from table1.coloumn2 (varchar2) to table2.coloumn4 (varchar2).
If I understand correctly, you want to update table1.column2 to the corresponding value in table2.column1 based on other conditions. Based on your description:
update table1
column2 = (select column4 from table2 t2 where t2.column1 = table1.column6)
where exists (select 1 from table2 t2 where t2.column1 = table1.column6);
MERGE is good for updating/inserting tables based on other tables. Something like this should work (would be a bit more clear with distinctly-named columns). It also accepts an optional 'WHEN NOT MATCHED THEN' clause which lets you insert new records.
MERGE INTO table2
USING (SELECT column2, column6 FROM table1) table1
ON (table2.column1 = table1.column6)
WHEN MATCHED THEN
update set column4 = column2;