reuse "sum(table_column) as x" - mysql

I have a problem with an SQL query.
SELECT SUM(table_colum) AS value, SUM(value * 3) AS value2 FROM table;
You need to know this is a short representation of my whole query.
The error:
Unknown column 'value' in 'field list'
Is there a way to reuse value in another SUM()?

You can just do:
SELECT SUM(table_colum) AS value, SUM(SUM(table_colum) * 3) AS value2 FROM table;
Internally, the server will only do the SUM(table_colum) calculation once and use the result twice.

I suppose you could write
SELECT value, SUM(value * 3) AS value2
FROM ( SELECT SUM(table_column) AS value
FROM table
) AS t
;
But as I mentioned in a comment above, I'm not sure what you would want this for. SUM(table_column) is just a single value, so the SUM of it is just the same value. So you'd get the same result by writing:
SELECT value, value * 3 AS value2
FROM ( SELECT SUM(table_column) AS value
FROM table
) AS t
;
without the second SUM.

Related

WHERE x IN works with a single value, not with multiple on json

There's a hard to understand issue with querying on a json field in MySQL. The data column is of type json.
The following query works perfectly fine
SELECT * FROM `someTable` WHERE data->'$.someData' in ('A')
However the following one returns nothing.
SELECT * FROM `someTable` WHERE data->'$.someData' in ('A','B')
Funnily enough this also works:
SELECT * FROM `someTable` WHERE data->'$.someData'='A' OR data->'$.someData'='B'
I'm clueless as to why this happens. I originally thought that WHERE x IN executed in a json query format might be doing something like && but even if the values are ('A','A') it still returns nothing which essentially shows that more than one value in WHERE x IN wont work.
SAMPLE DATA (any would do really)
id | data (json)
1 | {"someData":"A"}
2 | {"someData":"B"}
Too long for a comment...
This seems to be related to an optimisation MySQL is performing when there is only one value in the IN expression (probably converting it to an a = b expression) and then it ignoring quotes. Strictly speaking,
SELECT *
FROM `someTable`
WHERE data->'$.someData' in ('A')
or
SELECT *
FROM `someTable`
WHERE data->'$.someData' = 'A'
should return no data because
SELECT data->'$.someData'
FROM someTable;
returns
"A"
"B"
which is not the same as A. You need to use JSON_UNQUOTE (or if you have MySQL 5.7.13 or later the ->> operator) to get the actual value of the someData key:
SELECT JSON_UNQUOTE(data->'$.someData') FROm someTable;
SELECT data->>'$.someData' FROm someTable;
which gives
A
B
which then works fine with an IN expression:
SELECT *
FROM `someTable`
WHERE JSON_UNQUOTE(data->'$.someData') in ('A','B')
-- or use WHERE data->>'$.someData' in ('A','B')
Output:
id data
1 {"someData":"A"}
2 {"someData":"B"}
Demo on dbfiddle
You could try using a join on a subquery instead of a IN clause
SELECT *
FROM `someTable` s
INNER JOIN (
select 'A' col
union
select 'B'
) t ON t.col = s.data->'$.someData

What is the expression that will always be true while using SQL WHERE IN comparison query

SELECT *
FROM TABLE_X
WHERE 'Value' IN (SELECT * FROM TABLE_Y)
What expression can I use instead of 'Value' so that the WHERE clause where always return true?
I am trying to do something like:
WHERE (SELECT field FROM TABLE_Y) LIKE '%Value%'
Found the solution, use EXISTS instead of WHERE IN:
SELECT *
FROM TABLE_X
WHERE EXISTS (SELECT field FROM TABLE_Y WHERE field LIKE '%Value%')
I don't know if I understood it well, it's silly to do the following, but returns all the records in TABLE_X:
SELECT *
FROM TABLE_X
WHERE 1 IN (SELECT field FROM TABLE_Y)
NOTE: ...IN (SELECT * ...) crashes because you should choose just one column, that's why I wrote field instead of *
You cannot compare your 'Value' with *, you need a specified field from TABLE_Y, for example:
SELECT *
FROM TABLE_X
WHERE (SELECT Field FROM TABLE_Y WHERE Field LIKE '%Value%' LIMIT 1) IS NOT NULL

How to return NULL when result is empty?

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

How to alias a field or column in MySQL?

I'm trying to do something like this. But I get an unknown column error:
SELECT SUM(field1 + field2) AS col1, col1 + field3 AS col3 from core
Basically, I want to just use the alias so that I won't need to perform the operations performed earlier. Is this possible in mysql?
select #code:= SUM(field1 + field2), #code+1 from abc;
But, please be aware of the following (from the MySQL 5.6 docs):
As a general rule, other than in SET statements, you should never assign a value to a user variable and read the value within the same statement. For example, to increment a variable, this is okay:
SET #a = #a + 1;
For other statements, such as SELECT, you might get the results you expect, but this is not guaranteed. In the following statement, you might think that MySQL will evaluate #a first and then do an assignment second:
SELECT #a, #a:=#a+1, ...;
However, the order of evaluation for expressions involving user variables is undefined.
So, use at your own risk.
Consider using a subquery, like:
SELECT col1
, col1 + field3 AS col3
FROM (
SELECT field1 + field2 as col1
, field3
from core
) as SubQueryAlias
You can select the alias:
SELECT SUM(field1 + field2) AS col1, (select col1) + field3 AS col3 from core
This works.
select #code:= SUM(field1 + field2), (#code*1) from abc;
#code*1 covert into numeric expression and you can use anywhere like
select #code:= SUM(field1 + field2), (#code*1)+field3 from abc;
Short answer is no:
mysql> select 1 as a, a + 1 as b;
ERROR 1054 (42S22): Unknown column 'a' in 'field list'
postgresql# select 1 as a, a + 1 as b;
ERROR: column "a" does not exist
That said, some SQL implementations allow to use the aliases in where/group by/having clauses, e.g.:
postgresql# select 1 as a group by a; -- 1 row
In case you are using it with aggregate function (group by) and if it doesn't work for you place the calculated column to the end with forward column referecing.
SELECT FNC2(AF), FNC1(A) AS AF, B, C, FROM Table GROUP BY ...
1st one doesn't work due to forward column referencing. Do this instead
SELECT FNC1(A) AS AF, B, C, FNC2((SELECT AF)) FROM Table GROUP BY ...

mysql NULL value in where in CLAUSE

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)