-1

SELECT with WHERE Clause returns a new sequence of items matching the predicate by iteration.

Is there is any way to predict the given Search Criteria is available or not (Boolean) in MySQL?

Sample SQL

CREATE TABLE Ledger
(
PersonID int,
ldate date,    
dr float,
cr float,
bal float
);

INSERT INTO Ledger(PersonID, ldate, dr, cr, bal)
VALUES 
('1001', '2016-01-23', 105 ,0 ,0),
('1001', '2016-01-24', 0, 5.25, 0),
('1002', '2016-01-24', 0, 150, 0),
('1001', '2016-01-25', 0, 15, 0),
('1002', '2016-01-25', 73, 0, 0); 

Here I need to Check PersonID 1002 is exist or not

Common Way of Checking is

SELECT COUNT(PersonID) > 0 AS my_bool FROM Ledger WHERE PersonID = 1002

SELECT COUNT(*) > 0 AS my_bool FROM Ledger WHERE ldate = '2016-01-24' AND (bal > 75 AND bal <100)

The above two queries are only for sample.

But, the above SELECT Query iterates the whole collection and filters the result. It degrades the Performance in a very Big Database Collection (over 300k active records).

Is there's a version with a predicate (in which case it returns whether or not any items match) and a version without (in which case it returns whether the query-so-far contains any items).

Here I given a very simple WHERE Clause. But in real scenario there is complex WHERE Clause. .NET there is a method .Any() it predicts the collection instead of .Where().

How to achieve this in a efficient way?

James Z
  • 12,209
  • 10
  • 24
  • 44
B.Balamanigandan
  • 4,713
  • 11
  • 68
  • 130

1 Answers1

1

You can optimise by using EXISTS

SELECT EXISTS
(
  SELECT 1
  FROM Ledger 
  WHERE ldate = '2016-01-24' 
  AND (bal > 75 AND bal < 100)
) AS my_bool

It will return as soon as a match is found.

Click here to have a play on SQL Fiddle

More info here:

Optimizing Subqueries with EXISTS Strategy

Best way to test if a row exists in a MySQL table

Subqueries with EXISTS vs IN - MySQL

Community
  • 1
  • 1
davmos
  • 9,324
  • 4
  • 40
  • 43