query to check if record exists and column null - oracle

I have a table and i have to check a particular column in null or has value.
Lets say the column name is order_price.
If i just check where order_price is null then this also includes records that are not in the table too.
For example i have order_id = 1 whose order_price is null and i have order_id = 2 which does not exist in order table. So instead of a where condition to check whether order_price is null, i want to know whether the column is null or the record does not exist.
I'm doing outer join on this table so i cannot map the primary keys of another table. I am using Oracle.
Thanks

SELECT o.*,
od.order_price,
CASE
WHEN od.order_id IS NULL THEN
'Not exists'
WHEN od.order_price IS NULL THEN
'Exists, IS NULL'
ELSE
'Exists, IS NOT NULL'
END AS nullness
FROM orders o
LEFT JOIN
order_data od
ON od.order_id = o.id

Instead of a Join , you can use the "EXISTS / NOT EXISTS" keyword and a subquery.
e.g.
SELECT parent.*
FROM parent
WHERE EXISTS (SELECT 1
FROM child
WHERE child.id_parent = parent.id AND child.somecolumn IS NULL)
You can play with "exists / not exists" depending on whether you want or don't want the predicate to match.

Related

Oracle Join with operation returning null values

I'm trying to Right join two table on a column named "compte"
I need to do an addition after. The problem is that some "compte" doesn't exist in one of the table and as a result, the addition return null instead of keeping the based value
Here's the query
SELECT t.compte,t.posdev+x.mnt
FROM (
SELECT compte,SUM(mntdev) as mnt FROM mvtc22
WHERE compte IN ('11510198451','00610198451','40010198451','40010198453','00610198461','00101980081','00101980094',
'00101980111','40010198461','40010198462','40010198466','40010198463')
AND datoper BETWEEN '01/01/22' AND '06/01/22'
GROUP BY compte
)x
RIGHT OUTER JOIN
(
SELECT c.compte,c.posdev
FROM v_sldoper c
WHERE c.compte IN ('11510198451','00610198451','40010198451','40010198453','00610198461','00101980081','00101980094',
'00101980111','40010198461','40010198462','40010198466','40010198463')
AND datpos = '31/12/21'
)t
ON t.compte = x.compte
And the results :
I'm expecting to keep the results from the second subquery if there's no "compte" in the first subquery.
Thanks In advance,
Alex
You are very close, the problem is that in oracle SQL the result of any value + null value is null, so you need to handle potential null values from each column before applying the + operator betwen them.
To solve the issue, you can apply functions like NVL or decode or even CASE WHEN for that purpose.
Below I use NVL function to solve it (I assume t.posdev column cannot contain null values, otherwise apply nvl function to both columns).
SELECT t.compte, t.posdev + NVL(x.mnt, 0)
FROM (
SELECT compte,SUM(mntdev) as mnt FROM mvtc22
WHERE compte IN ('11510198451','00610198451','40010198451','40010198453','00610198461','00101980081','00101980094',
'00101980111','40010198461','40010198462','40010198466','40010198463')
AND datoper BETWEEN '01/01/22' AND '06/01/22'
GROUP BY compte
)x
RIGHT OUTER JOIN
(
SELECT c.compte,c.posdev
FROM v_sldoper c
WHERE c.compte IN ('11510198451','00610198451','40010198451','40010198453','00610198461','00101980081','00101980094',
'00101980111','40010198461','40010198462','40010198466','40010198463')
AND datpos = '31/12/21'
)t
ON t.compte = x.compte

Laravel JOIN query with 2 conditions out of which one is NULL

I need a query where I want to join tables, on 2 conditions in OR. Out of these 2 condition is to check whether the column IS NULL.
$query->select('users.*', 'o.name', 'r.name')
->join('owners as o', 'users.owner_id', '=', 'o.id')
->join('residents as r', 'users.resident_id', '=', 'r.id');
In the above query I also want to check if the users.resident_id IS NULL i.e., users.resident_id = r.id OR users.resident_id IS NULL.
Thanks for your time and help in advance.
i haven't try this..
how about use "right join" sql..
from w3school..
SQL RIGHT JOIN Keyword. The RIGHT JOIN keyword returns all records from the right table (table2), and the matched records from the left table (table1). The result is NULL from the left side, when there is no match.
if this not working then use "whereIn"..
select all id with null data first, then select all id from join.. then you can use whereIn to select all data with id from data1 and data2..

Constraint check if row and other row not null on same time

