SQL sum select returns null - mysql

I want to obtain unread messages count from MySQL database using SELECT SUM operator.
So, my SQL is:
SELECT sum(status_field = 'new') unreadMessagesCount
FROM messages
WHERE 'author_uid' = 'authorUID'
And it returns NULL. Why?
I have items in database and I can select it by (SELECT * FROM messages)

It returns NULL because you are comparing strings, not columns with:
WHERE 'author_uid' = 'authorUID'
And these two strings are not equal. So, all rows are filtered out. The NULL value is because you have an aggregation query. SUM() returns NULL when there are no rows in such a query.
I'm not sure what you intend. Perhaps:
WHERE author_uid = 'authorUID'
However, 'authorUID' seems like a strange value for a uid. You need to put an appropriate value there. If it is a string, enclose it in single quotes. If it is a number, do not use single quotes.

Related

Replace null with zero in sql query

I have an sql query that could potentially return null values, in the event of this I want the query to return '0'. Here is the query
SELECT (select count(goal) from fixtures where goal='1' and fixture='$fixture') as goalCountHome
from fixtures where fixture='$fixture'LIMIT 1
Any help much appreciated!
In MySql use IFNULL() function. For MsSql use ISNULL() function.
If you are using MySql, IFNULL(<column_name>, 0) should do.
This query:
SELECT (select count(goal) from fixtures where goal='1' and fixture='$fixture') as goalCountHome
FROM fixtures
WHERE fixture = '$fixture'
LIMIT 1
cannot return NULL values. The subquery is an aggregation query with no GROUP BY, so it always returns one row. That row will contain a result from COUNT(). COUNT() itself can never return a NULL value. If there are no rows, then the value will be zero.
The outer query might return no rows but that is different from NULL values.
Of course, this query is way overcomplicated, and should simply be:
SELECT COUNT(*) as goalCountHome
FROM fixtures
WHERE fixture = ? AND -- pass this in as a parameter
goal = 1 ; -- it looks like a number so I assume it is
Note that you should be passing parameters in using proper parameters rather than munging query strings.
if you need all the rows and not the rows where goal is not null you could use count(*)
select count(*)
from fixtures
where goal=1
and fixture='$fixture'
count(goal) return the number of rows where goal is not null
count(*) return the total number rows selected
otherwise in general when you need not null values in mysql you can ifnull(your_column, value) or coalesce(your_column, value)
based on you comment seems you need sum(goal)
select sum(ifnull(goal,0))
from fixtures
where goal=1
and fixture='$fixture'

MySQL Return the first non-NULL value from the list of the column in select statement with column name

I have a sql query below:
SELECT
md.refereeInternetSearch,
md.refereeCompanyColleague,
md.refereeIndustryPeer,
md.refereeIndustryEvent,
md.refereeIndustryPublication,
md.refereeMarketingEmail,
md.refereeOther
FROM
marketing_details md
WHERE
md.id = 14588
From the 7 columns in the above select statement only one column will have a value and rest will be null. Is it possible to select just that one column value that is not null using some sort of sql statement ?
Use the coalesce() function to return the 1st non-null value from a list of parameters:
SELECT
coalesce(md.refereeInternetSearch,
md.refereeCompanyColleague,
md.refereeIndustryPeer,
md.refereeIndustryEvent,
md.refereeIndustryPublication,
md.refereeMarketingEmail,
md.refereeOther) as non_null_value
FROM
marketing_details md
WHERE
md.id = 14588
However, it will not be able to tell you which column the value came from.
UPDATE
If you really want to use sql to retrieve the name of the field that has the non null value, then you can do that with the following monstrous sql statement below. What it does it concatenates each field value from a record into a single string, where the values are separated by comma. NULL values are converted to empty string. Then using find_in_set() function it finds the position of the only non null value within the above string. Then using the elt() function it returns the name of the field from the list of field name literals based on the position returned by find_in_set().
SELECT
md.id,
coalesce(md.refereeInternetSearch,
md.refereeCompanyColleague,
md.refereeIndustryPeer,
md.refereeIndustryEvent,
md.refereeIndustryPublication,
md.refereeMarketingEmail,
md.refereeOther) as non_null_value,
elt(find_in_set(coalesce(md.refereeInternetSearch,
md.refereeCompanyColleague,
md.refereeIndustryPeer,
md.refereeIndustryEvent,
md.refereeIndustryPublication,
md.refereeMarketingEmail,
md.refereeOther),
concat(coalesce(md.refereeInternetSearch,''),',',
coalesce(md.refereeCompanyColleague,''),',',
coalesce(md.refereeIndustryPeer,''),',',
coalesce(md.refereeIndustryEvent,''),',',
coalesce(md.refereeIndustryPublication,''),',',
coalesce(md.refereeMarketingEmail,''),',',
coalesce(md.refereeOther,'')
)
),'refereeInternetSearch',
'refereeCompanyColleague',
'refereeIndustryPeer',
'refereeIndustryEvent',
'refereeIndustryPublication',
'refereeMarketingEmail',
'refereeOther'
) as field_name
FROM
marketing_details md
WHERE
md.id = 14588
Huh, I hope I got all the parentheses right!

In MySQL select query, checking for a string or checking for true in a where clause?

