MySQL IF NOT NULL, then display 1, else display 0 - mysql

I'm working with a little display complication here. I'm sure there's an IF/ELSE capability I'm just overlooking.
I have 2 tables I'm querying (customers, addresses). The first has the main record, but the second may or may not have a record to LEFT JOIN to.
I want to display a zero if there is no record in the addresses table.
And I want to only display 1, if a record exists.
What I've attempted so far:
SELECT c.name, COALESCE(a.addressid,0) AS addressexists
FROM customers c
LEFT JOIN addresses a ON c.customerid = a.customerid
WHERE customerid = 123
This first example does not do it. But I may be utilizing COALESCE wrong.
How can I display a 0, if null, and a 1, if something exists?

Instead of COALESCE(a.addressid,0) AS addressexists, use CASE:
CASE WHEN a.addressid IS NOT NULL
THEN 1
ELSE 0
END AS addressexists
or the simpler:
(a.addressid IS NOT NULL) AS addressexists
This works because TRUE is displayed as 1 in MySQL and FALSE as 0.

SELECT c.name, IF(a.addressid IS NULL,0,1) AS addressexists
FROM customers c
LEFT JOIN addresses a ON c.customerid = a.customerid
WHERE customerid = 123

Careful if you're coming from C/C++ and expecting this to work:
select if(name, 1, 0) ..
Even if 'name' is not NULL, unlike in C, a false-condition still triggers and the above statement returns 0. Thus, you have to remember to explicitly check for NULL or empty string:
select if(name is null or name = '', 0, 1)
PS Eugen's example up above is correct, but I wanted to clarify this nuance as it caught me by surprise.

SELECT
c.name,
CASE WHEN a.addressid IS NULL THEN 0 ELSE 1 END AS addressexists
FROM customers c
LEFT JOIN addresses a ON c.customerid = a.customerid
WHERE customerid = 123

Another method without WHERE, try this..
Will select both Empty and NULL values
SELECT ISNULL(NULLIF(fieldname,'')) FROM tablename
It will set null if it is an empty string, then be true on that also.

You can actually use an IF statement in the latest versions of MySQL.
IF(expr,if_true_expr,if_false_expr)
IE:
SELECT name, IF(ISNULL(name), 'robot', 'human') AS type
FROM visitors

If within TSQL, you can try :
SELECT IIF(a.addressid IS NULL, 0, 1) AS addressexists
SQL Server should work

Related

Use subquery in mysql

The query below gives me 2 out of the 3 answers I'm looking for. On the sub-query select I get null instead of no
the 3 possible values for column name isCyl could be blank, yes, no
I'm not sure if the sub-query is the best way to go about it, but I don't know how else to re-state the query.
The schedule table has a series of columns to show what tasks must be completed on an assignment. Related tables store the results of the tasks if they were assigned to be completed. So I need to test if a specific task was scheduled. If so, then I need to see if the results of the task have been recorded in the related table. For brevity I am only showing one of the columns here.
SELECT s.`reckey`,
if(s.cylinders="T",
(select
if(c.areckey is not null,
"yes",
"no"
)
from cylinders c where c.areckey = s.reckey limit 1
)
,""
) as isCyl
from schedule s
where s.assignmentDate between 20161015 and 20161016
order by s.reckey
Use a LEFT JOIN, which returns NULL for columns in the child table when there's no match.
SELECT s.reckey, IF(s.cylinders = "T",
IF(c.areckey IS NOT NULL, 'yes', 'no'),
"") AS isCyl
FROM schedule AS s
LEFT JOIN cylinders AS c ON c.areckey = s.reckey
WHERE s.assignmentDate between 20161015 and 20161016
ORDER BY s.reckey
If there can be multiple rows in cylinders with the same areckey, change it to:
LEFT JOIN (select distinct areckey FROM cylinders) AS c on c.areckey = s.reckey
or use SELECT DISTINCT in the main query.

MySQL replace NULL to some value

