SQL - Return record with a null value only if there is no matching record that is not null - sql

I have a table that has some multiple entries for certain fields but not others. Here's an illustration:
I need to write a query that will return a distinct list of the 'Type' values with the numeric value if a non-null record exists, but with the null value only if there is no matching 'Type' value with a corresponding numeric value. So, for the table above, I need a recordset like this:
I thought this would be easy, but I've been scratching my head over it. Any help appreciated.

You can use aggregation:
select type, max(col2)
from t
group by type;
This guarantees that only one row is returned for each value in the first column and you only get NULL when all the values are NULL.
If you want all non-null values and a representative NULL one of the others do not exist, you can use logic like this:
select type, col2
from t
where col2 is not null
union al
select type, null
from t
group by type
having max(col2) is null;

Related

Not In operator eliminates NULL values rows in a table

I would like to retrieve all rows with values except 1,2,3,4,5 in my COLUMNA in TABLEA .
SELECT * FROM TABLEA WHERE COLUMNA NOT IN (1,2,3,4,5)
But this eliminates the rows with NULL values in COLUMNA too.
I don't want to eliminate NULL values rows and would like to include those rows in the resultset.
Alternatively, I can try below query for the same
SELECT * FROM TABLEA WHERE COLUMNA NOT IN (1,2,3,4,5) OR COLUMNA IS NULL.
But I would like to know, why is it necessary to add this OR condition?
Why is the additional necessary?
NULL comparisons almost always results in NULL, rather than true or false. A WHERE clause filters out all non-true values, so they get filtered out.
This is how SQL defines NULL. Why is NULL defined like this?
NULL does not mean "missing" in SQL. It means "unknown". So, the result of <unknown> not in (1, 2, 3, 4, 5) is "unknown", because the value could be 1 or it might be 0. Hence it gets filtered.
I will also note that the SQL standard includes NULL-safe comparisons, IS NOT DISTINCT FROM and IS DISTINCT FROM corresponding to = and <> respectively. These treat NULL as just "any other value", so two NULL values are considered equal. However, there is no construct for NULL-safe IN and NOT IN, as far as I know.
Try the following:
SELECT * FROM TABLEA WHERE ISNULL(COLUMNA,0) NOT IN (1,2,3,4,5)

Make MIN(column) return NULL if column contains NULL

SELECT MIN(column) FROM table;
will return minimum from nonnull elements.
I would like to write a query that will treat NULL as if it were the smallest value possible.
I have seen tricks with dates using a special value like here: https://stackoverflow.com/a/32240382/7810882
But what if the column is of type int and there is no special value that I can map NULL to?
You can do this using a case expression:
SELECT (CASE WHEN COUNT(*) = COUNT(COLUMN) THEN MIN(column) END)
FROM table;

Select from table with 2 condition and 2 operations

I have a Table BoxTrans
the table Contain Rows (ID,Date,FromBox,ToBox,Value)
I want to make a View like (ID,Date,Box,ValueIn,ValueOut)
select when frombox Give Value to ValueOut
and when tobox Give Value to ValueIN
You can use a CASE statement to check the value of a different column when populating a column. The below query will return your output as long as either ToBox or FromBox is NULL, if they are both not null you may get unexpected results.
SELECT ID,
Date,
COALESCE(ToBox,FromBox) as Box,
CASE WHEN ToBox IS NOT NULL THEN value ELSE NULL as ValueIn,
CASE WHEN FromBox IS NOT NULL THEN value ELSE NULL as ValueOut
FROM BoxTrans

SQL query to get null count from a column

I want to generate a SQL query to get null count in a particular column like
SELECT COUNT (column) AS count
FROM table
WHERE column = null ;
This is returning 0, but I want how many null values are present in that column like
SELECT COUNT (column) AS count
FROM table
WHERE column = 'some value';
which returns the count of the matched records
NULL value is special in that you cannot use = with it; you must use IS NULL instead:
SELECT COUNT (*) AS count FROM table where column IS null ;
This is because NULL in SQL does not evaluate as equal to anything, including other NULL values. Also note the use of * as the argument of COUNT.
You can use a conditional sum()
SELECT sum(case when column is null
then 1
else 0
end) AS count
FROM table
A different query but exact answer check it out
select count(*)-count(column) from table
please vote check this as answer if it helps you
To get exact output you can use below command as well -
SELECT COUNT (*) AS count FROM table where column IS null OR column='';
because some times only '' doesn't counted as NULL.

