SQL COUNT(Column) Counts also the null value which is wrong - c#

I'm creating a total details in my project but I'm having a problem regarding the "COUNT" in my query. It also calculates the null. What I want is, count the column with values only other than that, the query will not count the null column.
Here's my code
SELECT COUNT(columnName) as TotalColumnValue FROM tblName
| columnName|
| value|
| |
| value|
| value|
so the result count would be 3 and not 4 because the value is null.
Thank you in advance.

Actually, a IS NOT NULL condition like mentioned in all the answers is not necessary since count(columnName) will not count null values. So basically it enough to just filter empty string values and just specify the column in the count.
SELECT COUNT(columnName) as TotalColumnValue
FROM tblNam
WHERE columnName <> ''
Note -> to the question you've asked on the comments. <> means != or in words - NOT EQUAL

If the value is really NULL, then COUNT should be excluding that row. Maybe it's not NULL but an empty string''. Try adding a NULLIF in your column:
CREATE TABLE tbl(columnName VARCHAR(10) NULL);
INSERT INTO tbl VALUES ('value'), ('value'), ('value'), ('');
SELECT COUNT(NULLIF(columnName, '')) FROM tbl;
Or you can filter for empty strings:
SELECT COUNT(columnName) FROM tbl WHERE columnNameIS NOT NULL AND columnName <> ''

Adding where function solve your issue. :)
SELECT COUNT(columnName) as TotalColumnValue FROM tblName where columnName is not null

If you want the number of different values (not counting repeating values) use
SELECT DISTINCT COUNT(columnName) AS TotalColumnValue FROM tblName WHERE columnName IS NOT NULL

You need to exclude both NULL and empty string ''.
SELECT COUNT(columnName) as TotalColumnValue FROM tblName
WHERE columnName <> '';

Related

How to get exact match from data row using Sql query

Hello i've datarow (IDs) as
12?15?6?11?51?
1?15?6?11?51?
&
I want to search numbers which is equal to 1 (id). For That When i used
%1% this will return match result as both rows
%1?% this will return match result as both rows
%?1?% this will return match result as null
%?1% this will return match result as both rows
the result should be only 2nd row for ID 1.
Please give proper query for this.
Thanks.
SELECT * FROM TableName WHERE ID LIKE '1?%' OR ID LIKE '%?1?%'
SELECT * FROM TABLE WHERE ID LIKE '1?_%' ;
This will work meaning if you contain starting with 1?
You can use
CREATE TABLE T(
ID VARCHAR(45)
);
INSERT INTO T VALUES
('12?15?6?11?51?'),
('1?15?6?11?51? &');
SELECT *
FROM T
WHERE ID LIKE '[1][^0-9]%';
Returns:
+-----------------+
| ID |
+-----------------+
| 1?15?6?11?51? & |
+-----------------+
Demo

How do I retrieve non-empty & non-duplicate data from the database?

I have this nitpicked columns on my table (cause the rest are irrelevant in the problem).
ID | Generic Name
-----+---------------
001 | Cetirizine
002 | Cetirizine
003 |
004 | Paracetamol
I want my combo box to display only a single entry Cetirizine (or any data that has been duplicated) and no empty generic names (some data have no generic names).
I've tried:
select
Item_GenName
from
ItemMasterlistTable
where
nullif(convert(varchar, Item_GenName), '') is not null
but it only achieves the no empty data part.
I've tried using DISTINCT, but it doesn't work and somebody suggested JOIN but I don't think it works since I'm only using 1 table.
I've also tried:
SELECT
MIN(Item_ID) AS Item_ID, Item_GenName
FROM
ItemMasterlistTable
GROUP BY
Item_GenName
but there's always an error:
The text, ntext, and image data types cannot be compared or sorted, except when using IS NULL or LIKE operator.
The following query should return only distinct, non-empty Item_GenNames:
SELECT DISTINCT Item_GenName
FROM ItemMasterlistTable
// because Item_GenName is of type *text*, the below in lieu of `is not null` and `!= ''`
WHERE datalength(Item_GenName) != 0
You said you tried DISTINCT and it did not work so I want to clarify,
The DISTINCT keyword will return unique records over the complete domain of your select statement. If you include the ID column in your select statement, even a distinct selection will return your duplicate Item_GenNames b/c the combined ID / Item_GenName record would be unique. Include only Item_GenName in your select clause to guarantee distinct values for this column.
The following query might be useful.
declare #tab table (ID varchar(10), Generic_Name varchar(100))
insert into #tab
select '001', 'Cetirizine'
union
select '002', 'Cetirizine'
union
select '003', ''
union
select '004', 'Paracetamol'
select MIN(substring(ID, 1, 10)) ID, substring(Generic_Name, 1, 1000) Generic_Name
from #tab
where substring(Generic_Name, 1, 1) <> ''
group by substring(Generic_Name, 1, 1000)
You can try this query
Select distinct Item_GenName FROM(
Select * FROM ItemMasterlistTable where Item_GenName <> ''
)t
Inner query remove non-empty records and outer query get the distinct record from the inner output

NullReferenceException using COALESCE in SQL query