I have the following stored procedure
BEGIN
SELECT kids.*, SUM(point) as `point_sum`
FROM kids
LEFT JOIN tasks
ON kids.id = tasks.kid_id
WHERE kids.user_id = IN_user_id
GROUP BY kids.name;
END
This statement works fine.
My Question: the SUM(point) for new users are typically NULL because there is no submitted value yet to be summed.
What I want is if SUM(point) is NULL then it should return value like 0 but otherwise it should present the sum. I have looked around and not sure how to fix it, any good ideas?
You could use the coalesce function:
SELECT kids.*, COALESCE(SUM(point), 0) as `point_sum`
FROM kids
LEFT JOIN tasks
ON kids.id = tasks.kid_id
WHERE kids.user_id = IN_user_id
GROUP BY kids.name;
All you really need is IFNULL():
SELECT kids.*, IFNULL(SUM(point), 0) AS point_sum
That converts NULL to the supplied value, in this case 0.

MySQL IF Function not recognizing characters with integers

The issue I am having is that the IF function in MySQL is not correctly telling me if an ID is or is not located in the second table. Here is where you can view what I am doing
http://sqlfiddle.com/#!2/501513/4'
SELECT c.id AS clientID, IF (e.id, 'yes', 'no') AS hasID
FROM Table1 c LEFT JOIN Table2 e ON (c.id = e.id)
WHERE c.id IN ("123456","H100512","94061","OW59556","OR37615");
If you notice that the values "H100512" and "w76789" should both say 'yes' and not 'no' because they are found in the second table. I notice that if I take away the letter from the id in the query and in the table then it will correctly say whether it is there present in the table or not. Am I doing something wrong in the IF Function?
As a matter of course, I think it is better to declare the ids as varchar() and to use single quotes rather than double quotes to delimit character strings. However, neither of these is the cause of your problem.
The problem is the statement:
if(e.id, 'yes', 'no')
In MySQL, this is checking:
if(e.id <> 0, 'yes', 'no')
You are probably thinking that it is checking for NULL. Nope. So, what is happening is that a string like 'H100512' is being converted to an integer -- and it gets converted to 0 which fails the test.
I think you should write the query as:
SELECT c.id AS clientID,
(case when e.id is not null then 'yes' else 'no' end) AS hasID
FROM Table1 c LEFT JOIN
Table2 e
ON c.id = e.id
WHERE c.id IN ('123456', 'H100512', '94061', 'OW59556', 'OR37615', 'w76789');
This is explicit in what it is doing and it uses the ANSI standard conditional statement.

MySQL - tell if column _all_ has same value