I have a school 'project' to work on, which has some tables and one table needs to have a constraint which is not working out for me.
There are some tables like QUESTION, ANSWER and REACTION.
A reaction belongs with or a question or a answer but not both on the same time.
There by I have 2 rows:
question_id NUMBER,
answer_id NUMBER,
Both not null because the cant by null, but not on the same time.
I already made a constraint but isn't working..
/* CHECK if reaction belongs to an question or a answer NOT WORKING YET*/
CONSTRAINT CHECK_question_or_answer CHECK((answer_id != NULL AND question_id = NULL) OR (answer_id = NULL OR question_id != NULL))
Already tested the constraint and I can insert a value without a question_id or answer_id.
I hope it's a bit clear, if not, I am happy yo try explain myself better.
(still newby on SQL)
Thanks.
Your constraint:
CONSTRAINT CHECK_question_or_answer CHECK((answer_id != NULL AND profile_id = NULL) OR (answer_id = NULL OR profile_id != NULL))
Is always FALSE.
You need to use IS NULL or IS NOT NULL like:
CONSTRAINT CHECK_question_or_answer CHECK((answer_id IS NOT NULL AND profile_id IS NULL) OR (answer_id IS NULL OR profile_id IS NOT NULL))
This is because comparison operators != , = , > , <, combined with NULL produce NULL and are treated as false.
Demo:
SELECT 1
FROM dual
WHERE 1 IS NOT NULL;
SELECT 1
FROM dual
WHERE 1 != NULL;
From doc:
NULL values represent missing or unknown data. NULL values are used as
placeholders or as the default entry in columns to indicate that no
actual data is present. The NULL is untyped in SQL, meaning that it is
not an integer, a character, or any other specific data type.
Note that NULL is not the same as an empty data string or the
numerical value '0'. While NULL indicates the absence of a value, the
empty string and numerical zero both represent actual values.
While a NULL value can be assigned, it can not be equated with
anything, including itself.
Because NULL does not represent or equate to a data type, you cannot
test for NULL values with any comparison operators, such as =, <, or
<>.
The IS NULL and IS NOT NULL operators are used to test for NULL
values.
Do it the other way around. Put the id of the main table in the others like that
question table
--------------
id
text
...
answers table
-------------
id
question_id
text
...
reactions table
---------------
id
question_id
text
...
And question_id is never null. Then you can use a left join to get the results from both tables - one of them will have no results.
select *
from questions q
left join answers a on a.question_id = q.id
left join reactions r on r.question_id = q.id
While #lad2025s answer is good for two columns, if you wanted to extend the method to more than two it can get a bit cumbersome.
A flexible alternative is:
check ((case when answer_id is null then 0 else 1 end +
case when question_id is null then 0 else 1 end ) = 1)
It extends well to checking for a particular count of null (or non-null) values for an arbitrary number of columns.
For example, if you had column_1, column_2, column3, and column_4, and wanted at least 1 of them to be non-null, then:
check ((case when column_1 is null then 0 else 1 end +
case when column_2 is null then 0 else 1 end +
case when column_3 is null then 0 else 1 end +
case when column_4 is null then 0 else 1 end ) >= 1)

Oracle SQL Query to get missing date from two joined tables

I'm trying to write a Oracle SQL query and I'm unable to get the right result.
For the tables below, I would like to first get all records from DEVICE where DEVICE.MODEL='UNITA' and for those results, give me the DEVICE.CUSTOMER_ID's who don't have a record where PROFILE.TYPE='TEST' joining both tables on CUSTOMER_ID. Any ideas on how to formulate this query?
TABLE DEVICE:
ID - sequence generated primary key (NUMBER (10))
DEVICE_NUMBER - unique (varchar)
CUSTOMER_ID (varchar)
MODEL (varchar)
TABLE PROFILE:
ID - sequence generated primary key (NUMBER (10))
CUSTOMER_ID (varchar)
TYPE (varchar)
If I understand the requirement, this should do the trick:
SELECT d.ID, d.Device_Number, d.Customer_ID, d.Model
FROM Device d
LEFT JOIN Profile p ON d.Customer_ID = p.Customer_ID
WHERE d.Model = 'UNITA'
AND (p.ID IS NULL OR p.Type = 'TEST')
It works because of the LEFT JOIN, which will make Profile.ID NULL if there's not a matching Profile row for the Customer_ID. If there is a matching row, the test for Profile.Type = 'TEST' will determine what's included.
There's a SQL Fiddle here. The Fiddle includes the Profile.ID and Profile.Type values in the results because I think they help explain things more clearly.
Addendum: Some confusion on my part over the requirements; this query may be closer to what's needed:
SELECT d.ID, d.Device_Number, d.Customer_ID, d.Model, p.id AS pid, p.type
FROM Device d
LEFT JOIN Profile p ON d.Customer_ID = p.Customer_ID AND p.Type = 'TEST'
WHERE d.Model = 'UNITA'
AND p.ID IS NULL

Reference parent query column in subquery (Oracle)

