SOQL Query Basics
Master the fundamentals of writing and executing SOQL queries with Salesforce Navigator's Query Tool. Learn basic syntax, autocomplete features, query execution, and common patterns.
Getting Started
The SOQL Query Tool provides a dedicated environment for writing, executing, and managing SOQL queries with intelligent autocomplete and syntax highlighting.
Opening the Query Tool
Method 1: Keyboard Shortcut
Press Ctrl+Shift+Q from any Salesforce pageMethod 2: Navigator Panel
1. Press Ctrl+Shift+M
2. Type "query"
3. Press EnterThe Query Tool opens in a new browser tab with:
- Query editor at the top
- Results panel below
- Command palette at the bottom (press
:)
First Query
Try executing this simple query to get started:
SELECT Id, Name FROM Account LIMIT 5Press Ctrl+Enter to execute.
Query Structure
SOQL (Salesforce Object Query Language) uses a SQL-like syntax optimized for Salesforce data.
Basic Query Anatomy
SELECT Field1, Field2, Field3
FROM ObjectName
WHERE FilterCondition
ORDER BY SortField
LIMIT MaxRecordsComponents:
| Clause | Required | Purpose | Example |
|---|---|---|---|
SELECT | Yes | Fields to retrieve | Id, Name, Email |
FROM | Yes | Object to query | Contact, Account |
WHERE | No | Filter criteria | CreatedDate = TODAY |
ORDER BY | No | Sort results | Name ASC, Amount DESC |
LIMIT | No | Max records | 10, 100, 2000 |
Simple Query Examples
Query all fields for one object:
SELECT Id, Name, Email, Phone
FROM Contact
LIMIT 10Query with filter:
SELECT Id, Name, Type
FROM Account
WHERE Type = 'Customer'Query with sorting:
SELECT Id, Name, Amount, CloseDate
FROM Opportunity
ORDER BY Amount DESC
LIMIT 20Autocomplete Features
The Query Tool provides intelligent autocomplete as you type, making it easy to write correct SOQL without memorizing field names.
SOQL Keywords
Type the first few letters of a keyword to see suggestions:
Type: SEL
Suggests:
├─ SELECT
└─ SELECT COUNT()
Type: WH
Suggests:
├─ WHERE
└─ WHENCommon Keywords:
SELECT,FROM,WHEREORDER BY,GROUP BY,HAVINGLIMIT,OFFSETAND,OR,NOTIN,NOT IN,LIKETODAY,YESTERDAY,THIS_MONTH
Object Names
After typing FROM, autocomplete suggests objects:
SELECT Id, Name
FROM Acc
└─ Suggests: Account, AccountContactRelation, AccountHistoryFeatures:
- All standard objects (Account, Contact, Lead, etc.)
- All custom objects (ending with
__c) - Platform objects (User, Profile, PermissionSet)
- Fuzzy matching (type "opp" → finds "Opportunity")
Field Names
After SELECT or in WHERE clauses, autocomplete suggests fields:
SELECT Na
└─ Suggests: Name, NamePrefix, NameSuffix
SELECT Id, Email
FROM Contact
WHERE Last
└─ Suggests: LastName, LastModifiedDate, LastModifiedByIdContext-Aware:
- Suggestions based on selected object in
FROMclause - Shows field type (Text, Number, Date, Reference)
- Includes custom fields
Relationship Fields
Access related object fields with dot notation:
SELECT Account.Name
└─ Autocomplete after typing "."
Suggests:
├─ Account.Name
├─ Account.Type
├─ Account.Industry
└─ Account.Owner.Name (nested relationship)Parent Relationships:
SELECT Id, Name, Account.Name, Owner.Name
FROM ContactChild Relationships (Subqueries):
SELECT Id, Name,
(SELECT FirstName, LastName FROM Contacts)
FROM AccountUsing Autocomplete
Keyboard Controls:
| Key | Action |
|---|---|
Type | Trigger autocomplete automatically |
↑ / ↓ | Navigate suggestions |
Enter or Tab | Accept suggestion |
Esc | Close autocomplete |
Ctrl+Space | Manually trigger autocomplete |
Workflow:
1. Type "SEL" → SELECT appears
2. Press Tab → "SELECT " inserted
3. Type "Na" → Name, NamePrefix appear
4. Press ↓ to select Name
5. Press Enter → "Name" inserted
6. Type ", Em" → Email appears
7. Press Tab → "Email" insertedAutocomplete Tips
- Wait 300ms for autocomplete to appear
- Type at least 2 characters for best results
- Use Ctrl+Space if autocomplete doesn't trigger
- Fuzzy matching means "accname" finds "AccountName"
Syntax Highlighting
Queries are color-coded for readability:
SELECT Id, Name, CreatedDate
FROM Account
WHERE AnnualRevenue > 1000000
AND Type = 'Customer'
ORDER BY Name
LIMIT 50Color Scheme:
| Element | Color | Example |
|---|---|---|
| Keywords | Blue | SELECT, FROM, WHERE |
| Strings | Green | 'Customer', 'Acme' |
| Numbers | Purple | 1000000, 50 |
| Fields | White | Id, Name, CreatedDate |
| Operators | Orange | =, >, <, AND, OR |
| Functions | Yellow | COUNT(), MAX(), TODAY() |
This visual coding helps you:
- Spot syntax errors quickly
- Distinguish between field names and values
- Understand query structure at a glance
Executing Queries
Run queries to fetch data from Salesforce.
Execution Methods
Method 1: Keyboard Shortcut
Press Ctrl+Enter anywhere in the query editorMethod 2: Execute Button
Click the "Execute" button below the query editorMethod 3: Command Mode
Press : (colon) to open command palette
Type: execute
Press EnterExecution Process
When you execute a query:
- Validation - Query syntax is checked
- API Call - Query sent to Salesforce REST API
- Response - Results returned and displayed
- Metrics - Record count and execution time shown
Visual Feedback:
Executing query... (loading spinner)
↓
50 records found (234ms)
↓
Results displayed in table belowReading Results
Results appear in a table format:
Query: SELECT Id, Name, Email FROM Contact LIMIT 5
Results (5 records, 234ms):
┌─────────────────────┬──────────────┬─────────────────────┐
│ Id │ Name │ Email │
├─────────────────────┼──────────────┼─────────────────────┤
│ 003xx000003DH1QAAW │ John Doe │ john@example.com │
│ 003xx000003DH1RBAW │ Jane Smith │ jane@example.com │
│ 003xx000003DH1RCAW │ Bob Johnson │ bob@example.com │
│ 003xx000003DH1RDAW │ Alice Brown │ alice@example.com │
│ 003xx000003DH1REAW │ Charlie Lee │ charlie@example.com │
└─────────────────────┴──────────────┴─────────────────────┘
Use j/k to navigate rowsResult Metadata:
- Record count - Total records returned
- Execution time - Query performance in milliseconds
- Column headers - Field labels or API names
- Scrollable - Horizontal (many columns) and vertical (many rows)
Understanding Execution Time
Performance Indicators:
| Time | Performance | Typical Cause |
|---|---|---|
| < 200ms | Excellent | Simple query, small dataset |
| 200-500ms | Good | Standard query with filters |
| 500-1000ms | Fair | Complex query or large dataset |
| > 1000ms | Slow | Multiple relationships or aggregations |
Optimization Tips:
- Use
WHEREclauses to filter results - Add
LIMITto reduce records returned - Avoid querying all fields (use specific fields)
- Index fields used in
WHEREclauses - Minimize nested relationship queries
Common SOQL Patterns
Learn these patterns to write effective queries quickly.
Pattern 1: All Records with Limit
Get a sample of records:
SELECT Id, Name
FROM Contact
LIMIT 10When to Use:
- Exploring object structure
- Testing queries
- Quick data checks
Pattern 2: Filtered Records
Query specific records:
SELECT Id, Name, Email
FROM Contact
WHERE LastName = 'Smith'Common Filters:
WHERE Email != null
WHERE CreatedDate = TODAY
WHERE Status = 'Active'
WHERE Amount > 1000Pattern 3: Sorted Results
Order records by field:
SELECT Id, Name, Amount
FROM Opportunity
ORDER BY Amount DESC
LIMIT 10Sorting Options:
ASC- Ascending (A-Z, 0-9, oldest-newest)DESC- Descending (Z-A, 9-0, newest-oldest)- Multiple fields:
ORDER BY Name ASC, CreatedDate DESC
Pattern 4: Related Field Access
Query parent object fields:
SELECT Id, Name, Account.Name, Owner.Name
FROM Contact
WHERE Account.Type = 'Customer'Relationship Depth:
- Up to 5 levels:
Account.Owner.Manager.Name - Mix standard and custom relationships
Pattern 5: Date Filters
Query by date:
SELECT Id, Name, CreatedDate
FROM Account
WHERE CreatedDate = THIS_MONTHDate Literals:
TODAY,YESTERDAY,TOMORROWTHIS_WEEK,LAST_WEEK,NEXT_WEEKTHIS_MONTH,LAST_MONTH,NEXT_MONTHTHIS_YEAR,LAST_YEAR,NEXT_YEARLAST_N_DAYS:30,NEXT_N_MONTHS:3
Pattern 6: Multiple Conditions
Combine filters with AND/OR:
SELECT Id, Name, Email, Phone
FROM Contact
WHERE (Account.Type = 'Customer' OR Account.Type = 'Partner')
AND Email != null
AND CreatedDate > 2025-01-01Logical Operators:
AND- Both conditions must be trueOR- Either condition can be trueNOT- Negates condition- Use parentheses to group conditions
Pattern 7: IN Clause
Match multiple values:
SELECT Id, Name, StageName
FROM Opportunity
WHERE StageName IN ('Prospecting', 'Qualification', 'Closed Won')Variations:
WHERE Id IN ('001xxx', '001yyy', '001zzz')
WHERE OwnerId IN (SELECT Id FROM User WHERE IsActive = true)Pattern 8: NULL Checks
Find records with/without values:
-- Records WITH a value
SELECT Id, Name, Email
FROM Contact
WHERE Email != null
-- Records WITHOUT a value
SELECT Id, Name, Phone
FROM Contact
WHERE Phone = nullPattern 9: LIKE Pattern Matching
Search for partial text matches:
SELECT Id, Name, Email
FROM Contact
WHERE Name LIKE '%John%'Wildcards:
%- Matches any characters_- Matches single character'John%'- Starts with "John"'%Smith'- Ends with "Smith"'%manager%'- Contains "manager"
Pattern 10: Counting Records
Get record counts:
SELECT COUNT()
FROM Account
WHERE Type = 'Customer'Aggregate Functions:
SELECT COUNT(Id), MAX(Amount), AVG(Amount)
FROM Opportunity
WHERE StageName = 'Closed Won'Query Validation
The Query Tool validates syntax before execution.
Common Syntax Errors
Missing FROM clause:
SELECT Id, Name
❌ Missing FROM
Fix:
SELECT Id, Name
FROM AccountInvalid field name:
SELECT Id, Nme FROM Account
❌ Field doesn't exist
Fix:
SELECT Id, Name FROM AccountMissing quotes on strings:
WHERE Name = John
❌ String values need quotes
Fix:
WHERE Name = 'John'Invalid operator:
WHERE Amount => 1000
❌ Not a valid operator
Fix:
WHERE Amount >= 1000Validation Feedback
Errors appear in the quickfix list:
Quickfix List (1 error):
1. Line 2: Unexpected token 'FORM'. Did you mean 'FROM'?Fix Process:
- Error appears with line number
- Press Enter on error to jump to location
- Fix the syntax
- Re-execute query
- Quickfix list clears on success
Query Best Practices
Use Specific Fields
Bad:
SELECT Name FROM Account -- Only gets NameGood:
SELECT Id, Name, Type, Industry, AnnualRevenue
FROM Account -- Gets all needed fieldsAlways Use LIMIT
Bad:
SELECT Id, Name FROM Account -- Returns ALL records (could be millions)Good:
SELECT Id, Name FROM Account LIMIT 100 -- Returns max 100 recordsLIMIT Guidelines:
- Development:
LIMIT 10-50 - Testing:
LIMIT 100-500 - Production:
LIMIT 2000(SOQL max)
Filter Before Sorting
Slow:
SELECT Id, Name FROM Account
ORDER BY Name -- Sorts all records first
WHERE Type = 'Customer' -- Then filtersFast:
SELECT Id, Name FROM Account
WHERE Type = 'Customer' -- Filters first (smaller dataset)
ORDER BY Name -- Then sortsUse Indexed Fields in WHERE
Slower:
WHERE Description LIKE '%keyword%' -- Not indexedFaster:
WHERE Status = 'Active' -- Indexed field
AND Description LIKE '%keyword%'Common Indexed Fields:
Id,Name,OwnerIdCreatedDate,LastModifiedDateRecordTypeId- Custom fields marked as External ID
Next Steps
Now that you understand query basics, explore advanced features:
- Query Results - Navigate and edit results with vim keys
- Variables - Use variables for dynamic queries
- Export - Export results as JSON or CSV
- Common Queries - Real-world query examples
Practice Makes Perfect
Try writing 5-10 simple queries to get comfortable with autocomplete and syntax highlighting. Start with objects you know (Account, Contact) and gradually add WHERE clauses and relationships.