Handle missing data in SQL Server 2012 SELECT statement [closed] - sql

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 7 years ago.
Improve this question
create table t1 (col1 int);
Leave the table empty.
select isnull(col1,0) from t1;
I want to replace null with zeros in the above case. However, ISNULL() does not work if there are no records in the table. How can I get around this?

Maybe you can first test if the table is empty:
IF NOT EXISTS (select * from t1)
SELECT 0
ELSE select coalesce(col1,0) from t1;
Anyway, you should use COALESCE instead of ISNULL because it is standard SQL.

In case if you want to replace non existing value then surround another null check of mentioned select statement. like this
ISNULL(select isnull(col1,0) from t1,0)

COALESCE(col1, 0)
will give you the first non-NULL value from the list, which is
col1 if col1 does not contain NULL
0 if col1 contains NULL.

If no record exists in the table , your query returns EMPTY not NULL .
You can transform the EMPTY value into a NULL value and then switch it to 0 like this :
SELECT ISNULL((SELECT col1 FROM tl),0) AS col1;

When I want to return exactly one row from a table that might be empty or have an arbitrary number of rows, then I often use aggregation:
select coalesce(max(col1), 0)
from t1;
This is guaranteed to return exactly one row. It is unclear what you want when the table is not empty, however.

If you absolutely must have a value returned for an empty table, maybe something like:
if ((select COUNT(*) from t1) = 0)
begin
select 0 as col1;
end
else
begin
select isnull(col1,0) as col1 from t1;
end

The left join will get a hard coded table, OneZero, even with no rows in t1.
select isnull(t1.col1, OneZero.zero)
from ( values(0) ) as OneZero (zero)
left join t1
on 1 = 1

Related

