What is the meaning of <> in mysql query? - mysql

I have a MySQL query that includes <> in it. I don't know the exact usage of it.
SELECT * FROM table_laef WHERE id = ? AND genre_type <> 'LIVE'
P.S.: Im sorry for this basic syntax, since I have searched for this on Google. All they give is about <=>. Thanks anyway, guys!

<> is Standard SQL and stands for not equal or !=.

<> means not equal to, != also means not equal to.
Documentation

<> means NOT EQUAL TO, != also means NOT EQUAL TO. It's just another syntactic sugar. both <> and != are same.
The below two examples are doing the same thing. Query publisher table to bring results which are NOT EQUAL TO <> != USA.
SELECT pub_name,country,pub_city,estd FROM publisher WHERE country <> "USA";
SELECT pub_name,country,pub_city,estd FROM publisher WHERE country != "USA";

In MySQL, I use <> to preferentially place specific rows at the front of a sort request.
For instance, under the column topic, I have the classifications of 'Chair', 'Metabolomics', 'Proteomics', and 'Endocrine'. I always want to list any individual(s) with the topic 'Chair', first, and then list the other members in alphabetical order based on their topic and then their name_last.
I do this with:
SELECT scicom_list ORDER BY topic <> 'Chair',topic,name_last;
This outputs the rows in the order of:
Chair
Endocrine
Metabolomics
Proteomics
Notice that topic <> 'Chair' is used to select all the rows with 'Chair' first. It then sorts the rows where topic = Chair by name_last.*
*This is a bit counterintuitive since <> equals != based on other feedback in this post.
This syntax can also be used to prioritize multiple categories. For instance, if I want to have "Chair" and then "Vice Chair" listed before the rest of the topics, I use the following
SELECT scicom_list ORDER BY topic <> 'Chair',topic <> 'Vice Chair',topic,name_last;
This outputs the rows in the order of:
Chair
Vice Chair
Endocrine
Metabolomics
Proteomics

In MySQL, <> means Not Equal To, just like !=.
mysql> SELECT '.01' <> '0.01';
-> 1
mysql> SELECT .01 <> '0.01';
-> 0
mysql> SELECT 'zapp' <> 'zappp';
-> 1
see the docs for more info

<> is equal to != i.e, both are used to represent the NOT EQUAL operation. For instance, email <> '' and email != '' are same.

I know im late to the game but maybe this will help somebody...
this is not true even though everyone wrote it
<> is equal to !=
it actually is less than or greater than
the exception is with NULL
column <> 3 will not get null columns
column != 3 will get null columns
hope it helps

Related

MySQL: Get total number of customers and total of each status within a store [duplicate]

I have two tables, one is for news and the other one is for comments and I want to get the count of the comments whose status has been set as approved.
SELECT
ccc_news . *,
count(if(ccc_news_comments.id = 'approved', ccc_news_comments.id, 0)) AS comments
FROM
ccc_news
LEFT JOIN
ccc_news_comments
ON ccc_news_comments.news_id = ccc_news.news_id
WHERE
`ccc_news`.`category` = 'news_layer2'
AND `ccc_news`.`status` = 'Active'
GROUP BY
ccc_news.news_id
ORDER BY
ccc_news.set_order ASC
LIMIT 20
But the problem with this query is that the minimum value that is fetched for the comments column is 1 whether there is any comment existent corresponding to that news or not.
Any help would be highly appreciable.
Use sum() in place of count()
Try below:
SELECT
ccc_news . * ,
SUM(if(ccc_news_comments.id = 'approved', 1, 0)) AS comments
FROM
ccc_news
LEFT JOIN
ccc_news_comments
ON
ccc_news_comments.news_id = ccc_news.news_id
WHERE
`ccc_news`.`category` = 'news_layer2'
AND `ccc_news`.`status` = 'Active'
GROUP BY
ccc_news.news_id
ORDER BY
ccc_news.set_order ASC
LIMIT 20
Better still (or shorter anyway):
SUM(ccc_news_comments.id = 'approved')
This works since the Boolean type in MySQL is represented as INT 0 and 1, just like in C. (May not be portable across DB systems though.)
As for COALESCE() as mentioned in other answers, many language APIs automatically convert NULL to '' when fetching the value. For example with PHP's mysqli interface it would be safe to run your query without COALESCE().
This should work:
count(if(ccc_news_comments.id = 'approved', ccc_news_comments.id, NULL))
count() only check if the value exists or not. 0 is equivalent to an existent value, so it counts one more, while NULL is like a non-existent value, so is not counted.
Replace this line:
count(if(ccc_news_comments.id = 'approved', ccc_news_comments.id, 0)) AS comments
With this one:
coalesce(sum(ccc_news_comments.id = 'approved'), 0) comments
count(ccc_news_comments.id = 'approved' or null)
More concise