How can I reference a column outside of a subquery using Oracle? I specifically need to use it in the WHERE statement of the subquery.
Basically I have this:
SELECT Item.ItemNo, Item.Group
FROM Item
LEFT OUTER JOIN (SELECT Attribute.Group, COUNT(1) CT
FROM Attribute
WHERE Attribute.ItemNo=12345) A ON A.Group = Item.Group
WHERE Item.ItemNo=12345
I'd like to change WHERE Attribute.ItemNo=12345 to WHERE Attribute.ItemNo=Item.ItemNo in the subquery, but I can't figure out if this is possible. I keep getting "ORA-00904: 'Item'.'ItemNo': Invalid Identifier"
EDIT:
Ok, this is why I need this kind of structure:
I want to be able to get a count of the "Error" records (where the item is missing a value) and the "OK" records (where the item has a value).
The way I have set it up in the fiddle returns the correct data. I think I might just end up filling in the value in each of the subqueries, since this would probably be the easiest way. Sorry if my data structures are a little convoluted. I can explain if need be.
My tables are:
create table itemcountry(
itemno number,
country nchar(3),
imgroup varchar2(10),
imtariff varchar2(20),
exgroup varchar2(10),
extariff varchar2(20) );
create table itemattribute(
attributeid varchar2(10),
tariffgroup varchar2(10),
tariffno varchar2(10) );
create table icav(
itemno number,
attributeid varchar2(10),
value varchar2(10) );
and my query so far is:
select itemno, country, imgroup, imtariff, im.error "imerror", im.ok "imok", exgroup, extariff, ex.error "exerror", ex.ok "exok"
from itemcountry
left outer join (select sum(case when icav.itemno is null then 1 else 0 end) error, sum(case when icav.itemno is not null then 1 else 0 end) ok, tariffgroup, tariffno
from itemattribute ia
left outer join icav on ia.attributeid=icav.attributeid
where (icav.itemno=12345 or icav.itemno is null)
group by tariffgroup, tariffno) im on im.tariffgroup=imgroup and imtariff=im.tariffno
left outer join (select sum(case when icav.itemno is null then 1 else 0 end) error, sum(case when icav.itemno is not null then 1 else 0 end) ok, tariffgroup, tariffno
from itemattribute ia
left outer join icav on ia.attributeid=icav.attributeid
where (icav.itemno=12345 or icav.itemno is null)
group by tariffgroup, tariffno) ex on ex.tariffgroup=exgroup and extariff=ex.tariffno
where itemno=12345;
It's also set up in a SQL Fiddle.
You can do it in a sub-query but not in a join. In your case I don't see any need to. You can put it in the join condition.
select i.itemno, i.group
from item i
left outer join ( select group, itemno
from attribute b
group by group itemno ) a
on a.group = i.group
and i.itemno = a.itemno
where i.itemno = 12345
The optimizer is built to deal with this sort of situation so utilise it!
I've changed the count(1) to a group by as you need to group by all columns that aren't aggregated.
I'm assuming that your actual query is more complicated than this as with the columns you're selecting this is probably equivilent to
select itemno, group
from item
where itemno = 12345
You could also write your sub-query with an analytic function instead. Something like count(*) over ( partition by group).
As an aside using a keyword as a column name, in this case group is A Bad Idea TM. It can cause a lot of confusion. As you can see from the code above you have a lot of groups in there.
So, based on your SQL-Fiddle, which I've added to the question I think you're looking for something like the following, which doesn't look much better. I suspect, given time, I could make it simpler. On another side note explicitly lower casing queries is never worth the hassle it causes. I've followed your naming convention though.
with sub_query as (
select count(*) - count(icav.itemno) as error
, count(icav.itemno) as ok
, min(itemno) over () as itemno
, tariffgroup
, tariffno
from itemattribute ia
left outer join icav
on ia.attributeid = icav.attributeid
group by icav.itemno
, tariffgroup
, tariffno
)
select ic.itemno, ic.country, ic.imgroup, ic.imtariff
, sum(im.error) as "imerror", sum(im.ok) as "imok"
, ic.exgroup, ic.extariff
, sum(ex.error) as "exerror", sum(ex.ok) as "exok"
from itemcountry ic
left outer join sub_query im
on ic.imgroup = im.tariffgroup
and ic.imtariff = im.tariffno
and ic.itemno = im.itemno
left outer join sub_query ex
on ic.exgroup = ex.tariffgroup
and ic.extariff = ex.tariffno
and ic.itemno = ex.itemno
where ic.itemno = 12345
group by ic.itemno, ic.country
, ic.imgroup, ic.imtariff
, ic.exgroup, ic.extariff
;
You can put WHERE attribute.itemno=item.itemno inside the subquery. You are going to filter the data anyway, filtering the data inside the subquery is usually faster too.

Resources