How to return a default value when a column value is null in SQL - sql

How to return a default value when a column value is null in SQL

You can use COALESCE. Please refer https://www.sqlshack.com/using-the-sql-coalesce-function-in-sql-server/ for more info.
SELECT COALESCE (NULL,'A')

IsNull is used when the value is null and you want a default value to return.
Select IsNull(YourColumn, defaultvalue)
i.e.
Select IsNull( CandidateName , ''), -This is string column and return default value ''
IsNull(CandidateSalaryExpected, 0), --This is Integer/Double/Numeric column and return default value 0
IsNull(MaritalStatus , 0) --0 - marital means unmarried, 1 means married. This is boolean value
You can use Coalesce value too. Check the below link.
SQL Select Return Default Value If Null

Seems you are trying to fulfill your column with default value when any NULL value found.
You could try this:
SELECT COALESCE([dbo].YourTableName.[YourColumnName],'Default Value When Null Encountered') AS YourTableAlias FROM [dbo].[YourTable]
Test With Real Sample:
See my Table Column below where some FlatName is NULL
Real Query For Default Value When NULL Found:
SELECT FlatId,COALESCE([dbo].[Flat].[FlatName],'Default Value When Null Encountered') AS FlatName, FlatDescription FROM [dbo].[Flat]
Output Of Query:

Instead of returning default value, you can design your table to add default value if the value is not provided. See below example
CREATE TABLE DemoTable
(
ID INT,
Name VARCHAR(100),
RecordAddedOn DATETIME DEFAULT GETDATE()
)
You cane take a look at below link to have a better idea about default constraint. Default Constraint
However, if you want to return default value, you can use ISNULL(ColumnName, ‘Default Value’)

Related

replace 'null' strings with NULL in sql

I wanted to check my column. If there was a 'null' string, I wanted to replace it with a NULL value. This works but is there a better way to do it? Such that I don't have to repeat the same thing twice JSON_DATA :"ContactPerson"::STRING
SELECT
IFF(JSON_DATA :"ContactPerson"::STRING = 'null',NULL, JSON_DATA :"ContactPerson"::STRING) AS "ContactPerson",
FROM TEST_TABLE
I want to use REPLACE or REGEX_REPLACE instead.
Using IS_NULL_VALUE could be a bit shorter:
SELECT
IFF(IS_NULL_VALUE(JSON_DATA:"ContactPerson"), NULL,
JSON_DATA :"ContactPerson"::STRING)
FROM TEST_TABLE;
or NULLIF:
Returns NULL if expr1 is equal to expr2, otherwise returns expr1.
SELECT NULIF(JSON_DATA :"ContactPerson"::STRING, 'null')
FROM TEST_TABLE;
Regarding comments:
Still, how would regex_replace be used? REGEXP_REPLACE( , [ , , , , ] )what would the subject be here?
REGEXP_REPLACE(JSON_DATA :"Business_Type"::STRING, 'null', NULL) AS "BS2",but this would give me NULL if "null" doesn't exist in the original value
CREATE FUNCTION:
CALLED ON NULL INPUT
Specifies the behavior of the UDF when called with null inputs. In contrast to system-defined functions, which always return null when any input is null, UDFs can handle null inputs, returning non-null values even when an input is null
and REPLACE function has this behaviour described explicitly"
If any of the arguments is a NULL, the result is also a NULL.

Convert 'NULL' to Date in SQL

I have a column in my table called startdate. It is in string format. Most of the fields are 'NULL'. I am copying this column to another table which data type is 'Date'.
How can I convert all the values from string to Date in SQL.
I have tried this code:
INSERT INTO Destination_Table [new_date]
SELECT CONVERT(DATE,[startdate],103)
FROM Source_Table
nullif([startdate],'NULL') returns [startdate] unless it equals to 'NULL' and then it returns NULL (a real NULL, not the string 'NULL')
INSERT INTO Destination_Table [new_date]
SELECT CONVERT(DATE,nullif([startdate],'NULL'),103)
from Source_Table
For learning purposes, here are some expressions with the same results:
nullif(x,y)
case when x=y then null else x end
case x when y then null else x end
It looks like you are using MSSQL. If you are using MSSQL 2012, the following code should work :
INSERT INTO Destination_Table [new_date]
SELECT IIF([startdate] = "NULL", null, CONVERT(DATE,[startdate],103))
FROM Source_Table
What this does, is use the IIF() method to check the value of [startdate] and if the value is the text "NULL", then return the actual null value which can be allowed in most fields unless you have null disabled on the Destination_Table.[new_date] field.
Since the Date field can only accept and store Date/Time/Date&Time/(actual null) information, the text "NULL" is not valid.
Following is the equivalent for MySQL
INSERT INTO Destination_Table [new_date]
SELECT IF([startdate] == 'NULL', null, CONVERT(DATE,[startdate],103))
FROM Source_Table
(although I am unsure MySQL allows a conversion code as a param to CONVERT() )

