I would like to have a SELECT statement that will return specified default values if no rows are returned from the database.
We can use UNION to get the desired result like this question: "How to set a default row for a query that returns no rows?", but this gives an extra result row.
example:
SELECT a
from TBL_TEST
UNION
SELECT 0
FROM DUAL
Is there a better way, or a standard SQL way to do this that will be portable across multiple database engines?
SELECT ifnull(a,20) FROM TBL_TEST
Selects 20 if a is null otherwise selects a (in mysql, not sure about others)
For a portable solution, how about:
select coalesce(a, 0)
from TBL_TEST
right outer join DUAL on null is null
The COALESCE function is used here because it is more portable than NVL() or IFNULL().
You would have a DUAL table created in database systems that use a different name, such as SQL Server or DB2.
MySQL has the DEFAULT function, but I'm not sure how standard or widely supported it is.
MySQL IFNULL is like oracle's NVL function
MySQL IFNULL() takes two expressions and if the first expression is not NULL, it returns the first expression. Otherwise it returns the second expression.
Syntax
IFNULL(expression1, expression2);
SELECT IFNULL(a,<default value>) from TBL_TEST
In Oracle:
select nvl(a, 0)
from DUAL left join TBL_TEST on null is null
use the COALESCE() to convert the null value column with its default value such as
select coalesce(a,0) from TBL_TEST
In, SQL SERVER 2008 R2 : When Value IS NULL
SELECT ISNULL(a,<Default Value>) from TBL_TEST
e.g. SELECT ISNULL(a,0) from TBL_TEST
In, SQL SERVER 2008 R2 : When Empty String
SELECT ISNULL(NULLIF(a,<Empty String>)<Default Value>) from TBL_TEST
e.g. SELECT ISNULL(NULLIF(a,'')0) from TBL_TEST
This is working fine...
Related
Is it possible to make a query that changes the where clause acording to some condition? For instance I want to select * from table1 where data is 19/July/2016 but if field id is null then do nothing, else compare id to something else. Like the query bellow?
Select * from table1 where date="2016-07-19" if(isnull(id),"",and id=(select * from ...))
Yes. This should be possible.
If we assume that date and id are references to columns in (the unfortunately named) table table1, if I'm understanding what you are attempting to achieve, we could write a query like this:
SELECT t.id
, t.date
, t....
FROM table1 t
WHERE t.date='2016-07-19'
AND ( t.id IS NULL
OR t.id IN ( SELECT expr FROM ... )
)
It would also be possible to incorporate the MySQL IF() and IFNULL() functions, if there's some requirement to do that.
As far as dynamically changing the text of the SQL statement after the statement is submitted to the database, no, that's not possible. Any dynamic changes to the SQL text would need to be done when the SQL statement is generated, before it is submitted to the database.
My personal preference would be to use a join operation rather than a IN (subquery) predicate.
I think you're trying too hard. If id is NULL that's equivalent to having a FALSE in the where clause. So:
Select * from table1 where date="2016-07-19" and id=(select * from ...)
Should only match the records you want. If id is NULL you get nothing.
One of my columns in the table contains 'NULL' values and I would like to replace them with certain values.
I looked at this post: Replace nulls values in sql using select statement? and followed the answer.
My sql statement:
Select ifnull(`option`, 'MCQ') as `option`
from question_table
This statement returns me the columns there are already with 'MCQ', but the 'NULL' values are not replaced yet.
Need some guidance to change this.
If you want to change the data, you need an update:
update question_table
set option = 'MCQ'
where option is null;
A select statement does not change the database.
If you want to update the table use Gordon's answer, but maybe you just want to return a replacement value for NULL in the SELECT, you can use COALESCE:
SELECT COALESCE(`option`, 'MCQ') as `option`
FROM question_table
This selects MCQ for every option-value that is NULL.
Another way is using CASE:
SELECT CASE WHEN `option` IS NULL THEN 'MCQ' ELSE `option` END as `option`
FROM question_table
'NULL' is a string, NULL is a special value that means "unknown/unavailable". They are totally different things.
MySQL function IFNULL() handles NULL values (they cannot be compared using the regular comparison operators). You can use the regular comparison operators (=, <>) to work with strings, even when they are 'NULL'.
If your query produces 'NULL' values in the result set it means the values in the database are not NULL but strings ('NULL').
In this case the query you need is:
SELECT IF(`option` = 'NULL', 'MCQ', `option`) AS `option`
FROM question_table
I have a simple query that selects one field and only one row, thus one value.
Is there any way to make it return NULL if the query results in an empty set? Instead of returning zero rows?
I think I need to use something with NOT EXISTS, THEN NULL but not certain about it.
select
(Your entire current Select statement goes here) as Alias
from
dual
dual is a built in table with a single row that can be used for purposes like this. In Oracle this is mandatory. MySQL supports it, but you can also just select a single value without specifying a table, like so:
select
(Your entire current Select statement goes here) as Alias
In either case you're selecting a single value. This means that:
If your select returns one value, that value is returned.
If your select statement returns one column, but no rows, NULL will be returned.
If your select statement returns multiple columns and/or multiple rows, this won't work and the query fails.
An easy way to do this is with aggregation:
select max(col)
from t
where <your condition here>
This always returns one row. If there is no match, it returns NULL.
Late reply but I think this is the easiest method:
SELECT
IFNULL((SELECT your query), NULL)
Use a UNION with a NOT EXISTS(original where clause)
select col1
from mytable
where <some condition>
union
select null
where not exists (
select * from mytable
where <some condition>)
You can use COALESCE for example:
SELECT COALESCE(Field1,NULL) AS Field1 FROM Table1
Edit 1:
sorry i mistake with return field as null not result set,for result set return as null use Union and Exist Function like this:
SELECT NULL AS Field1 FROM Table1 WHERE not EXISTS(SELECT Field1 FROM Table1 WHERE Field2>0)
UNION
SELECT Field1 FROM Table1 WHERE Field2>0
this is my first question ever, so please be patient.. :)
We are two developers and both have the same MySql DB with same tables and values.
One is MySql version 5.5 and works ok (apparently) as I am told by the other developer.
On my machine with MySql 5.1.44 (a basic MAMP install) I have the following weird problem.
A very huge query (not mine) fails with error "Column 'xd' cannot be null".
Removing pieces I slimmedi it down to this:
select xd, avg(media) from questionario_punteggi where somefield = 1 union select 1,2
Note, there is no record with somefield = 1 so the first select returns an empty set
We have a SELECT with AVG() function that returns an empty set UNION another SELECT that returns something (1,2 are just random values I put now as an example)
If I remove the AVG() the query works.
If I remove xd (and the 2 of 1,2 to the right) the query works.
If I remove the UNION the query works.
If I set some record with somefield = 1 the query works.
On the other machine 5.5 the query works.
Otherwise the error is:
1048 - Column 'xd' cannot be null
Fields are:
`xd` char(3) NOT NULL DEFAULT '001',
`media` decimal(7,4) NOT NULL DEFAULT '0.0000',
`somefield` tinyint(4) NOT NULL DEFAULT '0',
Gosh. Any help? Thanks.
UPDATE
It has been reported to me as a BUG in MySql <= 5.1 that was fixed before MySql 5.5. I don't have the details but I trust the source
I suggest reversing the order of the queries in the UNION.
This is because the first SELECT in a UNION determines the data type of the columns in the resultset; in your case, the first column of the UNION took the type of the questionario_punteggi.xd column: that is, CHAR(3) NOT NULL.
Since you are applying an aggregate function over the first part of the UNION, it results in a single row even though no records are matched by the filter criterion. As documented under GROUP BY (Aggregate) Functions:
AVG() returns NULL if there were no matching rows.
The value taken for the hidden xd column would normally be an indeterminately chosen record from those that match the filter (which is why you probably don't want to do that anyway); however, since in this case no records match, the server instead returns NULL (which obviously cannot go into a column with the NOT NULL attribute).
By reversing the order of the UNION, the column will not have the NOT NULL attribute. You may need to alias your columns appropriately:
SELECT 1 AS xd, 2 AS avg_media
UNION
SELECT xd, AVG(media) FROM questionario_punteggi WHERE somefield = 1
Using this to explain each of your observations in turn:
If I remove the AVG() the query works.
Since aggregation is no longer performed, the first SELECT in the UNION yields an empty recordset and therefore no NULL record in the first column.
If I remove xd (and the 2 of 1,2 to the right) the query works.
Since the hidden column is no longer selected, MySQL no longer returns NULL in its place.
If I remove the UNION the query works.
This is the bug that was likely fixed between your version of MySQL and your colleague's: the NOT NULL attribute shouldn't really apply to the UNION result.
If I set some record with somefield = 1 the query works.
The value selected for the hidden column is an indeterminate (but non-NULL value, due to the column's attributes) from the matching records.
On the other machine 5.5 the query works.
This bug (I'm still searching for it) must have been fixed between your respective versions of MySQL.
try using the SELECT IFNULL();
Select IFNULL(xd,0), avg(media) f
rom questionario_punteggi
where somefield = 1
union
select 1,2
http://dev.mysql.com/doc/refman/5.0/en/control-flow-functions.html#function_ifnull
how to deal with NULL value in mysql where in CLAUSE
i try like
SELECT * FROM mytable WHERE field IN(1,2,3,NULL)
it not working
only work like :
SELECT * FROM mytable WHERE field IN(1,2,3) OR field IS NULL
how can i get it work in WHERE IN ? it is possible ?
There is a MySQL function called COALESCE. It returns the first non-NULL value in the list, or NULL if there are no non-NULL values.
If you for example run SELECT COALESCE(NULL, NULL, -1); you will get -1 back because it's the first non-NULL value.
So the trick here is to wrap your expression in COALESCE, and add a value as the last parameter that you also add in your IN function.
SELECT * FROM mytable WHERE COALESCE(field,-1) IN (1,2,3,-1)
It will only match if field is 1,2 or 3, or if field is NULL.
As by my understanding you want to pull every record with 1,2,3 and null value.
I don't think its possible to put null in the IN operator. Its expects values and null is well.. not a value. So You really have to put the OR with the null to get the desired result.
Maybe this information from the MySQL Reference Manual helps:
To comply with the SQL standard, IN returns NULL not only if the expression on the left hand side is NULL, but also if no match is found in the list and one of the expressions in the list is NULL.
Using UNION as a subquery in IN operator can get tableIds as a list and from that can get results with the NULL value.
eg:
SELECT * FROM
mytable
WHERE mytable.id IN(
SELECT mytable.id
FROM mytable
where mytable.field IS NULL
UNION
SELECT mytable.id
FROM mytable
WHERE mytable.field IN(1,2,3)
)
Following statement should help:
SELECT * FROM mytable WHERE COALESCE(field,0) IN (1,2,3,0)