How to assign default value to empty column - sql

I am working on report builder 6i.
I have two tables
1- Company_info
2- Address_info
Comp_addr_code is a foreign key in company_info table which is primary key in
Address_info table.Now I am retrieving data from address_table base on comp_address_Code.But in some cases first three columns are empty in Address_info table.
I want for these columns 'X' should be displayed.What Changes should I make in my SQL Statement.My Sql statement is:
SELECT COMP_CODE, COMP_NAME, COMP_ADDR_CODE,
FROM COMPANY_INFO, ADDRESS_INFO
WHERE COMP_CODE=:P_COMP_CODE
AND COMP_ADDR_CODE=ADDR_CODE

Use COALESCE, it picks the first non-null value. I.e. if the column value is not null, return the column value, else return specified default value:
select coalesce(COMP_CODE,'X'),
coalesce(COMP_NAME,'X'),
etc

As given, only COMP_NAME can be NULL; if COMP_CODE or COMP_ADDR_CODE are null, those rows will not be in the resultset.
NVL or COALESCE are usually used to replace null values with other values, e.g.
SELECT
COMP_CODE,
nvl(COMP_NAME, 'X')
COMP_ADDR_CODE
FROM COMPANY_INFO,ADDRESS_INFO
WHERE COMP_CODE=:P_COMP_CODE
AND
COMP_ADDR_CODE=ADDR_CODE

Related

Select another column value from the same table if another column value is NULL

I have a table with four columns: NAME, AGE, PRIMARYWEIGHT and SECONDARYWEIGHT
Where NAME = 'Damian', I wish to select AGE and PRIMARYWEIGHT only if SECONDARYWEIGHT is NULL otherwise I'll take PRIMARYWEIGHT.
Ideally I'd like to give its an alias 'WEIGHT' regardless of whether it was PRIMARYWEIGHT or SECONDARYWEIGHT.
SELECT NAME, AGE, ISNULL(PRIMARYWEIGHT, SECONDARYWEIGH) As WEIGHT
msdn reference
SELECT AGE, COALESCE(SECONDARYWEIGH, PRIMARYWEIGHT) As WEIGHT
You can use COALESCE (as indicated in your tag)
Evaluates the arguments in order and returns the current value of the first expression that initially does not evaluate to NULL.

Unable to retrieve NULL data

I have three fields Category, Date, and ID. I need to retrieve data that does not belong under certain ID. Here is an example of my query:
SELECT Category, Date, ID
FROM table
WHERE ID NOT IN('1','2','3')
AND Date = '01/06/2015'
After running this query I should only get records that do not have any ID meaning NULL values because for yesterday's record only ID 1,2,3 exist and rest do not have any value (NULL). For some reason when I run the query it takes away the NULL values as well so I end up with 0 rows. This is very stranger to me and I do not understand what is the cause. All I know that the ID numbers are string values. Any suggestions?
Try this. NULL values cannot not be equated to anything else.
SELECT Category, Date, ID
FROM table
WHERE (ID NOT IN('1','2','3') OR ID IS NULL)
AND Date = '01/06/2015'
Others have already shown how to fix this, so let me try to explain why this happens.
WHERE ID NOT IN('1','2','3')
is equivalent to
WHERE ID <> '1' AND ID <> '2' AND ID <> '3'
Since NULL <> anything yields UNKNOWN, your expression yields UNKNOWN and the record in question is not returned.
See the following Wikipedia article for details on this ternary logic:
Null (SQL): Comparisons with NULL and the three-valued logic (3VL)
Take a look at NULL comparison search conditions.
Use the IS NULL or IS NOT NULL clauses to test for a NULL value. This
can add complexity to the WHERE clause. For example, the TerritoryID
column in the AdventureWorks2008R2 Customer table allows null values.
If a SELECT statement is to test for null values in addition to
others, it must include an IS NULL clause:
SELECT CustomerID, AccountNumber, TerritoryID
FROM AdventureWorks2008R2.Sales.Customer
WHERE TerritoryID IN (1, 2, 3)
OR TerritoryID IS NULL
If you really want to be able to compare values to NULL's directly, you can do that as well. This is also described in the above article:
Transact-SQL supports an extension that allows for the comparison
operators to return TRUE or FALSE when comparing against null values.
This option is activated by setting ANSI_NULLS OFF.
Are you sure about you want ID fields as null?
Here is how you do it: (Assumins rest of your query is ok)
SELECT Category, Date, ID
FROM table
WHERE ID IS NULL
AND Date = '01/06/2015'
If you want records that does not have a category than you need to change your query as
SELECT Category, Date, ID
FROM table
WHERE Category IS NULL
AND Date = '01/06/2015'
You got a couple of options:
SELECT Category, Date, ID
FROM table
WHERE ISNULL(ID, '4') NOT IN('1','2','3')
AND Date = '01/06/2015'
Or what su8898 said
Please note that when you use "IN" or "NOT IN" which will not fetch any values if the column has got NULL values..
In your case, if you want to fetch only records with ID=NULL, then you can try the solution vgSefa suggested above..
If you want to pull all records with NULL as well as ID NOT IN('1','2','3'), then you could try something like this..
SELECT Category, Date, ID
FROM table
WHERE ID IS NULL
AND Date = '01/06/2015'
UNION ALL
SELECT Category, Date, ID
FROM table
WHERE ID NOT IN('1','2','3')
AND ID IS NOT NULL
AND Date = '01/06/2015'
Try this:
SELECT Category, Date, ID
FROM table
WHERE ID N
AND Date = '01/06/2015'

