惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

L
LangChain Blog
Security Latest
Security Latest
P
Proofpoint News Feed
GbyAI
GbyAI
PCI Perspectives
PCI Perspectives
博客园 - Franky
N
Netflix TechBlog - Medium
博客园_首页
WordPress大学
WordPress大学
K
Kaspersky official blog
CTFtime.org: upcoming CTF events
CTFtime.org: upcoming CTF events
Threat Intelligence Blog | Flashpoint
Threat Intelligence Blog | Flashpoint
Vercel News
Vercel News
T
Threatpost
The Hacker News
The Hacker News
H
Help Net Security
S
Securelist
Recent Announcements
Recent Announcements
腾讯CDC
T
Tailwind CSS Blog
Cyber Security Advisories - MS-ISAC
Cyber Security Advisories - MS-ISAC
cs.CL updates on arXiv.org
cs.CL updates on arXiv.org
Engineering at Meta
Engineering at Meta
C
Cisco Blogs
V
V2EX
C
Check Point Blog
S
Schneier on Security
Cyberwarzone
Cyberwarzone
C
Cybersecurity and Infrastructure Security Agency CISA
奇客Solidot–传递最新科技情报
奇客Solidot–传递最新科技情报
B
Blog RSS Feed
H
Hackread – Cybersecurity News, Data Breaches, AI and More
Jina AI
Jina AI
M
MIT News - Artificial intelligence
T
Threat Research - Cisco Blogs
博客园 - 叶小钗
A
Arctic Wolf
AWS News Blog
AWS News Blog
Latest news
Latest news
Martin Fowler
Martin Fowler
Recorded Future
Recorded Future
Last Week in AI
Last Week in AI
The GitHub Blog
The GitHub Blog
小众软件
小众软件
B
Blog
aimingoo的专栏
aimingoo的专栏
C
Cyber Attacks, Cyber Crime and Cyber Security
V
Visual Studio Blog
P
Palo Alto Networks Blog
Spread Privacy
Spread Privacy

DEV Community

