Databases 3 min read

Why Replace COUNT(*) with SELECT 1 LIMIT 1 for Faster Existence Checks

The article explains that using SELECT 1 with LIMIT 1 instead of COUNT(*) to test whether rows exist can dramatically improve query performance, shows the typical COUNT(*) approach in SQL and Java, and provides a streamlined alternative with code examples and practical benefits.

Senior Brother's Insights
Senior Brother's Insights
Senior Brother's Insights
Why Replace COUNT(*) with SELECT 1 LIMIT 1 for Faster Existence Checks

Current Common Practice

Many developers check for the existence of records by counting rows, even when they only need to know whether at least one row matches the criteria.

SELECT count(*) FROM table WHERE a = 1 AND b = 2;

Typical Java code mirrors this pattern:

int nums = xxDao.countXxxxByXxx(params);
if (nums > 0) {
    // execute when a record exists
} else {
    // execute when no record exists
}

Optimized Approach

Instead of counting, query for a constant value and stop after the first match using LIMIT 1. This avoids scanning all matching rows.

SELECT 1 FROM table WHERE a = 1 AND b = 2 LIMIT 1;

Corresponding Java code can use a DAO method that returns a non‑null value when a row is found:

Integer exist = xxDao.existXxxxByXxx(params);
if (exist != NULL) {
    // execute when a record exists
} else {
    // execute when no record exists
}

Using LIMIT 1 makes the database stop searching after the first matching row, which can significantly improve performance, especially when many rows satisfy the condition, and may reduce the need for additional composite indexes.

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

JavaperformanceoptimizationSQLExistence Check
Senior Brother's Insights
Written by

Senior Brother's Insights

A public account focused on workplace, career growth, team management, and self-improvement. The author is the writer of books including 'SpringBoot Technology Insider' and 'Drools 8 Rule Engine: Core Technology and Practice'.

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.