Difference between updation with NULL and ''? [duplicate] - sql

This question already has answers here:
Why does Oracle 9i treat an empty string as NULL?
(10 answers)
Closed 9 years ago.
I have used to two queries to update one column as NULL:
update table_name
set col1 = NULL
where col2 = 'MUTHU';
update table_name
set col1 = ''
where col2 = 'MUTHU';
But when i used to query with function NVL then i am getting the same result for both queries.
select nvl(col1, 'value') from table_name;
My question is: what is the 'difference' and 'use' between NULL and '' ?

One difference is that null usually propagates so if you concat null with another string :
create table t
(
col1 varchar(10),
col2 varchar(10),
col3 varchar(10)
);
insert into t values ( null, '', 'hello' ) ;
select
concat(col1 ,col3),
concat(col2 ,col3)
from t
>> NULL, 'hello'

'' implies that the column has a value, which is an empty string
But NULL means “a missing unknown value”
so NULL cannot be compared with =, <= and so on

Related

How to check all the columns are 0 in SQL Server without specifying all columns with OR condition?

I want to return an error flag when all columns are 0s in a temp table.
Is there any good method other than specifying all columns checking to 0 with OR condition?
An OUTER APPLY can be used to calculate the flag.
For example, from this sample data:
create table #test (
id int identity(1,1) primary key,
col1 int not null,
col2 float,
col3 decimal(10,2)
);
insert into #test (col1, col2, col3) values
(1,0,0),(0,0.2,0),(0,null,0.3),(0,0,null),(0,0,0);
This query:
-- sum of nums check
select *
from #test t
outer apply (
select cast(iif(sum(abs(v.num))>0,0,1) as bit) as AllZeroOrNullFlag
from (values (col1),(col2),(col3)) v(num)
) ca
where ca.AllZeroOrNullFlag = 1;
Returns:
id col1 col2 col3 AllZeroOrNullFlag
4 0 0 NULL True
5 0 0 0,00 True
Without more information at the moment, all I can suggest you is the following :
SELECT id, 'ERROR'
FROM temp
WHERE value1+value2+value3 = 0;
Assuming you can provide all numeric columns that you would have checked in OR condition. (EDIT: In fact it would have been AND condition instead of OR...)
SEE A DEMO HERE

Concatenate two column values in SQL [duplicate]

This question already has answers here:
SQL Server: Best way to concatenate multiple columns?
(6 answers)
Closed 4 years ago.
I have two columns:
colA colB
a1 b1
NULL b2
a3 NULL
I want to concatenate both columns in a SELECT-query for the following cases:
if value of colA is NULL and colB is NULL return NULL
if value of colA is NULL and colB is NOT NULL return :b1
if value of colA is NOT NULL and colB is NULL return a1
if both values are NOT NULL return a1:b1
How can i select the appropriate values for the cases?
SELECT NULLIF(COALESCE(colA,'')+COALESCE(':'+colB,''), '') FROM myTable
Some explanation:
COALESCE returns the first not-null argument in its argument list. So the first COALESCE turns a null colA into the empty string.
The second COALESCE first prepends a colon to colB -- but if colB is null, attempting to append a string returns NULL! So the result is again the empty string if colB is null, and a colon plus colB if it wasn't.
We append the two COALESCE outputs. We now have everything the OP wanted, except that if both are null, we have the empty string. NULLIF takes care of that -- if its arguments are equal, it returns NULL, otherwise it returns the first argument.
This should do it:
DECLARE #t TABLE (cola VARCHAR(100), colb VARCHAR(100));
INSERT INTO #t VALUES
(NULL, NULL),
('a1', NULL),
(NULL, 'b1'),
('a1', 'b1');
SELECT NULLIF(CONCAT(cola, ':' + colb), '')
FROM #t
NULL
a1
:b1
a1:b1
Keep in mind that:
+ operator yields NULL if any operand is NULL
CONCAT treats NULL values as empty strings
NULLIF is there to handle the special case
;WITH col_data
As
(SELECT cols = CASE WHEN colA IS NOT NULL THEN colA ELSE '' END
+ CASE WHEN colB IS NOT NULL THEN ': '+colB ELSE '' END
FROM CTE
)
SELECT ISNULL(cols, '') from col_data;

How To Insert 2 Values in 2 columns and rest null values in rest columns without using Create Table Statement