Authentication Security Deep Dive: From Brute Force to Salted Hashing (With Java Examples) Why AI Systems Don’t Fail — They Drift Spilling beans for how i learn for exam😁"Reinforcement Learning Cheat Sheet" I Replaced Chrome with Safari for AI Browser Automation. Here's What Broke (and What Finally Worked) How Python Borrows Other People's Work The $40 Architecture: Processing 1 Billion API Requests with 99.99% Uptime Vibe Coding: A Workflow Guide (From Zero to SaaS) Most webhook security guides protect the wrong side. The scary part is delivery. Headless CMS for TanStack Start: Build a Blog with Cosmic EU Age Verification App "Hacked in 2 Minutes" — What Actually Happened Comfy Cloud’s delete function does not actually remove files Running AI Models on GPU Cloud Servers: A Beginner Guide Event-driven media intelligence with AWS Step Functions and Bedrock I scored 500 AI prompts across 8 quality dimensions — here's what broke How to Call Google Gemini API from Next.js (Free Tier, No Backend Needed) The Portal Protocol: Reclaiming Human Connection in the Age of AI How to Fix Your Team's Scattered Knowledge Problem With a Self-Hosted Forum Intro to tc Cloud Functors: A Graph-First Mental Model for the Modern Cloud Designing Multi-Tenant Backends With Both Ownership and Team Access I Built a Neumorphic CSS Library with 77+ Components — Here's What I Learned PostgreSQL Performance Optimization: Why Connection Pooling Is Critical at Scale Cómo construí un SaaS multi-rubro para gestionar expensas en Argentina con FastAPI + Vue 3 🚀 I Built an Ethical Hacking Scanner Tool – Open Source Project I Replaced /usage and /context in Claude Code With a Single Statusline A Pythonic Way to Handle Emails (IMAP/SMTP) with Auto-Discovery and AI-Ready Design I Collected 8.9 Million Polymarket Price Points — Here's What I Found About How Markets Really Move EcoTrack AI — Carbon Footprint Tracker & Dashboard Everyone's Using AI. No One Agrees How. 5 self-hosted ebook managers worth trying in 2026 Building Your First AI Agent with LangChain: From Chatbot to Autonomous Assistant Common SOC 2 Failures (Real World) Stop Vibe-Checking Your AI App: A Practical Guide to Evals How to Use SonarQube and SonarScanner Locally to Level Up Your Code Quality Your Next To-Do App Is Dead — I Replaced Mine with an OpenClaw AI Sign a Nostr event in 60 lines of Python using coincurve — no nostr-sdk, no nbxplorer, no rust toolchain ITGC Audit Explained Like You’re in Big 4 Patch Tuesday abril 2026: Microsoft parcha 163 vulnerabilidades y un zero-day en SharePoint Stop scraping everything: a better way to track competitor price changes Listing on MCPize + the Official MCP Registry while routing payments OUTSIDE the marketplace — how I kept 100% of my x402 revenue Building an AI-Powered Risk Intelligence System Using Serverless Architecture Why We Ripped Function Overloading Out of Our AI Toolchain Testing AI-Generated Code: How to Actually Know If It Works SaaS Churn Is Killing Your Business. Here Is What to Do About It (Without a Support Team) The Speed of AI Is No Longer Linear - And Self-Improving Models Are Why How to Implement RBAC for MCP Tools: A Practical Guide for Engineering Teams From Standard Quote to Persuasive Proposal: AI Automation for Arborists I built a CLI that scaffolds complete multi-tenant SaaS apps Axios CVE-2025–62718: The Silent SSRF Bug That Could Be Hiding in Your Node.js App Right Now The dashboard that ended our friendship Data Pipelines Explained Simply (and How to Build Them with Python) The Hidden Cost of AI Systems Nobody Talks About. undefined vs undeclared, and how typeof behaves Switching from file-based jobs to NATS/Kafka in Rust without changing code io_uring Adventures: Rust Servers That Love Syscalls Why Agentic AI is Killing the Traditional Database The POUR principles of web accessibility for developers and designers Quantum Neural Network 3D — A Deep Dive into Interactive WebGL Visualization How To Install Caveman In Codex On macOS And Windows Automation Pipeline Reliability: Why Your Workflow Breaks When Nobody Is Watching I Built an 'Open World' AI Coding Agent — It Works From ANY Folder From Freelancing to Product: A Tech Service Company's SaaS Transformation China's AI Giants: Adding Tencent Hunyuan & ByteDance Doubao to AI University (74 Providers) On the Vibe Coders and Their Lies clerk: Auto-Summarize Your Claude Code Sessions AI Weekly — 2026/04/10–04/17 | The Model Lockdown Is Here, but the Toolchain Is the Real Battleground AI 週報 — 2026/04/10–2026/04/17 模型封鎖潮來了,但工具鏈才是真戰場 Maybe this is how Open-Source apps are born... 🚀 Fine-Tune LLMs with LoRA and QLoRA: 2026 Guide tRPC v11 + Next.js App Router: End-to-End Type Safety Without the Boilerplate ShadCN UI in 2026: Why I Stopped Installing Component Libraries and Started Owning My Components SaaS Billing in React Server Components: Stripe + Supabase Without a Single `useEffect` Join our DEV Weekend Challenge — $1,000 in Prizes Across TEN winners! Submissions Due April 20 at 6:59 AM UTC. Implementing FSRS Spaced Repetition in Flutter + Supabase — Adding Memory Science to an AI Learning App "I Texted My Localhost From the Train — Claude Code Fixed the Bug Before I Got Home" I Built a Sales Prep AI and It Went Deeper Than Expected Design to Code #2: One JSON, Eleven Outputs Solving the 100M-Row Problem: A Summary Table Pattern for High-Volume Push Notification Logs Flutter Web With Wasm: What Actually Changes For Developers I Built 50 Royalty-Free Soundtracks for My Side Project in a Weekend Using AI Music Generation The Vibe Coding Security Checklist: 7 Things to Check Before You Ship Stop Letting Googlebot Guess Fix Your React App's SEO Right Desconstruindo o Streaming do LinkedIn: Como Criar um Engine de Extração de Vídeo de Alta Performance com HLS e FFmpeg (EDA Part-1) EDA (Exploratory Data Analysis) Explained With Real Life — Why Looking at Your Data Is the Most Important Step in Machine Learning Brand Relationship Management at Scale: Our 4-Touch Outreach System for 200+ Brands Why String.fromEnvironment() Might Return an Empty String in Dart JGuardrails 1.0.0 — Hardening Java LLM Apps Against Jailbreaks, Toxicity, and Prompt Injection Plan and Schedule a Full Week of Threads Content From One Claude Conversation Coding Cat Oran Ep3, Five Tables Changed Everything BFF模式详解:构建前后端协同的中间层 I'm done watching freelancers get buried by 200 proposals. So I'm building the alternative. This is my first post BFS Algorithm in Java Step by Step Tutorial with Examples Tracking LLM Pricing Monthly: An Open Dataset for 22 AI Models How We Measure Content ROI on a Comparison Site: Revenue Attribution Without Perfect Data Introducing Nova AI Ops: The AI-Native Operating System for SRE Teams I built a free desktop video downloader for Windows — Grabbit How Talkie OCR Helps Vision-Impaired & Dyslexic Users Read the World Around Them VRCFaceTracking安装和iPhone面捕配置教程,有bug Even CrowdStrike Can't See Your Agents The Automation Gold Rush: What n8n Workflows and Claude Are Opening Up for Developers Right Now
SOQL Selectivity: Avoiding Full Table Scans on Million-Row Objects
SapotaCorp · 2026-05-24 · via DEV Community