Consider the following table:
SELECT id, Bill_Freq, Paid_From, Paid_To, Paid_Dt, rev_code FROM psr_20160708091408;
The requirement is to fetch the row which has rev_code populated with the string **SUM**.
I've also noticed that for every row with rev_code populated as **SUM** its Bill_Freq won't be either null or zero.
So I wrote two queries to fetch the row with the lowest id
Query based on string check in where clause:
select
min(id) as head_id,
bill_freq,
Paid_From,
Paid_To,
Paid_Dt
from
`psr_20160708091408` where rev_code = "**SUM**";
Query based on true condition:
select
min(id) as head_id,
bill_freq,
Paid_From,
Paid_To,
Paid_Dt
from
`psr_20160708091408` where bill_freq;
I haven't seen anyone use the second type, would like to know its reliability and circumstance of failure.
If by "second type" you mean a where clause with no explicit condition, then there is a good reason why you do not see it.
The SQL standard -- and most databases -- require explicit conditions in the where. MySQL allows the shorthand that you use but it really means:
where not billing_freq <=> 0
or equivalently:
where billing_freq <> 0 or billing_freq is null
(The <=> is the null-safe comparison operator.
The more important issue with your query is the min(). I presume that you actually want this:
select p.*
from psr_20160708091408 p
where rev_code = '**SUM**'
order by id
limit 1;
Also, you should use single quotes as string delimiters. That is the ANSI standard and there is rarely any reason to use double quotes.
Actually you can use the second type of query, but as your requirement is based on rev_code, it is always good to have condition with rev_code, because of 2 reasons
Bill_Freq having no NUlls or Zeros might be assumption based on current data
Even if it is true, in future, your application logic might change and it might have a scenario having NULL or zero, which will break your logic in future.
So my suggestion is to use first query with Rev_code
Please try to use below query
select
id,
bill_freq,
Paid_From,
Paid_To,
Paid_Dt
from
`psr_20160708091408` where rev_code = "**SUM**" ORDER BY ASC LIMIT 0,1;
Thanks.
The requirement says it itself.
The requirement is to fetch the row which has rev_code populated with
the string '**SUM**'
In the scenario that bill_freq IS NOT NULL and rev_code is populated with
the string '**SUM**' then your logic will obviously fail.
Go for
where rev_code = "**SUM**";

LIKE clause not returning when comparing numbers with single quotes

I have a query contains a field transaction_id and data type integer.
In the WHERE condition of below query I have LIKE operator, in this case if I give transaction_id LIKE '00412552' I am not getting data.
Suppose if I give transaction_id LIKE 00412552 then I am getting data.
I think it is not taking string type as operator, please suggest what is the problem.
SELECT DISTINCT crt.carton_no,
crt.shipment_ref_no,
crt.put_away_location,
crt.item_category,
crt.total_quantity
FROM carton crt
RIGHT OUTER JOIN pick_list pl
ON (crt.carton_no = pl.carton_no AND
crt.shipment_ref_no = pl.shipment_ref_no)
WHERE pl.transaction_id LIKE '00412552'

I need some help getting MySql to output some results using a subquery

I'm storing a list of numbers inside a table as a varchar(255) and want to use this list in another query's "IN() clause.
Here's what I mean:
Table Data:
CREATE TABLE IF NOT EXISTS `session_data` (
`visible_portf_ids` varchar(255) DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
INSERT INTO `session_data` (`visible_portf_ids`) VALUES
('45,44,658,659,661,45,44,658,659,661')
I want to run a query like this to return a list of portfolio's "QUERY #1":
SELECT portfolio_hierarchy_id, account_id, name, leaf_node_portf_id
FROM portfolio_hierarchy
WHERE account_id = 1
AND leaf_node_portf_id IN
(
(SELECT visible_portf_ids
FROM session_data
WHERE username = 'ronedog')
)
ORDER BY name ASC
The result of the query above returns only 1 row, when there are a total of 3 that should have been returned.
If I run the subquery alone like this:
(SELECT visible_portf_ids
FROM session_data
WHERE username = 'ronedog')
it will return a list like this:
45,44,658,659,661,45,44,658,659,661
But, when I run Query #1 above, only one row of data, which is associated with the "visible_portf_ids" of "45" is returned.
If I replace the subquery with hard coded values like this:
SELECT portfolio_hierarchy_id, account_id, name, leaf_node_portf_id
FROM portfolio_hierarchy
WHERE account_id = 1
AND leaf_node_portf_id IN (45,44,658,659,661,45,44,658,659,661)
ORDER BY name ASC
then I get all 3 rows I'm expecting.
I'm guessing that MySql is returning the list as a string because its stored as a varchar() and so it stops processing after the first "visible_portf_ids" is found, which is "45", but I'm not really sure.
Anyone got any ideas how I can fix this?
Thanks in advance.
You should think about restructuring your tables storing each value in a new row, instead of concatenating them.
Until then, you can use the FIND_IN_SET() function:
AND FIND_IN_SET(leaf_node_portf_id,
(SELECT visible_portf_ids
FROM session_data
WHERE username = 'ronedog'
LIMIT 1)
) > 0
Unfortunately MySQL does not have a function to split a delimited string. Your IN argument is a single string with the result of your subquery. The reason it works when you hard-code it is that MySQL is parsing the values.
I suggest that you redesign your data base to store the visible ports list as separate rows in a separate table. Then you can retrieve them and use them in subqueries like you tried.