NVL Column and NULL - sql

I have rows as shown below
ProductId ProductName ProductDesc ProductLoc
101 Camel Pencil B-10
102 Parker Pen
103 Mirado Pen C-10
When I execute the following SQL query
SELECT *
FROM tablename
WHERE productloc = NVL ('', productloc)
It gives me the 1st and 3rd row, what I would like to achieve is if productloc is null in where condition of the SQL, then I should get all three rows.
How can I get the desired output.

select * from tablename;
Is what you need in that case because your where gives no effect. You compare column with itself.
If you want to filter and include nulls you can do (but probably replace one productloc with some value:
select * from tablename where productloc = productloc or productloc is null;
Or:
select * from tablename where nvl(productloc, 'SOME_UNIQUE_VAL') = nvl(productloc, 'SOME_UNIQUE_VAL');
and also replace one of productloc by some value.

Try something like :
SELECT *
FROM tablename
WHERE nvl(productloc,'zzz') = (case when productloc is null then 'zzz' else productloc end )
Here zzz is some dummy value, which otherwise should not be present as value in particular column.

I suppose three different solutions:
If you want all rows (with productloc null and valued) you can write the following query:
SELECT *
FROM tablename
Without WHERE clause.
If you want extract all rows with productloc has a specified value or is null, so you can write the following query:
SELECT *
FROM tablename
WHERE productloc IS NULL OR productloc = YOURVARIABLE
or (the last, without use OR condition)
SELECT *
FROM tablename
WHERE NVL(productloc, YOURVARIABLE) = YOURVARIABLE

I assume you are using Oracle. In Oracle "NULL" is not a value and because of it any compare function will return false.
I recomend:
SELECT *
FROM tablename
WHERE (productloc = productloc OR productloc IS NULL)
Hope it helps,
Sérgio

Related

Conditional insert in SQL for an order system

I have a question regarding a conditional insert.
I want to be able to add the same ID in the ("tafelID" = tableID) column, ONLY if the ("betaalstatus" = pay status) is equal to true. What query do i have to use ?
I'm new to SQL. my query is below.
INSERT INTO Rekening (tafelID, betaalstatus) Select ('7', 'False')
WHERE not exists ( select 'False' )
you can replace "<...>" with the data in the nested select statement in FROM clause. you can use nested Case When statement for complex conditions.
INSERT INTO Rekening (tafelID, betaalstatus)
Select Case WHEN betaalstatus = true THEN tableID ELSE tafelID END tafelID, betaalstatus
FROM (SELECT <betaalstatus> AS betaalstatus, <tableID> AS tableID, <tafelID> AS tafelID)
-- i.e. (SELECT true AS betaalstatus, 7 AS tableID, 8 AS tafelID)

How to ask where with calling function? - SQL Server

I want to ask a Function in the where clause.
The code:
SELECT * FROM MyTable
WHERE Field1=10
and dbo.MyFunction(Field2,Field3,Field4) = NULL
And this returns me an empty table even though there are correct values in the table, why is this happening? What could be the reason?
SELECT * FROM MyTable
WHERE Field1=10
and dbo.MyFunction(Field2,Field3,Field4) **is** NULL
and not = NULL
You need to define like dbo.MyFunction(Field2,Field3,Field4) is NULL instead of dbo.MyFunction(Field2,Field3,Field4) = NULL
SELECT * FROM MyTable
WHERE Field1=10
and dbo.MyFunction(Field2,Field3,Field4) is NULL
In SQL you have to use is null or is not null instead = null.
I suggest you do not use function in your where clause it is not a good practice. You can use cte as below:
with
cte
as
(
select
* ,
dbo.MyFunction(Field2,Field3,Field4) as [your_function_field]
from
MyTable
where
Field1=10
)
where
[your_function_field] is null

Returning a default value when query does not return rows in DB2

For a query I am using, a default value will need to be returned if no rows are returned (since the output will be used downstream). The problem I'm encountering is how to programmatically identify that zero or null rows are returned so that the query knows to use the 'default' value.
SELECT DISTINCT fieldName from DB2Table
WHERE qualifier1 = '___'
AND qualifier2 = '___';
This can return either a value or nothing (as in, no rows at all). I've attempted using count(*), NOT NULL, and EXISTS() within a CASE Statement, but I've had no luck.
**Psuedocode**:
IF query returns values, return those
ELSE return "Some Value"
Any tips/insights would be greatly appreciated!
If the query doesn't return a row and a default value needs to be returned in that case, use
SELECT
COALESCE(
(SELECT DISTINCT fieldName from DB2Table
WHERE qualifier1 = '___' AND qualifier2 = '___'), 'DEFAULTVALUE'
)
FROM sysibm.sysdummy1
If you are only expecting one row, then use aggregation:
SELECT COALESCE(fieldName, 'DEFAULT VALUE')
FROM DB2Table
WHERE qualifier1 = '___' AND qualifier2 = '___';
If you could be getting multiple rows, then here is another method:
WITH t as (
SELECT fieldName
FROM DB2Table
WHERE qualifier1 = '___' AND qualifier2 = '___'
)
SELECT t.*
FROM t
UNION ALL
SELECT 'DEFAULT VALUE'
FROM sysibm.sysdummy1
WHERE NOT EXISTS (SELECT 1 FROM t);

T-SQL Comma delimited value from resultset to in clause in Subquery

I have an issue where in my data I will have a record returned where a column value will look like
-- query
Select col1 from myTable where id = 23
-- result of col1
111, 104, 34, 45
I want to feed these values to an in clause. So far I have tried:
-- Query 2 -- try 1
Select * from mytableTwo
where myfield in (
SELECT col1
from myTable where id = 23)
-- Query 2 -- try 2
Select * from mytableTwo
where myfield in (
SELECT '''' +
Replace(col1, ',', ''',''') + ''''
from myTable where id = 23)
-- query 2 test -- This works and will return data, so I verify here that data exists
Select * from mytableTwo
where myfield in ('111', '104', '34', '45')
Why aren't query 2 try 1 or 2 working?
You don't want an in clause. You want to use like:
select *
from myTableTwo t2
where exists (select 1
from myTable t
where id = 23 and
', '+t.col1+', ' like '%, '+t2.myfield+', %'
);
This uses like for the comparison in the list. It uses a subquery for the value. You could also phrase this as a join by doing:
select t2.*
from myTableTwo t2 join
myTable t
on t.id = 23 and
', '+t.col1+', ' like '%, '+t2.myfield+', %';
However, this could multiply the number of rows in the output if there is more than one row with id = 23 in myTable.
If you observe closely, Query 2 -- try 1 & Query 2 -- try 2 are considered as single value.
like this :
WHERE myfield in ('111, 104, 34, 45')
which is not same as :
WHERE myfield in ('111', '104', '34', '45')
So, If you intend to filter myTable rows from MyTableTwo, you need to extract the values of fields column data to a table variable/table valued function and filter the data.
I have created a table valued function which takes comma seperated string and returns a table value.
you can refer here T-SQL : Comma separated values to table
Final code to filter the data :
DECLARE #filteredIds VARCHAR(100)
-- Get the filter data
SELECT #filteredIds = col1
FROM myTable WHERE id = 23
-- TODO : Get the script for [dbo].[GetDelimitedStringToTable]
-- from the given link and execute before this
SELECT *
FROM mytableTwo T
CROSS APPLY [dbo].[GetDelimitedStringToTable] ( #filteredIds, ',') F
WHERE T.myfield = F.Value
Please let me know If this helps you!
I suppose col is a character type, whose result would be like like '111, 104, 34, 45'. If this is your situation, it's not the best of the world (denormalized database), but you can still relate these tables by using character operators like LIKE or CHARINDEX. The only gotcha is to convert the numeric column to character -- the default conversion between character and numeric is numeric and it will cause a conversion error.
Since #Gordon, responded using LIKE, I present a solution using CHARINDEX:
SELECT *
FROM mytableTwo tb2
WHERE EXISTS (
SELECT 'x'
FROM myTable tb1
WHERE tb1.id = 23
AND CHARINDEX(CONVERT(VARCHAR(20), tb2.myfield), tb1.col1) > 0
)

return a default record from a sql query

I have a sql query that I run against a sql server database eg.
SELECT * FROM MyTable WHERE Id = 2
This may return a number of records or may return none. If it returns none, I would like to alter my sql query to return a default record, is this possible and if so, how? If records are returned, the default record should not be returned. I cannot update the data so will need to alter the sql query for this.
Another way (you would get an empty initial rowset returned);
SELECT * FROM MyTable WHERE Id = 2
IF (##ROWCOUNT = 0)
SELECT ...
SELECT TOP 1 * FROM (
SELECT ID,1 as Flag FROM MyTable WHERE Id = 2
UNION ALL
SELECT 1,2
) qry
ORDER BY qry.Flag ASC
You can have a look to this post. It is similar to what you are asking
Return a value if no rows are found SQL
I hope that it can guide you to the correct path.
if not exists (SELECT top 1 * FROM mytable WHERE id = 2)
select * from mytable where id= 'whatever_the_default_id_is'
else
select * from mytable where id = 2
If you have to return whole rows of data (and not just a single column) and you have to create a single SQL query then do this:
Left join actual table to defaults single-row table
select
coalesce(a.col1, d.col1) as col1,
coalesce(a.col2, d.col2) as col2,
...
from (
-- your defaults record
select
default1 as col1,
default2 as col2,
...) as d
left join actual as a
on ((1 = 1) /* or any actual table "where" conditions */)
The query need to return the same number of fields, so you shouldn't do a SELECT * FROM but a SELECT value FROM if you want to return a default value.
With that in mind
SELECT value FROM MyTable WHERE Id = 2
UNION
SELECT CASE (SELECT count(*) FROM MyTable WHERE Id = 2)
WHEN 0 THEN 'defaultvalue'
END