I'm trying to write a query like
if (select count(*) from Users where fkId=5000 and status='r') =
(select count(*) from Users where fkId=5000) then ..
in just one query.
What this means is, if all the rows that have fkId=5000 also have status=r, then do something.
There can be any number of rows with fkId=5000, and any fraction of those rows could have status=r, status=k, status=l, status=a etc. I'm interested in the case where ALL the rows that have fkId=5000 also have status=r (and not any other status).
The way I'm doing it now is
how many rows with id=5000 and status = 'r'?
how many rows with id=5000?
are those numbers equal? then ..
I'm trying to figure out how to rewrite this query using only 1 query, instead of 2. Keyword ALL didn't seem to be able to write such a query (<> ALL is equivalent to NOT IN). I tried a couple of GROUP BY formulations but could not get the correct result to appear.
The most efficient way to do this is:
if not exists (select 1
from users
where fkid = 5000 and (status <> 'r' or status is null)
)
This will stop the query at the first non-matching row.
I suggest you to check for any rows with status not equal to 'r'
SELECT count(*)>0 FROM Users WHERE fkId = 5000 AND status != 'r'
In the following case, if the number 1 is "true" (which it is) then you'll get Yes back, and if not you'll get No back:
SELECT IF(1, 'Yes', 'No') AS yesorno
(Go ahead -- try it!)
In your case however, the following would be more appropriate:
SELECT IF (
(SELECT COUNT(*) FROM Users WHERE fkId=5000 AND status IN('r') AND status NOT IN('1', 'a', 'k')) = (SELECT COUNT(*) FROM Users WHERE fkId=5000),
'They are equal.',
'They are not equal.'
)
AS are_they_equal
By adding AS, you can manipulate the name of the "column" that's returned to you.
Hope that helps... Also, see this page if you'd like more info.
:)
EASY!
Simply join back to the same table. Here is the complete code for testing:
CREATE TABLE Users(id int NOT NULL AUTO_INCREMENT, fkID int NOT NULL, status char(1), PRIMARY KEY (id));
INSERT Users (fkID, status) VALUES (5000, 'r');
INSERT Users (fkID, status) VALUES (5000, 'r');
INSERT Users (fkID, status) VALUES (5000, 'r');
-- The next query produces "0" to indicate no miss-matches
SELECT COUNT(*) FROM Users u1 LEFT JOIN Users u2 ON u1.id=u2.id AND u2.status='r' WHERE u1.fkID=5000 AND u2.id IS NULL;
-- now change one record to create a miss-match
UPDATE Users SET status='l' WHERE id=3 ;
-- The next query produces "1" to indicate 1 miss-match
SELECT COUNT(*) FROM Users u1 LEFT JOIN Users u2 ON u1.id=u2.id AND u2.status='r' WHERE u1.fkID=5000 AND u2.id IS NULL;
DROP TABLE Users;
So all you need to test for in the result is that it's 0 (zero) meaning everything has fkID=5000 also has status='r'
If you properly index your table then joining back to the same table is not an issue and certainly beats having to do a 2nd query.
Besides the NOT EXISTS version - which should be the most efficient as it does no counting at all and exits as soon as it finds a value that doesn't match the conditions, there is one more way, that will work if status is not nullable and will be efficient if there is an index on (fkId, status):
IF EXISTS
( SELECT 1
FROM Users
WHERE fkId = 5000
HAVING MIN(status) = 'r'
AND MAX(status) = 'r'
)
There is one difference though. The above will show false if there are no rows at all with fkId=5000, while the NOT EXISTS version will show true - which is probably what you want anyway.

JOIN data from same table

I have a table containing the names, emails, positions, etc of a students, as well as their "status" (which can be one of Y or N.) I want to write a query that counts the number of each type of position, as well as the number of Y AND the number of N within each type using JOIN. (That is, it would be a table with three columns: Position, StatusIsYes, and StatusIsNo.)
I have already done this using the CASE clause the following way, but I can't figure out how to do it using the JOIN clause.
SELECT position,
COUNT(CASE WHEN status = 'Y' THEN 1 ELSE NULL END) AS StatusIsYes,
COUNT(CASE WHEN status = 'N' THEN 1 ELSE NULL END) AS StatusIsNo
FROM
students GROUP BY crd
I appreciate any suggestions!
EDIT: I know it can be done without using JOIN, but I want to know how it is possible to do it with a JOIN.
You don't need a join:
SELECT
position,
SUM(status = 'Y') AS StatusIsYes,
SUM(status = 'N') AS StatusIsNo
FROM students
GROUP BY position
Note the rather funky dispensing of the CASE, because in mysql (only) true is 1 and false is 0, so sum() of a condition counts how many times it is true :)
You can use SELF JOIN in the case when you want to fetch records from same table.
For ex:
Table Name: employee
Fields : EmpId,EmpName,ManagerId
Now if you want to get the details of Empolyees who are in Manager Position for that we need to write query like this:
SELECT e1.EmpId, e1.EmpName FROM EmployeeDetails e1, EmployeeDetails e2 where e1.EmpId=e2.ManagerId;
Hope it will help you.
Fro more information please check this link.
Try ::
SELECT
position,
COUNT(status = 'Y' ) AS StatusIsYes,
COUNT(status = 'N' ) AS StatusIsNo
FROM
students GROUP BY POSITION