A Salesforce org grew from 50,000 Cases to 5 million Cases over four years. Apex code that processed Cases used to complete in 200ms. The same code now takes 30 seconds when it completes at all; sometimes it times out. The team blames "the platform getting slower." The actual cause is almost always SOQL selectivity. The query no longer hits an index. The platform is scanning the full table.

Selectivity is the single most important performance concern in Apex code touching large objects. The fix is mechanical when caught early and expensive when caught after the data has accumulated. Sapota's Salesforce team treats LDV (large data volume) audits as a recurring engagement type because the failure mode keeps recurring.

What selectivity actually means

A SOQL query is selective when Salesforce can use an index to find the matching records quickly. A query is non-selective when Salesforce has to scan the full table.

Salesforce indexes:

  • All standard fields that are primary keys (Id, Name on standard objects).
  • All foreign key fields (lookups, master-details).
  • Any field marked as External ID.
  • Any field marked as Unique.
  • Custom indexes on specific fields (requested via support; not self-serve).

For an index to be used, the WHERE clause must filter on an indexed field, AND the filter must be selective enough. The selectivity threshold:

  • Standard indexed field: query returns less than 30 percent of total records, OR less than 1 million records (whichever is lower).
  • Custom indexed field: query returns less than 10 percent of total records, OR less than 333,333 records.

Cross these thresholds and Salesforce falls back to a full table scan, regardless of whether the field is technically indexed.

What non-selective queries look like

Patterns that fail at high volume:

// Status = 'Open' might match 40 percent of all Cases. // Non-selective on a 5M-row Case table. SELECT Id, Subject FROM Case WHERE Status = 'Open' // LIKE with leading wildcard cannot use the index. SELECT Id FROM Account WHERE Name LIKE '%Acme%' // NOT operators on indexed fields disable the index. SELECT Id FROM Lead WHERE IsConverted != TRUE // OR across non-indexed fields produces a scan. SELECT Id FROM Opportunity WHERE StageName = 'Closed Won' OR Probability > 90 // No filter at all (yes, this exists in production code). SELECT Id, Amount FROM Opportunity

All of these may run fine in a developer org with 1,000 records. They become incidents when the data grows.

The selective rewrite patterns

The same queries, refactored:

// Add an indexed field to narrow the scope. // CreatedDate is indexed; pair it with Status. SELECT Id, Subject FROM Case WHERE Status = 'Open' AND CreatedDate = LAST_N_DAYS:30 // Use full-text search (SOSL) for substring matching, // or store a normalized prefix in an indexed field. SELECT Id FROM Account WHERE Name LIKE 'Acme%' // Rewrite to avoid NOT on indexed fields. SELECT Id FROM Lead WHERE IsConverted = FALSE // Split the OR into separate queries against indexed fields. List won = [SELECT Id FROM Opportunity WHERE StageName = 'Closed Won']; List highProb = [SELECT Id FROM Opportunity WHERE Probability > 90 AND StageName != 'Closed Lost']; // Always include a date or owner filter on large objects. SELECT Id, Amount FROM Opportunity WHERE CloseDate = THIS_QUARTER