Insert null/empty value in sql datetime column by default

How do I create a table in SQL server with the default DateTime as empty, not 1900-01-01 00:00:00.000 that I get?
I mean, if there is no value inserted, the default value should be null, empty, etc.
if there is no value inserted, the default value should be null,empty
In the table definition, make this datetime column allows null, be not defining NOT NULL:
...
DateTimeColumn DateTime,
...
I HAVE ALLOWED NULL VARIABLES THOUGH.
Then , just insert NULL in this column:
INSERT INTO Table(name, datetimeColumn, ...)
VALUES('foo bar', NULL, ..);
Or, you can make use of the DEFAULT constaints:
...
DateTimeColumn DateTime DEFAULT NULL,
...
Then you can ignore it completely in the INSERT statement and it will be inserted withe the NULL value:
INSERT INTO Table(name, ...)
VALUES('foo bar', ..);
Even if your column is nullable, inserting an empty string will set the value to 1900-01-01 00:00:00.000. Make you insert real nulls not strings, then the db will store a null.
define it like your_field DATETIME NULL DEFAULT NULL
dont insert a blank string, insert a NULL INSERT INTO x(your_field)VALUES(NULL)
Ozi, when you create a new datetime object as in
datetime foo = new datetime();
foo is constructed with the time datetime.minvalue()
in building a parameterized query, you could check to see if the values entered are equal to datetime.minvalue()
-Just a side thought. seems you have things working.
I was having the same issue this morning. It appears that for a DATE or DATETIME field, an empty value cannot be inserted. I got around this by first checking for an empty value (mydate = "") and if it was empty setting mydate = "NULL" before insert.
The DATE and DATETIME fields don't behave in the same way as VARCHAR fields.
you can use like this:
string Log_In_Val = (Convert.ToString(attenObj.Log_In) == "" ? "Null" + "," : "'" + Convert.ToString(attenObj.Log_In) + "',");

How to input the value 'NULL' into nvarchar column in SQL Server?

I have a requirement to insert the literal value 'NULL' into a nvarchar column as a default value. But when I insert records the default is going as db NULL instead of the literal 'NULL'. Can someone tell me where I am going wrong?
So you want the actual string of "NULL" to be inserted? Try something like this:
create table NullTable
(
nvarchar(100) not null default 'NULL',
.... -- your other fields
)
EDIT: Here is a full solution
create table InsertNull
(
Nullfield nvarchar(100) not null default 'NULL',
someint int not null
)
go
insert into insertnull(someint)
select 20
select *
from InsertNull
Note the quotes:
INSERT INTO yourtable (varcharfield) VALUES ('NULL'); // string null
INSERT INTO yourtable (varcharfield) VALUES (NULL); // actual null
If set the default in code instead of the designer is should work.
ALTER TABLE [myTable] ADD DEFAULT ('NULL') FOR [TextColumn]

NVL in Where clause doesn't return records which has null values

I used this SELECT statement:
SELECT
ID
,SUB_TYPE
,SERVICE_ID
,MENU_TYPE
,MENU_DESCRIPTION
FROM MY_TABLE
WHERE SUB_TYPE = NVL('' , SUB_TYPE)
AND SERVICE_ID = NVL('' , SERVICE_ID)
AND MENU_TYPE = NVL('' , MENU_TYPE)
The rows that have null MENU_TYPE don't return , but I want these records to return
Thanks in advance
NULL is never equal to NULL. And in Oracle, '' is NULL.
Try this:
((:P_MENU_TYPE IS NULL AND MENU_TYPE IS NULL) OR MENU_TYPE = :P_MENU_TYPE)
(I put a bind variable :P_MENU_TYPE where you had '' because the SQL wouldn't make sense with ''!)
If what you really mean is, MENU_TYPE must match the parameter if the parameter is not null, and may be anything including null when the parameter is null then simply:
(:P_MENU_TYPE IS NULL OR MENU_TYPE = :P_MENU_TYPE)
Are you looking for rows in which all three columns are null? If so, you want:
WHERE SUB_TYPE is null
AND SERVICE_ID is null
AND MENU_TYPE in null