MySQL: Check if there Exist Row(s) Matching a Condition - mysql

I have been doing this for quite some time:
SELECT COUNT(*) FROM Table WHERE Condition = *Condition*;
Since I am not interested in the total number of rows returned, I wonder if there is a more efficient way to check if there exist any row(s) that match the condition without letting MySQL scan through the entire table.

SELECT CASE
WHEN EXISTS(SELECT *
FROM YourTable
WHERE Condition = '*Condition*') THEN 1
ELSE 0
END

Try
SELECT COUNT(*) FROM SmallTable
WHERE EXISTS(SELECT * FROM Table WHERE Condition = *Condition*)

Related

sub query returns more than 1 - issue with passing values into subquery

I am running the following query which keep stating that more then one row is given:
select filestorage.id
from `filestorage`
where (SELECT LEFT(filestorage_inst_data.value, length(filestorage_inst_data.value - 1)) as seconds
FROM filestorage_inst_data
WHERE filestorage_inst_data.parameter = "Time" AND filestorage_inst_data.filestorage_id = filestorage.id) <= 3600
For some reason, the only very first value is passed into the subquery. Also, if I do set a limit within the subquery than the data is fetched fine, it's just I don't see why query would fetch multiple results?
Try this:
SELECT filestorage.id
FROM filestorage f
WHERE EXISTS(SELECT 1 FROM filestorage_inst_data fid
WHERE fid.parameter = 'Time'
AND fid.filestorage_id = f.id
AND CAST(LEFT(fid.value, length(fid.value - 1)) AS UNSIGNED) <= 3600)
You have to pass a specific one row when giving a select statement on where clause. select clause that, the one you using on where clause must return one unique row. for example.
"SELECT * FROM user WHERE role_id=(SELECT role_id FROM user_role WHERE role_name='Admin');"

Update with select and cases 'when/then'

When I try to execute this:
update YUmowa_Kontrahent set YUK_Typ_Umowy= 'WS'
where YUK_IdObiekt in (select YO_Id,
sum(isnull(YROB_WZ_Woda,0))as woda,
sum(isnull(YROB_WZ_Scieki,0))as scieki ,
case
when sum(isnull(YROB_WZ_Woda,0))> 0 and sum(isnull(YROB_WZ_Scieki,0))>0 Then 'WS'
end WS
from YObiekt
join YRozliczenie_Obiekt on YO_Id=YROB_IdObiekt
group by YO_Id)
I recieve:
Msg 116, Level 16, State 1, Line 45 Only one expression can be
specified in the select list when the subquery is not introduced with
EXISTS.
I need to update TYP UMOWY= 'WS' ON DBO.YUMOWA_KONTRAHENT which after sum records of 'WODA' & 'SCIEKI' >0
i specified in sub-query unique ID'S so???
Your select is wrong because you can't use in with on the left 1 parameter and on the right 3 parameters:
select *
from table
where a in (select a, b, c from table2)
Instead you should use: where a in (select a from table2)
UPDATE YUmowa_Kontrahent
SET YUK_Typ_Umowy = 'WS'
WHERE YUK_IdObiekt IN (
SELECT YO_Id
FROM YObiekt
JOIN YRozliczenie_Obiekt ON YO_Id = YROB_IdObiekt
GROUP BY YO_Id
HAVING sum(isnull(YROB_WZ_Woda,0)) > 0 AND sum(isnull(YROB_WZ_Scieki,0)) > 0
)
The subquery in your query is wrong:
If you use some statement except EXISTS, you have to specify only
one expression in the select list (as you could read in the error
message).
Your subquery returns all YO_Id rather than return only that meet
the condition sum(isnull(YROB_WZ_Woda,0)) > 0 AND sum(isnull(YROB_WZ_Scieki,0)) > 0
Of course, I don't know the structure of your tables, but it seems
you don't need to join two tables in subquery but use only the table
with fields YROB_WZ_Scieki and YROB_WZ_Woda to get IDs.

MySQL query to get fields from a table where the ID exists in another query

