COUNT(*) vs EXISTS in SQL: Indexing Matters

Is COUNT(*) really a BAD IDEA for existence checks in SQL? I didn’t just believe it - I tested it as below, Dataset: ~20,000 records Indexed column: user_email Queries Tested: -- 1. COUNT(*) SELECT COUNT(*)  FROM users  WHERE user_email = 'user830@example.com'; -- 2. EXISTS SELECT EXISTS (  SELECT 1   FROM users   WHERE user_email = 'user830@example.com' ); -- 3. LIMIT 1 SELECT 1  FROM users  WHERE user_email = 'user830@example.com' LIMIT 1; EXPLAIN Output (Screenshot Attached) All queries show: type: const rows: 1 Using index Meaning: All 3 queries are optimized and fast 🤔 So… is COUNT(*) really bad? Not always. With proper indexing: Even COUNT(*) performs efficiently No full table scan Direct index lookup happens ✅ Real-World Takeaway ✔ Use EXISTS → for correct intent (true/false) ✔ Use LIMIT 1 → for simple & fast API checks ✔ Use COUNT(*) → when you actually need the count 🔥 The Real Lesson ❌ Problem is NOT COUNT(*) ✅ Problem is missing indexes 💬 Final Thought 👉 “First optimize your indexing… then worry about query patterns.” 📸 Sharing my real EXPLAIN output below 👇 Have you tested this in your system? #SQL #MySQL #DatabaseOptimization #MuraliCodes #BackendDevelopment #PerformanceTuning #Developers #LearningInPublic

  • graphical user interface, text, application

Try the same without index - you’ll see the real difference 👀

Like
Reply

To view or add a comment, sign in

Explore content categories