Please Check this Sample Sql fiddle:http://www.sqlfiddle.com/#!3/f59ae.
In this way only i want output.first 2 columns Should contain values that can be anything
and rest columns should contain Hello values without considering Create Table statement.
I want to write a query that will insert 2 values into 2 columns and Hello into all other columns.
Suppose I have 100 columns then I want 10 and 20 values to be inserted into col1 and col2 and Hello into all other 98 columns.
Likewise if I have 200 columns then I want 10 and 20 values to be inserted into col1 and col2 and Hello into the other 198 columns.
I have written a query which but I thought it's a basic query so I am not writing here. So downvoters please consider that.
How to write this query???
You can do this by just adding the Default constraint to column's which you don't want to insert values explicitly. I hope #Manish Pant's answer should help you to do that.
Based on your comments you want do this only by using query. So you need to use Dynamic sql to do this.
Simple Demo
Schema
CREATE TABLE [dbo].[Test](
[id] [int] IDENTITY(1,1) NOT NULL,
[Country] [varchar](100) NULL,
[State] [varchar](100) NULL,
[City] [varchar](100) NULL,
[Population (in Millions)] [varchar](100) NULL
)
Declare a variable to hold the Dynamic sql
DECLARE #cl_val NVARCHAR(max)='Insert into Test('
Pull all the columns from sys.columns view and filter the identity column
SELECT #cl_val += Quotename(NAME) + ','
FROM sys.columns
WHERE Object_name(object_id) = 'Test'
AND is_identity <> 1
ORDER BY NAME
SELECT #cl_val = LEFT(#cl_val, Len(#cl_val)-1) + ') values (' -- Remove the trailing comma
Here add the values only to the column in case statement which you are explicitly passing value in else part add the default value
SELECT #cl_val += CASE
WHEN NAME ='City' THEN '''A'''
WHEN NAME='country' THEN '''c'''
ELSE '''Hello'''
END + ','
FROM sys.columns
WHERE Object_name(object_id) = 'Test'
AND is_identity <> 1
ORDER BY NAME
SELECT #cl_val = LEFT(#cl_val, Len(#cl_val)-1) + ')' -- Remove the trailing comma
--PRINT #cl_val
EXEC Sp_executesql #cl_val
select * from test
Result
id Country State City Population (in Millions)
-- ------- ----- ---- ------------------------
1 c Hello A Hello
If All other columns are set as Nullable then into your Insert statement you can write statement By without considering your Nullable fields.
Suppose for example your Table named Student with properties is:
Student ::
Name,
RollNo,
OptionalField_1,
OptionalField_2,
OptionalField_3
where columns with OptionalField are Nullble fields.
In this case you can write your Query simply as ::
INSERT INTO Student (Name,RollNo) VALUES ('MyName',12);
So this will make an ENtry with two column values & all remaining as Nullable.
For your better understandings you can refer :: http://www.w3schools.com/sql/sql_insert.asp
You can use this for your query:
create table mytable(
col1 varchar not null,
col2 varchar not null,
col3 varchar not null default 'Hello',
col4 varchar not null default 'Hello',
col5 varchar not null default 'Hello',
so on...... );
insert into mytable(col1,col2) values('10','20');

SQL Column 2 change from NULL to NOT NULL if the value of Column 1 is 1

I have an sql table with let say col1 and col2, i want to create a constraint or a trigger (whatever works) such that col2 should change from NULL to Not Null if and only if the value entered in col1 is 1.
The point is, i want to make a col2 field mandatory if col1 is set to 1 otherwise remain optional.
You mention SQL Server in a comment
CREATE TABLE YourTable
(
Col1 INT,
Col2 VARCHAR(25) NULL,
CONSTRAINT ck_foo CHECK (NOT (Col1 = 1 AND Col2 IS NULL))
);
would disallow NULL as stated in the question. To also disallow empty strings the constraint definition could be
CONSTRAINT ck_foo CHECK (NOT (Col1 = 1 AND ISNULL(Col2,'') = ''))
ALTER TABLE YourTable WITH CHECK ADD CONSTRAINT [CK_YourTable] CHECK (([col1]=(1) AND [col2] IS NOT NULL OR [col1]<>(1)))
GO
If you want to exclude empty string too then:
ALTER TABLE YourTable WITH CHECK ADD CONSTRAINT [CK_YourTable] CHECK (([col1]=(1) AND ( [col2] IS NOT NULL AND [col2] <> '') OR [col1]<>(1)))
GO

SQL Null values and non-Null values

I have a table that looks like this:
ID (pk,int)
Col1 (nvarchar)
Col2 (nvarchar)
Col3 (nvarchar)
In all columns (except ID) some values are NULL.
I want to make a query that will look like this:
SELECT * FROM Table
WHERE (Col1=<parameter> AND Col1 IS NULL)
+ (Col2=<parameter> AND Col2 IS NULL)
etc.
I need values that are NULL and that are equal to parameter
Thanks
Your question, specifically the bit "I need values that are NULL and that are equal to parameter", makes no sense. The where clause:
Col1 = <parameter> AND Col1 IS NULL
will never be true, since a column is either NULL or something. It can't be both at the same time.
If you mean you want values that are equal to the parameter OR NULL, you should use:
Col1 = <parameter> OR Col1 IS NULL
Replace the AND with OR in your WHERE statements.
WHERE (Col1=<parameter> OR Col1 IS NULL)
ANd (Col2=<parameter> OR Col2 IS NULL)