Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SELECT max(x) is returning null; how can I make it return 0?

Tags:

sql

sql-server

How do you return 0 instead of null when running the following command:

SELECT MAX(X) AS MaxX FROM tbl WHERE XID = 1 

(Assuming there is no row where XID=1)

like image 625
Phillip Senn Avatar asked Nov 06 '09 16:11

Phillip Senn


People also ask

Why does Max return NULL?

MAX returns NULL when there is no row to select. For character columns, MAX finds the highest value in the collating sequence. MAX is a deterministic function when used without the OVER and ORDER BY clauses.

How do you avoid NULL values in Max function?

You can use COALESCE() along with aggregate function MAX() for this. Insert some records in the table using insert command. Display you all records from the table using select statement. Here is the case when table is empty.

How do you fill nulls with 0?

UPDATE [table] SET [column]=0 WHERE [column] IS NULL; Null Values can be replaced in SQL by using UPDATE, SET, and WHERE to search a column in a table for nulls and replace them. In the example above it replaces them with 0.

Does return 0 count NULL?

As all of your values are null, count(cola) has to return zero.


2 Answers

or:

SELECT coalesce(MAX(X), 0) AS MaxX FROM tbl WHERE XID = 1 
like image 168
HLGEM Avatar answered Sep 23 '22 15:09

HLGEM


In SQL 2005 / 2008:

SELECT ISNULL(MAX(X), 0) AS MaxX FROM tbl WHERE XID = 1 
like image 38
Nestor Avatar answered Sep 21 '22 15:09

Nestor