SQL null values inner join

I would like to only include a comparison on an inner join if the value is not null. E.g. I am comparing addresses some addresses have the same house number street address and tag but have a distinct apartment number, but other addresses don't have apartment numbers associated with them so the value is null. These values don't get joined.
A left outer join won't work because I need to join data associated with the values that have null apartment values. Any ideas?
select * from address a
inner join ma_address ma
on a.number=ma.number
and a.street=ma.street
and a.tag=ma.tag
and a.apt=ma.apt
Thanks,
This is because in SQL, NULL does not equal NULL. Try something like this for each join criteria
(a.<col> = ma.<col> OR (a.<col> IS NULL AND ma.<col> IS NULL))
A value of NULL indicates that the value is unknown. A value of NULL is different from an empty or zero value. No two null values are equal. Comparisons between two null values, or between a NULL and any other value, return unknown because the value of each NULL is unknown.
Null values generally indicate data that is unknown, not applicable, or that the data will be added later. For example, a customer's middle initial may not be known at the time the customer places an order.
Following is information about nulls:
1. To test for null values in a query, use IS NULL or IS NOT NULL in the WHERE clause.
2. When query results are viewed in SQL Server Management Studio Code editor, null values are shown as NULL in the result set.
3. Null values can be inserted into a column by explicitly stating NULL in an INSERT or UPDATE statement, by leaving a column out of an INSERT statement, or when adding a new column to an existing table by using the ALTER TABLE statement.
4. Null values cannot be used for information that is required to distinguish one row in a table from another row in a table, such as primary keys.
Source: http://technet.microsoft.com/en-us/library/ms191504(v=sql.105).aspx

How to delete a row in SQL based on a NULL condition

I just started learning SQL; I've created a table. Learned insert command and inserted values in 2 rows. However I've inserted null values in 3rd.
Now I want to delete the third row which has 2 columns with no values in it.
I'm using the following query:
delete employee where city=null;
It doesn't seem to be working!
According SQL 92 standard many logical operations with null values like
> null
= null
and null
or null
not null
should always return null (and never true). Some DBMS (e.g. Oracle) follow this rule rigorously, some (MS SQL) can have a mode that null = null returns true, not required null. In order to be compartible with SQL 92 and so with (almost) all DBMSs, you should use is null or is not null standard comparisons, in your case
delete from employee
where city is null -- <- Standard comparison
You need the is null "operator":
delete from employee where city is null;
This is because in SQL, nothing is equal to NULL.
You can't use = with NULL. Instead, use:
delete employee where city is null;
To achieve this
you will have to write this query
DELETE from table_name WHERE city IS NULL;
this query will delete the rows/records WHERE city is null
Here you know you have added Null in city column so checking with is null will work but it's also possible to add an empty string in city column. So if your business condition is like delete all records from employee table where city is either null or empty i.e. with no values you should write as:
delete from employee where isnull(city,'')='';
change it :
delete from table_name where city is null
or
delete from table_name where city = null

Why does tsql Rand function not work in where clause?

I am trying to select a single row at random from a table. I am curious as to why the two statements below don't work:
select LastName from DataGeneratorNameLast where id = (ABS(CHECKSUM(NewId())) % 3)+1
select LastName from DataGeneratorNameLast where id = cast(Ceiling(RAND(convert(varbinary, newid())) *4) as int)
Both statements return, at random, either 1 row, no rows, or multiple rows. For the life of me I can't figure out why. Just adding top 1 to the query only solves the problem of multiple rows - but not of no rows returned.
Yes I could do the same thing by selecting top 1 and ordering by newid(). But the mystery of why this does not work is driving me crazy.
Thoughts on why I get multiple rows back?
Here is the table I am using to select from:
Create Table dbo.DataGeneratorNameLast
(
[Id] [int] IDENTITY(1,1) NOT NULL,
LastName varchar(50) NOT NULL,
)
Go
insert into DataGeneratorNameLast (LastName) values ('SMITH')
insert into DataGeneratorNameLast (LastName) values ('JOHNSON')
insert into DataGeneratorNameLast (LastName) values ('Booger')
insert into DataGeneratorNameLast (LastName) values ('Tiger')
The newid() gets evaluated for every row it is compared against, generating a different number. To do what you want, you should generate the random value into a variable before the select and then reference the variable.
Declare #randId int = (abs(checksum(newid())) % 3) + 1;
select LastName from DataGeneratorNameLast where id = #randId;
As Martin said in comments to this. Rand() would behave differently, only being evaluated once per query.
If the table has at least one row that this query would return one row is mandatory.
select TOP (1) LastName
from DataGeneratorNameLast
ORDER BY NEWID()
Notice that this solution can be slow if the table has a large number of rows.
About select LastName from DataGeneratorNameLast where id = #Rand - This solution does not guarantee that there exists a row with id. Even the IDENTITY column can contain gaps. If you definitely need one row then do a preliminary check IF EXISTS (select * from DataGeneratorNameLast where id = #Rand) SELECT ...
I've Had a similar issue and fixed it by making the ID a PRIMARY KEY.
NEWID() is computed per-row. Without a primary key, there is no access pattern other than a table scan, and the filter is checked for each row, so a different value is computed for each row, and you get however many rows match.
With the key, a seek is available, so the predicate is computed once and used as a search argument for a seek.