How to use RAND() in SQL [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 8 days ago.
Improve this question
I want to randomly choose a row in a column and change the values. I’m not too sure where Rand function goes.
To be more specific, I have a table with names in it but I want to randomly select one of the names from the first name column and change it to a different name of my choosing using the UPDATE and RAND() function and it can't be NEWID(). What parameters do I need inside the parenthesis as well?
I am using SQL Server Express
I tried starting the code out with
UPDATE table name
SET column name1 = ‘new name’, column name2 = 'new name 2'
WHERE column name = (SELECT RAND()(column name-column name)+column name
from table name);
We can use NEWID() to fetch a random row, see the documentation, especially part D.
Here an example how to use it:
Create a table with some sample data:
CREATE TABLE yourtable (yourcolumn varchar(100));
INSERT INTO yourtable VALUES ('A'),('B'),('C'),('D'),('E');
Update one randow row of this table:
UPDATE yourtable SET yourcolumn = 'HelloWorld'
WHERE yourcolumn = (SELECT TOP 1 yourcolumn FROM yourtable ORDER BY NEWID());
If we want to set the value of that column in one random row to a random existing value of another row rather than to a hardcoded string, we could use NEWID() two times, something like this:
UPDATE yourtable SET yourcolumn =
(SELECT TOP 1 yourcolumn FROM yourtable ORDER BY NEWID())
WHERE yourcolumn = (SELECT TOP 1 yourcolumn FROM yourtable ORDER BY NEWID())
Try out here

SQL Server - check more than 1 value in where condition [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 9 months ago.
Improve this question
SELECT *
FROM table1
WHERE (#Id IS NULL
OR (a.ID = #Id)
OR (SELECT * FROM Table2 WHERE TestID = #Id) // How to check multiple values here
The above query works fine when TestID has single record. But when more than 1 record present in TestID column, I am trying to implement and not got exact solution.
How to confirm #Id value present in TestId column?
Could you please assist me on this? Thank you
It looks like you need exists
or exists (
SELECT * FROM Table2 WHERE TestID = #Id
)
Use top 1 before * from this way you will always get a single row in case there are multiple rows for the same #ID.
SELECT top 1 * FROM Table2 WHERE TestID = #Id
Though I am not sure how this line works in where clause as it does not return any boolean

Reference a variable created with a case Statement [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 4 years ago.
Improve this question
I have my database up and running and can do some basic selects using SQL Server 2017 Management Studio. The problem I'm running into now is a have a table that depending on the values within a row, a certain outcome is generated. I have the below code which currently works.
I'm running into issues what I try to reference Master_Status when I'm writing another case.
Basically I need do say if Master_Status is null after the first check then allow it to go into the second criteria, etc. Have about 10 outcomes I need to build this out for.
Is this possible? Should I be using reference tables?
EDIT
Below better represents my problem: I'm trying to loop through a bunch of critera to determine the end status of a sale. The sale can only have a unique status which is why I'd like to check if master_status is null.
WITH MasterStatus AS
(
SELECT
[Name]
,case WHEN saleDate is not Null then 'outcome1'
else NULL end as 'Master_Status'
,case when SaleSize is not NULL and Master_Status is Null then
'Outcome2'
else NULL end as 'Master_status'
from [AllNames]
)
select
[Name]
from MasterStatus where Master_Status is not null
Based on the current iteration of your query, it seems you're struggling with how CASE expressions work. Rather than trying to use multiple CASE expressions to assign values to the same column (which won't work), you need one CASE expression with multiple WHEN conditions.
WITH MasterStatus AS
(
SELECT
Name
,CASE
WHEN saleDate IS NOT NULL
THEN 'Outcome1'
WHEN SaleSize IS NOT NULL
THEN 'Outcome2'
--...
WHEN ColumnN IS NOT NULL
THEN 'OutcomeN'
ELSE NULL
END AS Master_Status
FROM
AllNames
)
SELECT
Name
FROM
MasterStatus
WHERE
Master_Status IS NOT NULL;
The WHEN conditions will be evaluated in order, and on the first WHEN that evaluates to TRUE, the corresponding THEN value will be assigned to the column alias, Master_Status.
What you have actually already works, I believe your case statement is just ALWAYS true (so Master_Status is always not null.
See below:
declare #allnames as table ([name] int);
insert into #allnames([name])
values (1),(0)
;WITH MasterStatus as (
select
[name]
,case WHEN [name] = 1 then 'outcome1'
else NULL end as 'Master_Status'
from #allnames
)
select
[name]
from MasterStatus where Master_Status is not null

Usage of DISTINCT in Oracle [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 4 years ago.
Improve this question
Why my query is still showing the duplicate tuples?
I want all the attributes of all distinct tuples
select distinct * from employees;
I think your approach related to NULL values and empty strings maybe the cause of the problem :
create table tab( id int, value varchar2(75));
insert into tab values(1,' ');
insert into tab values(1,' ');
insert into tab values(1,'');
insert into tab values(1,null);
select distinct * from tab;
ID VALUE
-- -----
1
1
1 (null)
select id, length(value) as value from tab;
ID VALUE
-- -----
1 2
1 1
1 (null)
1 (null)
Oracle considers '' as NULL but the empty strings with length >= 1 is not considered as NULL.
SQL Fiddle Demo
If yours columns have some " " , you'll find duplicate because
Value1 value 2 " " is not
Value1 value 2 "" nor
value1 value2 NULL
Plus, PrimaryKey is always unique so
select distinct *, is unique
Often, if you need "select unique" in table employee, there a problem of conception because every employe should appears only once (if it is a real table employe without been linking)
To fix this during import you would have to trim whitespace from the end of the string, this should take care of those 3 different characters. Note that LTRIM and RTRIM only removes "blanks" which further down in the documentation suggests that only spaces are considered. You would thus have to use a different trim function, like in the programming language you're using, to do this trimming.
If you need all distinct results for a tuple then you should not use * (all column) but explicitly select for only the columns involved in tuple
select distinct col1, col2, col3 from employees;
Typically using all column selector (*) you select also the primary key from your table that typically (by definition) is not duplicated so using select * ...
you get all the rows in table.

WHERE statement that selects everything (content and NULL) [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
How do you return all possibilities, whether there is content or it is NULL?
If I want to return everything that isn't NULL:
SELECT * FROM table WHERE column LIKE '%'
And if I want to return all NULLs:
SELECT * FROM table WHERE column IS NULL
How do I combine them both? I need to be able to because I am parameterizing it. The front end of my application will have multiple options ALL (any content or NULL) or a specific value.
How can I achieve this?
EDIT:
Let me clarify better. I have a dropdown List that will show things like this
-Select All-
Team A
Team B
...
So if -Select All- is selected then I need the query to return all NULLs and those with any Team
If Team A is selected I need to show only Team A and no NULLs and so on...
I cant change the query just a single variable (parameter)
WHERE column LIKE '%' OR column IS NULL
Assuming NULL as the parameter value means "All"
WHERE Team = #Team OR #Team IS NULL
Unless you are on 2008+ and use OPTION (RECOMPILE) this can give sub optimal plans though.
See Dynamic Search Conditions in T-SQL
It's fairly straightforward. To only get NULLS:
SELECT * FROM table
WHERE column IS NULL
To only get NOT NULLS:
SELECT * FROM table
WHERE column IS NOT NULL
-- could be this if your example is not representative
-- WHERE column IS NULL OR column LIKE '%whatever%'
And for everything (no filter), just do:
SELECT * FROM table
Further clarification:
In your example, if the code is already written and you can only pass in the WHERE clause then you could do this:
WHERE <insert here>
column IS NULL -- just nulls
column = 'teamX' OR column IS NULL -- nulls or 'teamX'
column IS NOT NULL -- any value, but no nulls
1=1 -- for the case where you don't really want a WHERE clause. All records
It doesn't sound like this is the best way of structuring your code, but if you are already restricted by something that can't be changed, I guess you have to make do.
If I understood your question then this is what you are looking for
SELECT *
FROM table
WHERE column LIKE '%' or column Is null
Does select * from table get you what you want?
Perhaps you mean "parameter can be passed or parameter can be NULL" ?
If so then something like this should do the trick
SELECT * FROM table WHERE param IS NULL OR column LIKE '%' + param '%'
Similarly if parameter passed keyword 'ALL' that means "select everything" it would be
SELECT * FROM table WHERE param = 'All' OR column LIKE '%' + param '%'
One case is not to use any where clauses.
Or else you can use or condition
where (column is null or column like '%something%')
Try something like this:
SELECT * FROM table WHERE column LIKE '%'
Union
SELECT * FROM table WHERE column IS NULL
It will combine both query if they have the same column name and number, since the only difference is where clause, it should be working