This must be fairly straight forward, as I tend to use ORMs I don't have to get my hands dirty often and am therefore struggling!
I have a database and want to get several fields from a table, that bit is easy..
SELECT main_table.registration_number, main_table.registered_name FROM main_table;
I want to filter the results based on another table, which is also easy..
SELECT second_table.registration_number FROM second_table WHERE this_field = '' AND that_field = '0';
Now the problem is I want to run the first query based on the second queries result set, I was thinking something like this:
SELECT main_table.registration_number, main_table.registered_name FROM main_table WHERE main_table.registration_number IN (SELECT * FROM second_table WHERE this_field = '' AND that_field = '0');
This gives me: Error Code: 1241. Operand should contain 1 column(s)
Am I handling this completely wrong?
Your subquery should do something like below,
(select * from table) in subquery is not what you really need to do your
so the subquery should return one column
(SELECT registration_number FROM second_table WHERE this_field = '' AND that_field = '0');
You cannot have multiple columns being returned in a subquery like
that, doing so it will result in such error
You have to select a column
SELECT main_table.registration_number, main_table.registered_name FROM
main_table WHERE main_table.registration_number IN (SELECT
registration_number FROM second_table WHERE this_field = '' AND
that_field = '0');

MySQL SELECT 1 vs SELECT `field_id` AND COUNT 1 vs COUNT (*) or COUNT (`field_id`) Performance wise

I have a very simple question.
I want to know if a certain database row exists.
I generally use :
SELECT 1 FROM `my_table` WHERE `field_x` = 'something'
Then I fetch the result with :
$row = self::$QueryObject->fetch();
And check if any results :
if(isset($row[1]) === true){
return(true);
}
You can do this also with :
COUNT 1 FROM `my_table` WHERE `field_x` = 'something'
And similar to COUNT * FROMmy_tableandCOUNT field_id FROM `my_table
But I was wondering.. How does this relate to performance?
Are there any cons to using SELECT 1 or COUNT 1??
My feeling says that select INTEGER 1 means the lowest load.
But is this actually true??
Can anyone enlighten me?
Actually all your solutions are suboptimal :) What you do with your queries is reading every row there is to be found, even if you add limit. Do it like this:
SELECT EXISTS ( SELECT 1 FROM `my_table` WHERE `field_x` = 'something');
EXISTS returns 1 if something was found, 0 if not. It stops searching as soon as an entry was found. What you select in the subquery doesn't matter, you can even select null.
Also keep in mind, that COUNT(*) or COUNT(1) are very different from COUNT(column_name). COUNT(*) counts every row, while COUNT(column_name) only count the rows that are not null.
If you add the LIMIT 1 to the end of the query then SELECT works better than COUNT especially when you have a large table.

Mysql Query Efficiency

I have a mysql table of data and I need to only return the rows that do not have a status of "Deactive" and do not have a Total of 0 (but there can be rows where status is deactive and total is not 0 and vice versa). Before I needed this requirement I was just doing the standard query to select all rows:
SELECT * FROM tableName WHERE uid = id;
However now when I change the query to add the constraints above:
SELECT * FROM tableName WHERE uid = id AND (status != "Deactive" OR Total != 0);
This bottom query is taking much much longer to complete. Why is this happening and is there a better way I can do this query?
The first query is looking up based on an index (I'm assuming by 'uid'). The second query is filtering on other values. Run this, and it will help you figure out how you can best optimize it:
EXPLAIN EXTENDED SELECT * FROM tableName WHERE uid = id AND status != "Deactive" OR Total != 0;
It's dirty, but this would probably be a quick way to speed it up:
SELECT
*
FROM
(
SELECT
*
FROM
tableName
WHERE
uid = id
) as temp
WHERE
temp.status != "Deactive"
OR temp.Total != 0;
This would force the query to just get the rows with a matching uid first, and then filter them down, instead of having to do a big table scan. Like I said before though, EXPLAIN EXTENDED is your friend
Do you need to return all the data in each row? ie picking only the columns you need will make the query run faster.
You also say you need to 'return the rows that do not have a status of "Deactive" and do not have a Total of 0'. Your query should then read:
SELECT * (or column names) FROM tableName WHERE uid = id AND status != "Deactive" AND Total != 0;