Null Value Statement

I have created a table called table1 and it has 4 columns named Name,ID,Description and Date.
I have created them like Name varchar(50) null, ID int null,Description varchar(50) null, Date datetime null
I have inserted a record into the table1 having ID and Description values. So Now my table1 looks like this:
Name ID Description Date
Null 1 First Null
One of them asked me to modify the table such a way that The columns Name and Date should have Null values instead of Text Null. I don't know what is the difference between those
I mean can anyone explain me the difference between these select statements:
SELECT * FROM TABLE1
WHERE NAME IS NULL
SELECT * FROM TABLE1
WHERE NAME = 'NULL'
SELECT * FROM TABLE1
WHERE NAME = ' '
Can anyone explain me?
In a CREATE TABLE, the NULL or NOT NULL here varchar(50) null is a constraint that determines whether NULLs are allowed. NOT NULL means no.
When you inserted data, which statement did you run?
INSERT TABLE1 VALUES (Null, 1, First, Null)
or
INSERT TABLE1 VALUES ('Null', 1, First, 'Null')
The first one uses the keyword NULL, inserts a NULL (not a null value: no such thing, arguably). No values is stored except in the NULL bitmap fields
The second one has a string "null" and the characters N, U, L, L + 2 bytes for length are stored
When you run SELECT * FROM TABLE1, client tools will show NULL.
To test whether you actually have NULLs or the string NULL, run this
SELECT ISNULL(name, 'fish'), ISNULL(date, GETDATE()) FROM TABLE1
For the SELECTs
--null symbols. No value stored
SELECT * FROM TABLE1 WHERE NAME IS NULL
--string null
SELECT * FROM TABLE1 WHERE NAME = 'NULL'
--empty string
SELECT * FROM TABLE1 WHERE NAME = ' '
Note: null symbol/value is not empty string. It has no value and won't compare. Even to itself.
As for your DBA, the code above with ISNULL will decide what is stored.
Edit: if you are storing null symbol/value, then your DBA should read up on "null bitmap"
The data does represent nulls. The text 'Null' is your query tool displaying the text.
One of them asked me to modify the table such a way that The columns Name and Date should have Null values instead of Text Null. I don't know what is the difference between those.
The NULL keyword indicates the absence of any value -- the value is unknown.
But that won't stop someone from storing the letters that spell out "NULL", data type providing (which INT and DATETIME will not). Because of this, operators like IS NULL would not work on text that spells out "NULL" and vice versa -- searching for strings using: ... LIKE '%NULL%' will not return records with NULL values.
The data type of the column does matter with regard to NULL in SQL Server. In a UNION statement, you need to cast NULL to be the appropriate data type -- the default for NULL is INT:
SELECT CAST('2011-01-01 00:00:00' AS DATETIME)
UNION
SELECT CAST(NULL AS DATETIME)
Based on the information provided about the columns and the output, the DBA appears to be asking you to change the text the client you are using to connect to SQL Server with displays when a NULL value is encountered in a resultset. Reminds me of my first job dishwashing, and was asked to get the lefthanded spatula...
The string "Null" is a string.
The value of NULL (or Null or null, SQL is case-insensitive when it comes to these things) is used to denote an unknown value. It's the empty set of values, if you will.
http://www.w3schools.com/sql/sql_null_values.asp
NULL, in software, is symbolic of no value. Assuming you're inserting the columns using a string with null as the value, use the null constant. e.g.
INSERT INTO table1 (Name,ID,Description,Date) VALUES (NULL,1,'First',NULL);
Note that NULL is a constant in SQL, not the word "NULL" in a string.
AFAIC, there is no different between NULLs. There are different column types. But as long as a column is a text data type, and it's NULL, it's a text NULL.
Sometimes there are questions about empty strings ("") instead of NULLs, but the description you're using doesn't seem to be referring to that.
SELECT * FROM TABLE1 WHERE NAME IS NULL
Returns all rows where the Name is NULL
SELECT * FROM TABLE1 WHERE NAME = 'NULL'
Returns all rows where the Name is equal to the string 'NULL', Null values are not returned
SELECT * FROM TABLE1 WHERE NAME = ' '
Returns all rows where the Name is equal to exactly one space ' ', Null values are not returned
If you run this statement it might help clear up when its null and when its not
select
*,
case
WHEN name is null THEN 'Its Null alright'
ELSE 'It has a value'
END
FROM TABLE1