Returning a value even if no result - mysql

I have this kind of simple query that returns a not null integer field for a given id:
SELECT field1 FROM table WHERE id = 123 LIMIT 1;
The thing is if the id is not found, the resultset is empty. I need the query to always return a value, even if there is no result.
I have this thing working but I don't like it because it runs 2 times the same subquery:
SELECT IF(EXISTS(SELECT 1 FROM table WHERE id = 123) = 1, (SELECT field1 FROM table WHERE id = 123 LIMIT 1), 0);
It returns either field1 if the row exists, otherwise 0. Any way to improve that?
Thanks!
Edit following some comments and answers: yes it has to be in a single query statement and I can not use the count trick because I need to return only 1 value (FYI I run the query with the Java/Spring method SimpleJdbcTemplate.queryForLong()).

MySQL has a function to return a value if the result is null. You can use it on a whole query:
SELECT IFNULL( (SELECT field1 FROM table WHERE id = 123 LIMIT 1) ,'not found');

As you are looking for 1 record, (LIMIT 1) then this will work.
(SELECT field1 FROM table WHERE id = 123)
UNION
(SELECT 'default_value_if_no_record')
LIMIT 1;
Can be a handy way to display default values, or indicate no results found. I use it for reports.
See also http://blogs.uoregon.edu/developments/2011/03/31/add-a-header-row-to-mysql-query-results/ for a way to use this to create headers in reports.

You could include count(id). That will always return.
select count(field1), field1 from table where id = 123 limit 1;
http://sqlfiddle.com/#!2/64c76/4

You can use COALESCE
SELECT COALESCE(SUM(column),0)
FROM table

If someone is looking to use this to insert the result INTO a variable and then using it in a Stored Procedure; you can do it like this:
DECLARE date_created INT DEFAULT 1;
SELECT IFNULL((SELECT date FROM monthly_comission WHERE date = date_new_month LIMIT 1), 0)
INTO date_created
WHERE IFNULL((SELECT date FROM monthly_comission WHERE date = date_new_month LIMIT 1), 0) = 0;
With this you're storing in the variable 'date_created' 1 or 0 (if returned nothing).

Do search with LEFT OUTER JOIN. I don't know if MySQL allows inline VALUES in join clauses but you can have predefined table for this purposes.

k-a-f's answer works for selecting one column, if selecting multiple column, we can.
DECLARE a BIGINT DEFAULT 1;
DECLARE b BIGINT DEFAULT "name";
SELECT id, name from table into a,b;
Then we just need to check a,b for values.

if you want both always a return value but never a null value you can combine count with coalesce :
select count(field1), coalesce(field1,'any_other_default_value') from table;
that because count, will force mysql to always return a value (0 if there is no values to count) and coalesce will force mysql to always put a value that is not null

Related

How to check if a column has all null values in a table? snowflake sql

I would like to see if in my table there exists a column where the entirety of its rows are null.
SELECT * FROM yourTableName
WHERE yourSpecificColumnName IS NULL
-> this will only return the values that are null but i wont know if yourSpecificColumnName is entirely null throughout the table
Using COUNT combined with HAVING:
COUNT
Returns either the number of non-NULL records for the specified columns, or the total number of records.
SELECT 'Entire_column_is_empty'
FROM yourTable
HAVING COUNT(yourSpecificColumnName) = 0;
or QUALIFY:
SELECT *
FROM yourTable
QUALIFY COUNT(yourSpecificColumnName) OVER() = 0;
Alternative approach:
SELECT 'Entire_column_is_empty'
FROM yourTable
HAVING MIN(yourSpecificColumnName) = MAX(yourSpecificColumnName);

MySQL How to find Null data in a table

Scenario: I have a table with duplicate data. One of the columns of this table is ddate, if it is empty/null I want to select that row (and remove it). But for some reason, I cannot find the null rows with a direct query.
Issue: When I run the following query (1):
select
`ddate`,
count(1) as `nb`
from instrument_nt
group by `ddate`;
I get the number of rows where ddate is NULL and where it has other values. But when I run query (2):
select count(*) from instrument_nt where `ddate` = Null;
or
select * from instrument_nt where `ddate` = NULL;
My query result is either 0 or empty.
Question: What is the difference between those two queries (1 and 2)? How can I properly delete the data that has null/missing dates?
NULL mean unknow it's a value.
If you want to get NULL row you need to use IS NULL instead of eqaul NULL
select count(*) from instrument_nt where `ddate` IS Null;
What is the difference between those two queries (1 and 2)? How can I properly delete the data that has null/missing dates?
(1)
select count(*) from instrument_nt where `ddate` IS Null;
you will get the amount ddate is NULL from instrument_nt table.
(2)
select * from instrument_nt where `ddate` IS NULL;
you will get a result set which ddate is NULL;
Every null is defined to be different from every other null. Thus, equality to null is always false. See, for example, here, which describes this so-called "three value problem".
For this third class of value, you want to use IS, as in IS NULL or IS NOT NULL.
use the keyword IS NULL to check the null values in tables
For example:
select * from instrument_nt where `ddate` IS NULL;
MySQL null checks use the IS operator instead of =.
Your query should look like this: select * from instrument_nt whereddateIS NULL;