SQL: Something wrong with inheriting variables for NULL next-row values

I'm trying to inherit value from previous row (based on correct subscription_id + checking for IS NULL subscription_status), but something goes wrong and I get incorrect value.
Take a look at screenshot.
If I'm not mistaken it also called last non-null puzzle, but examples of possible solution for other DB provide window function with IGNORE NULLS.
But, I'm using MySQL 8.x and it doesn't support this function.
I'm sorry, but SQL fiddle doesn't provide correct text-value for variables in my code :(
https://www.db-fiddle.com/f/wHanqoSCHKJHus5u6BU4DB/4
Or, you can see mistakes here:
SET #history_subscription_status = NULL;
SET #history_subscription_id = 0;
SELECT
c.date,
c.user_id,
c.subscription_id,
sd.subscription_status,
(#history_subscription_id := c.subscription_id) as 'historical_sub_id',
(#history_subscription_status := CASE
WHEN #history_subscription_id = c.subscription_id AND sd.subscription_status IS NULL
THEN #history_subscription_status
ELSE
sd.subscription_status
END
) as 'historical'
FROM
calendar c
LEFT JOIN
subscription_data sd ON sd.date = c.date AND sd.user_id = c.user_id AND sd.subscription_id = c.subscription_id
ORDER BY
c.user_id,
c.subscription_id,
c.date
I expect to get results for this query in this way:
IMPORTANT: I'm going to use this code for a lot of data (about 1 mln rows), so it very important for me to avoid additional select or subquery that can slow down the execution of the query.

Difference between "<>some" and "not in"

I was reading the books fundamentals of database systems and in the topic nested subqueries(set comparison) it was written that some and in are identical whereas <>some and not in are not.
According to me <>some means "not at least one" and not in means "not in the set"...so I think they should mean the same.
They are not the same!
<>SOME means: not = a or not = b or not = c...
NOT IN means: not = a and not = b and not = c...
Hope this will be more clear for you now.
For example:
SELECT CustomerID
FROM Sales.Customer
WHERE TerritoryID <> ANY
(SELECT TerritoryID
FROM Sales.SalesPerson);
This query return every single CustomerID with the exception of those for wich the TerritoryID is NULL.
While if you use NOT IN the query will return nothing.
<> only apply to 1 value, while "not in" apply to 1 or more values, e.g.
1. WHERE id <> '123'
2. WHERE id NOT IN ('123') --same as case 1
3. WHERE id NOT IN ('123', '456')

SELECT different row IF no rows returned

This is kind of hard to headline, but given this statement:
SELECT DISCOUNT FROM people_discounts WHERE ID = ? AND PGROUP = ?
Let's assume I enter ID 5 and PGROUP 2. This row does not exist in the table (fetch returns false in the case of PHP and mysqli). In that case I want the row that would have been presented had the statement been:
SELECT DISCOUNT FROM people_discounts WHERE ID = ? AND PGROUP = 0
With ID still being 5, but PGROUP "fallen back" to 0 instead, which let's assume always exists.
Is this possible with some kind of IF, CASE or maybe some other keyword that I'm not aware of?
I know this can of course be accomplished by running a second statement in the case of no rows, but that's not what I'm trying to do.
presuming the query should only ever return a single row
select discount from people_discount
where id = ? and (pgroup = ? or pgroup = 0)
order by pgroup desc
limit 1;
If limit seems "impure" you could use other tricks.
This might be more portable though it assumes that discount is never negative:
select abs(max(case when proup <> 0 then discount else -discount end))
from people_discount
where id = ? and pgroup in (?, 0)
group by id
Not every platform has a top/limit/fetch option. And some people object to non-set-based queries. I'm simply offering a hack of sorts with those people in mind or at least as an exercise in thinking about problems in a different way.
The idea is just to assume there cannot be a negative discount and to use that end of the number scale to temporarily "store" the fallback discount for pgroup 0. MAX() accomplishes the equivalent of sorting and limiting by favoring the positive value when both are present. ABS() restores the sign of the result.

Having trouble with an IFNULL in a mySQL WHERE clause

Before anyone says, I have searched through for a suitable answer for my issue but cannot find anything specific enough so I thought I'd ask it.
Basically I am trying to select a bunch of data for a report of people who have made loan applications to a website, but there are two different types: unsecured and guarantee. I need to place an IFNULL statement in the WHERE clause so that I ONLY use that clause if a certain other field isn't null.
Here is my statement:
SELECT
la.`lms_loan_application_id`,
la.`created`,
la.`updated`,
la.`loan_amount`,
la.`loan_term`,
la.`loan_document_fee`,
la.`broker_reference`,
la.`broker_sub_reference`,
laa.`first_name`,
laa.`surname`,
laa.`dob`,
laa.`email`,
laa.`mobile_number`,
laaAd.`address_postcode`,
lag.`first_name`,
lag.`surname`,
lag.`dob`,
lag.`email`,
lag.`mobile_number`,
lagAd.`address_postcode`,
lagAd.`housing_status`
FROM
loan_application AS la
JOIN
loan_application_applicant AS laa ON la.`id` = laa.`loan_application`
LEFT JOIN
loan_application_guarantor AS lag ON la.`id` = lag.`loan_application`
JOIN
loan_application_address AS laaAd ON laaAd.`loan_application_applicant` = laa.`id`
LEFT JOIN
loan_application_address AS lagAd ON lagAd.`loan_application_guarantor` = lag.`id`
WHERE
la.`status` = 'signature_given'
AND ! IFNULL(lag.`first_name`,
lag.`status` = 'signature_given')
AND laa.`status` = 'signature_given'
AND ! IFNULL(lag.`first_name`,
lagAd.`current_address` = 1)
AND laaAd.`current_address` = 1
ORDER BY la.`updated` DESC
LIMIT 10000
As you can see, I have attempted to use the IFNULLs (although in a negated way, which I assume works?) but all I get is duplicate row results and not the result set I really want.
Basically, I need to use the where clause "lag.status = 'signature_given" and "lagAd.current_address = 1" ONLY if the lag.first_name field is NOT null (i.e. there is a guarantor name) otherwise the status won't exist, and therefore the results of unsecured loans will not show. Hope I'm explaining this well enough!
In summary, I need to show all loan information, unsecured and guaranteed, and use a negated IFNULL in order to determine when the WHERE clause is to be taken into consideration.
Any help appreciated!
Thank you in advance
Michael
From this MySQLTutorial article:
Notice that you should avoid using the IFNULL function in the WHERE clause, because it degrades the performance of the query. If you want to check if a value is NULL or not, you can use IS NULL or IS NOT NULL in the WHERE clause.
Here is a WHERE clause which implements your logic correctly using IS NULL and IS NOT NULL instead of IFNULL:
WHERE la.`status` = 'signature_given' AND
(lag.`first_name` IS NULL OR
(lag.`first_name` IS NOT NULL AND lag.`status` = 'signature_given')) AND
laa.`status` = 'signature_given' AND
(lag.`first_name` IS NULL OR
(lag.`first_name` IS NOT NULL AND lagAd.`current_address` = 1)) AND
laaAd.`current_address` = 1