Perhaps I'm misunderstanding COALESCE, but in essence, what I'm trying to do is run a select query that if it returns NULL instead of an int, instead return 0 for the purposes of ExecuteScalar().
SQL Server query:
SELECT TOP 1 COALESCE(SeqNo,0)
FROM tblProjectChangeOrder
WHERE ProjectID = XXXXX
ORDER BY SeqNo DESC
If the supplied ProjectID exists in the Change Order table, it returns the expected highest SeqNo. However, if the supplied ProjectID has no existing Change Orders (thus returns NULL for SeqNo), rather than the COALESCE returning 0, I am still getting NULL.
Am I just getting the syntax wrong or is what I want to do possible with COALESCE? The other option I see is to have my ExecuteScalar() pass to a nullable int, then follow that with a ?? to coalesce in my C# codebehind.
As john has mentioned in the comments, COALESCE operates at row level. If a table contains no rows, or a statement returns no rows, then no rows will be returned. Take the simple example below:
CREATE TABLE #Sample (ID int);
SELECT COALESCE(ID, 0)
FROM #Sample;
DROP TABLE #Sample;
Notice that nothing is returned.
Instead, one method is to use a subquery. For your query, that would result in:
SELECT COALESCE(SELECT TOP 1 SeqNo
FROM tblProjectChangeOrder
WHERE ProjectID = XXXXX
ORDER BY SeqNo DESC),0) AS SeqNo;
This also assumes that Seqno has a data type of int; otherwise you're likely to get a conversion error.
My guess is that the null reference exception occures on the code and has nothing to do with the sql query. It might just be that your code is not handling that you return no rows (or no scalar in your case) but you might be trying to access it somewhere in c#.
Show us the line of code that is throwing this exception in c# so we might be able to confirm this.
regards
Edit : From this similar topic
In your c# code you might want to try ("cmd" being your "SqlCommand" object):
int result = 0;
int.TryParse(cmd.ExecuteScalar(), out result);
or in one line
int.TryParse(cmd.ExecuteScalar(), out int result);
I don't know if it is the most suitable solution for you but I hope it is a start.
As covered null and no row are not the same.
This sample covers it.
set nocount on;
select isnull(1, 0)
where 1 = 1;
select isnull(1, 0)
where 1 = 2;
select isnull(null, 0)
where 1 = 1;
select isnull(null, 0)
where 1 = 2;
-----------
1
-----------
-----------
0
-----------
this should work
select top 1 isnull(seq, 0)
from (select null as seq
union all
select max(seq) from tblProjectChangeOrder where ProjectID = XXXXX
) tt
order by seq desc

C# DataTable.Select() - How do I format the filter criteria to include null?

This doesn't work
DataTable myNewTable = myDataTable.Select("Name <> 'n/a'").CopyToDataTable();
myDataTable has a row named Name. I would like to select the rows from this table where Name is not equal to "n/a". It selects but still am missing the null values i need the null values too.
Can anyone help?
Try this
myDataTable.Select("[Name] is NULL OR [Name] <> 'n/a'" )
Edit: Relevant sources:
DataTable.Select Method (String)
Expression filtering syntax
Try out Following:
DataRow rows = DataTable.Select("[Name]<>'n/a'")
For Null check in This:
DataRow rows = DataTable.Select("[Name] <> 'n/a' OR [Name] is NULL" )
The way to check for null is to check for it:
DataRow[] myResultSet = myDataTable.Select("[COLUMN NAME] is null");
You can use and and or in the Select statement.
try this:
var result = from r in myDataTable.AsEnumerable()
where r.Field<string>("Name") != "n/a" &&
r.Field<string>("Name") != "" select r;
DataTable dtResult = result.CopyToDataTable();

Get all or part result from sql using one TSQL commnd

Here is my condition.
There is a Text box in a form, if you don't input any thing, it would return all rows in this table. If you input something, it would return rows whose Col1 matches the input. I try to use the sql below to do it. But there is one problem, these columns allows Null value. It wouldn't return the row with NULL value. Is there any way to return all or matched row based on the input?
Update
I use the ObjectDataSource and ControlParameter to pass the parameter, when the input of control is empty, the ObjectDataSource would pass a DBNULL to the TSQL commnd.
Col1 Col2 Col3
ABCD EDFR NULL
NULL YUYY TTTT
NULL KKKK DDDD
select * from TABLE where Col1 like Coalesce('%'+#Col1Val+'%',[Col1])
Have you tried
SELECT *
FROM TABLE
WHERE COALESCE(Col1, '') LIKE COALESCE ('%'+#Col1Val+'%', [Col1])
Something like this might work.
select * from TABLE where Coalesce(Col1,'xxx') like Coalesce('%'+#Col1Val+'%',Col1, 'xxx')
SELECT * FROM [TABLE]
WHERE (Col1 LIKE '%'+#Col1Val+'%' OR (#Col1Val = '' AND Col1 IS NULL))
Use this:
SELECT *
FROM TABLE
WHERE
( #Col1Value IS NOT NULL AND COALESCE(Col1, '') LIKE '%' + #Col1Val +'%' )
OR #Col1Value IS NULL
Or perhaps use this, so null won't creep in to your query:
string nullFilteredOutFromQueryString = #"SELECT *
FROM TABLE
WHERE
( #Col1Value <> '' AND COALESCE(Col1, '') LIKE '%' + #Col1Val +'%' )
OR #Col1Value = ''";
var da = new SqlDataAdapater(nullFilteredOutFromQueryString, c);
// add the TextBox's Text property directly to parameter's value.
// this way, null won't creep in to your query
da.SelectCommand.Parameters.AddWithValue("Col1Value", txtBox1.Text);
da.Fill(ds, "tbl");

Categories

Resources