The pattern: narrow the result set with an indexed filter as the primary criterion. Use additional filters to refine within that subset.

How to know if a query is selective

Two diagnostic tools:

Query Plan Tool in Developer Console. Type the query, click "Query Plan." Returns a cost estimate and notes whether the query is selective. A "cost" below 1.0 generally means the query is selective; above 1.0 means the platform will scan more than the threshold.

EXPLAIN-like analysis with sObjectDescribe and indexes. For custom fields, check the field's customIndexed attribute or the field setup screen. Indexed fields show an "Indexed" indicator.

In production, the symptom is timing. A SOQL query that takes more than a few seconds against a single object table is almost always non-selective. The fix starts with identifying the indexed field the query should use.

Skinny tables and external IDs

For very high-volume objects (often 5M+ rows) with frequent reporting queries, Salesforce offers two additional optimizations:

Skinny tables are a feature requested through support. Salesforce creates a read-only copy of an object that contains only the columns you specify. Reports and queries that touch only those columns run against the skinny table, bypassing the full record table. Massive performance improvement for predictable query patterns.

The catch: skinny tables only apply for specific use cases (read-only reporting, specific SOQL patterns). Custom Apex queries must be written to hit the skinny table specifically. Engagement with Salesforce support is required to set them up.

External IDs and unique indexes. Marking a custom field as External ID makes it indexed. Marking it Unique also indexes it. Both are self-serve in Setup. Use these proactively for fields that filter or join in Apex. Adding an External ID to a custom field after the data has grown requires a one-time index build (Salesforce manages this).

When to use Database.query vs static SOQL

Static SOQL (inside square brackets) is checked at compile time and has better tooling support. Dynamic SOQL (Database.query(...)) is needed for queries built at runtime.

For LDV concerns, both produce the same query plan. Selectivity is a property of the query string, not how it was constructed. Prefer static SOQL when the query shape is known; use dynamic SOQL only when the shape genuinely varies.

A common LDV anti-pattern with dynamic SOQL: building queries from user input that produces non-selective filters. The user-typed search hits the unindexed field, the query scans the full table, the page times out. Always validate that user-driven queries use indexed fields with selective filters.

Batch Apex for genuinely large operations

When a single SOQL query truly needs to process millions of records, no amount of selectivity makes it fit in one transaction. The right tool is Batch Apex.

Batch Apex chunks the query into batches of 200 records by default (configurable up to 2,000). Each batch runs in its own transaction with its own governor limits. The framework handles the iteration.

The pattern:

public class CaseAgingBatch implements Database.Batchable { public Database.QueryLocator start(Database.BatchableContext bc) { // Selective by CreatedDate to bound the result. return Database.getQueryLocator( 'SELECT Id, Status FROM Case ' + 'WHERE CreatedDate < LAST_N_DAYS:90 ' + 'AND Status = \'Open\'' ); } public void execute(Database.BatchableContext bc, List scope) { // Process up to 200 cases per batch. } public void finish(Database.BatchableContext bc) {} }

Even Batch Apex requires a selective start query. The framework cannot turn a non-selective query into a fast one; it can only chunk the result.

What good LDV practices look like

A Salesforce org healthy with respect to large data volumes:

  • Every Apex SOQL query against high-volume objects (Case, Task, Opportunity, custom objects above 1M rows) uses an indexed field in the WHERE clause.
  • Date-bounded filters (CreatedDate = LAST_N_DAYS:30) are the default on bulk processing code.
  • External ID fields configured on every custom field used in joins or lookups across Apex.
  • Skinny tables requested for high-volume reporting use cases.
  • Batch Apex used for operations touching more than 50K records.
  • Query Plan tool runs against new SOQL during code review.

Sapota's Salesforce team holds the Platform Developer I credential and runs LDV audits as a defined engagement type. The audit produces a list of non-selective queries, expected impact at the org's projected data growth, and the refactor path for each. Investing in selectivity before data accumulates is dramatically cheaper than after.


Auditing Apex SOQL for selectivity or running an LDV-aware refactor? Sapota's Salesforce team handles performance audits, indexing strategy, and Batch Apex design on production engagements. Get in touch ->

See our full platform services for the stack we cover.