SQL Query to compare all the matching records - sql

I want to assign Valid Column value to a Variable if the entire result set is valid. so need to write the SQL query that checks the entire result set if the column value is valid(not null and not empty) then assign first column value to that variable else check second column with same condition and assign to variable.
For Example: If my Table has column FirstName with 100 records, I need to check Whether all the records are valid(not null or not empty) records suppose 99th record is empty then I need to check LastName column and assign it to a variable.
Thanks in advance.

You can use CASE:
SELECT
CASE
WHEN FirstName IS NULL OR FirstName = '' THEN ISNULL(LastName, '')
ELSE FirstName END
FROM
Tbl

you can use If exists to determine if the column is valid:
if not exists (select 1 from table where col1 is null)
begin
select top(1) col1 from table
end

Related

Conditional Select Statement in T-SQL

I have a table INFO with 3 columns as NAME, ID and FLAG. The condition for select statement is if NAME column is not null it should display the NAME based on the ID and FLAG values from WHERE clause.
My original query was as follows,
Select NAME from INFO where ID=101 and FLAG='Y'
This query returns the NAME if it is present for given ID and FLAG condition. But shows NULL if NAME is not present for the given ID and FLAG condition (As it should as per the T-SQL properties)
In my case I want to execute the query only if NAME column value if NOT NULL.
Till now I have used CASE condition but it does not skips the execution
select CASE NAME is not null then NAME
else 'NA' end from INFO where ID=101 and FLAG='Y'
This only replace the resultant NULL with NA, Is there a way I can execute this select only if NAME column has values
Why not add an
and name is not null
to the where clause?

what's the difference between is not null and <>' '

Look my example, what's the difference between two codes?
Select name from customers where name is not null
Select name from customers where name <> ''
They do completely different things.
Select name from customers where name is not null
This one selects any customer who has a value in the name field. Those values can include '' as well as things like 'Sam', 'John Jones', 'pretty blonde girl'.
Select name from customers where name <> ''
This will select all names that are not null or blank In Sql Server at least. Other databases may handle this differently. The reason why it also excludes Null is that Null cannot be part of a comparison since it by definition means we don't have a clue what the value of this field is.
If you wanted to return both real names and null values and only exclude the empty strings. In SQl Server you would do:
Select name from customers where coalesce(name, 'Unknown') <>''
There are a lot of correct answers here but I think you are missing what NULL is. It's nothing so it's not comparable to anything. Here's some test for you
DECLARE #param CHAR(1)=NULL --you can replace #param with your column name in your queries
SELECT 1 WHERE #param = NULL --you can't compare NULL to anything using = > < <> != or any other comparision operator
SELECT 1 WHERE #param = '' --an empty value isn't the same as a NULL value so if a NULL is present it won't be returned
SELECT 1 where #param IS NULL --this is how you have to check for null values
--If you want to check for both empty and nulls, you can force the empty string with COALESCE or ISNULL
SELECT 1 WHERE COALESCE(#param,'') = ''
SELECT 1 WHERE ISNULL(#param,'') = ''
The key concept you are missing is that in SQL Server, NULL does not mean no value, it means that the value is unknown. So consider your query with some silly sample data:
DECLARE #t TABLE
( id INT IDENTITY(1,1) PRIMARY KEY CLUSTERED
, name VARCHAR(10) NULL );
INSERT INTO #t
VALUES
('dog'),
('cat'),
(''),
(NULL);
SELECT *
FROM #t
WHERE name <> '';
What you are asking the engine is to return the records where name is not an empty string. On the evaluation of the fourth record, it is determining if NULL equals empty string or not. NULL could be empty string, we don't know ... given that the value is unknown, the engine can't include that record because you are asking for only records where we know the name is definitely not empty string.
Consider another query against the same data:
WITH cteTemp AS
(
SELECT *
, isEqualToEmptyString = CASE WHEN name = '' THEN 'true' ELSE 'false' END
FROM #t
)
SELECT *
FROM cteTemp
WHERE isEqualToEmptyString = 'false';
Now this is written to demonstrate a point and there are cleaner ways to do the same thing (such as the COALESCE in HLGEM's answer.) But understand what is happening here: the query is first determining for sure what names are empty string (which excludes the NULL since its value is unknown) and then excluding those that are. Thus, the NULL is returned.
Null and empty string are two different things. A given field in a table can either have no value (null) or a value of an empty string (''). The results return by each query will be mutually exclusive.
Is not null determines if the object/record being inspected is a true null value or not (no data).
<> '' means is not an empty string, so the record does contain data (that there is an empty string) and is not actually null.
So a query with is not null will return records with a value of string.empty, and a query with <> '' will return values that are neither null nor empty. To catch both empty strings and null values you should use <> '' in your SQL statements.

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