Do i use count(*) to count record or i add count column into my table directly

My team lead insisting me to add days entry count column within table and update it regularly. something like this
Get previous record
take count column value
Add .5 into that value
And update the count record in current record
like this
.5
1
1.5
2 //each time i have to get previous value to make new value which means select statment, then update statement
While I think that this is not the right way. I can count [using Count(*)] the record to display days which is easy why i bother to add it, use update command to know previous entry etc. The reason he told that we can get count directly without query bunch of records which is performance wise is fast. How you do this? what is correct way?
If I understand correctly, you just want row_number() divided by 2:
select t.*,
(row_number() over (order by ??) ) / 2.0
from t;
The ?? is for whatever column specifies the ordering of the table that you want.
UPDATE YourTable
SET COUNT_COLUMN = (SELECT MAX(COUNT_COLUMN) + 0.5
FROM YourTable
)
WHERE "Your condition for the current record";
For better performance add index on to COUNT_COLUMN column of YourTable.
Hi Fizan,
You can achieve this using function. You can create a function to get resultant value and update it in you column. Like this -
CREATE function Get_Value_ToBeUpdated
RETURN DECIMAL(10,2)
AS
BEGIN
DECLARE result decimal (10,2);
DECLARE previousValue decimal (10,2);
DECLARE totalCount int;
SELECT previousValue = SELECT MAX(columnName) FROM YourTable order by primaryColumn desc
SELECT totalCount = SELECT COUNT(1) FROM YourTable
SET result = ISNULL(previousValue,0) + ISNULL(totalCount,0)
RETURN result;
END
UPDATE YourTable SET COLUMNNAME = DBO.Get_Value_ToBeUpdated() WHERE Your condition
Thanks :)

mySQL/SQlite subtractive query

I need a query in which it starts off by selecting the entire table, then there would be a few more querys that would remove entries from the first query. Ive accomplished this by using several querys and then comparing the results in my application. I was wondering if I can accomplish this in a single query.
Algorithm
Select All AccountIDs from table
Select AccountIDs from table where parameter1 = true
Remove those matches from the original query result
Select AccountIDs from table where parameter2 = true
Remove those matches from the remaining query result
and so on up to N parameters.
This would need to also be compatible with both mySQL and SQLite
I think you are looking for this:
SELECT AccountID FROM the_table
LEFT JOIN (
SELECT AccountID FROM the_table
WHERE
parameter1 = true OR
... OR
parameterN = true ;
) AS not_included USING (AccountID)
WHERE not_included.AccountID IS NULL -- only items with no match in the "not_included" sub-query
The not_included subquery returns all items for which any parameter is set to TRUE. You actually want to exclude these records from your final result set.
Then LEFT-JOIN the_table (i.e. all items) to this sub-result. The WHERE...IS NULL clause excludes items present in the_table but not present in not_included.
Therefore only items which you do not want to exclude remain in the final result set.
The most direct way to implement your algorithm is to use a compound SELECT statement:
SELECT AccountID FROM MyTable
EXCEPT
SELECT AccountID FROM MyTable WHERE parameter1 = 1
EXCEPT
SELECT AccountID FROM MyTable WHERE parameter2 = 1
However, this is also possible with a single WHERE expression:
SELECT AccountID
FROM MyTable
WHERE NOT (parameter1 = 1 OR
parameter2 = 1 OR
...)

Select rows based on non-equality, using just one condition

Suppose a table has a column num of type INT and the values in that column are allowed to be NULL. Now, provided that some rows has num cell set to some value and it's NULL for other rows, how do I select all the rows where num is not equal to a specific value, including the rows where num is NULL, using just one condition?
For example, if the num value I wanted to exclude from selection was 5, I would have to use a SELECT query with two conditions:
SELECT * FROM `table` WHERE `num` != 5 OR `num` IS NULL;
But how to make this simple retrieval using just one condition?
hope this will help you.
SELECT * FROM `table` WHERE ifnull(`num`,0) != 5;