Salesforce Decode
Salesforcedecode
All interview topics

SOQL & Data Modeling Interview Questions

Relationship queries, selectivity, aggregates, SOSL, and designing objects for scale.

120 unique questions in this topicDrill in practice mode →

Concept at a glance

Selective SOQL lets the query optimizer use indexes; good data modeling keeps queries simple at scale.

  • Selective filters & indexes
  • Relationship queries
  • Aggregates & GROUP BY
  • SOSL vs SOQL
SOQL & Data Modeling architecture diagram

Selective SOQL lets the query optimizer use indexes; good data modeling keeps queries simple at scale.

Difficulty Level

Topic Focus

Showing 120 of 120 SOQL & Data Modeling questions

Beginnersoqlrelationship-query

How do you write parent-to-child and child-to-parent relationship queries?

You need Accounts with their Contacts, and Contacts with their Account name, in one query each.

Advancedperformancesoqlselectivity

What makes a SOQL query selective, and why does it matter?

A trigger query on a 4-million-row object throws "Non-selective query against large object type".

Intermediatesoqlaggregategroup-by

What are aggregate queries and their limitations?

Management wants total Opportunity amount per Stage per Owner from Apex.

Beginnersoqlsearchsosl

What is the difference between SOQL and SOSL?

A global search box must find a term across Accounts, Contacts and Cases.

Intermediatesoqlsemi-joinanti-join

How do semi-joins and anti-joins work in SOQL?

Find Accounts that have at least one open Case, and Accounts that have never had an Opportunity.

Intermediatesoqlsharingall-rows

How do you query records the user cannot see, deleted records, or archived activities?

An admin batch needs to include soft-deleted records and archived tasks.

Advancedsoqlflssecure-apex

What does WITH SECURITY_ENFORCED vs WITH USER_MODE do?

A security review flags that an Apex controller returns fields the user has no access to.

Advancedsoqlsecure-apexsoql-injection

How do you prevent SOQL injection in dynamic queries?

Code builds a query with 'WHERE Name LIKE \'%' + searchTerm + '%\'' from user input.

Intermediateperformancesoqlpagination

How do OFFSET and LIMIT work, and how should you paginate large result sets?

A custom list component pages through 120,000 Cases using OFFSET and fails after page 100.

Advancedsoqlpolymorphictypeof

How do you query polymorphic fields like WhatId or OwnerId?

You need Task records with the related record's name, plus Amount when the related record is an Opportunity.

Advancedsoqllockingfor-update

What is FOR UPDATE in SOQL and when should you use it?

Two users clicking "Reserve" at the same time both reserve the last item in stock.

Beginnersoqldate-literals

How do date literals and date functions work in SOQL?

A report-style query needs Opportunities closing this quarter and Cases created in the last 7 days.

Advancedsoqllarge-data-volumebatch-apex

How do you query large data volumes in Apex without hitting the 50,000-row limit?

A nightly job needs to process 3 million Contact records.

Architectdata-modeldesignsubscriptions

Design a data model for a subscription business with plans, add-ons and usage.

A SaaS company wants Salesforce to track customer subscriptions, plan changes, add-ons and monthly usage.

Beginnergovernor-limitssoql

What are the Salesforce governor limits for SOQL every developer should know?

Quick-fire limits round in an interview.

Advancedperformancesoqlquery-plan

What is the Query Plan tool and how do you read it?

A list view on Opportunity takes 20 seconds; you want to know if indexes are used.

Architectdata-modelperformancesharing

What is data skew and how does it affect performance?

A single "Unassigned" Account has 300,000 Contacts and loads fail with lock errors.

Architectdata-modelarchitectureexternal-objects

How do you choose between storing data in Salesforce vs leaving it in an external system?

Order history with 200 million rows lives in an ERP; sales reps want to see it on the Account page.

Advanceddata-modelsalesforce-connectexternal-objects

What are External Objects and how do you query them?

Show shipment records from a logistics OData service on the Order page.

Advancedperformancesoqllwc

How would you optimise a slow query used in a high-traffic LWC?

An Account page component runs a query on 6 million Activity-like custom records and takes 4 seconds.

Beginnerbulkificationgovernor-limitssoql

Why should you never put SOQL inside a loop, and how do you fix it?

Code loops over trigger.new and queries the Account for each Contact.

Intermediateapexsoqldynamic-soql

What is the difference between Database.query, static SOQL and Database.queryWithBinds?

A configurable search component needs to choose fields at runtime.

Intermediatesoqlpickliststolabel

How do you query picklist labels instead of API values?

A French user sees English picklist values in a custom component.

Intermediatesoqljunction-objectrelationship-query

How do you query records related through a junction object?

You need all Job Openings a given Candidate applied to, with the application status.

Beginnersoqlexceptionsdebugging

What causes "List has no rows for assignment to SObject" and how do you avoid it?

Code like Account a = [SELECT Id FROM Account WHERE Name = :n]; fails in production.

Advancedsoqlsharingsecure-apex

How do you enforce sharing for a query in a "without sharing" class?

A utility class is "without sharing" for admin jobs but one method serves a user-facing component.

Intermediatetroubleshootinggovernor-limitssoql

How do you handle "Too many query rows: 50001"?

A trigger that recalculates a total queries all Opportunities of an Account; big Accounts have 80,000.

Beginnersoqlaggregate

What is the difference between COUNT() and COUNT(Id)?

Quick SOQL syntax question.

Advanceddata-modeldesignmaster-detail

How do you design objects to avoid hitting the 2 master-detail limit?

A Work Order object needs to belong to Account, Asset and Contract, all with cascade delete and roll-ups.

Intermediatedata-modelhierarchyuser

What is a hierarchical relationship field?

You need to store a user's mentor, who is also a User.

Advanceddata-modelaccount-hierarchyhierarchy

How do you model a hierarchy of unknown depth, like an account hierarchy?

Global customers have up to 12 levels of subsidiaries and leadership wants totals at the top.

Beginnersoqlschemarecord-types

How do you get the record type Id without a SOQL query?

Code queries RecordType in every trigger execution.

Intermediatesoqlfield-typeslimitations

What field types cannot be used in WHERE clauses or are restricted?

A query filtering on a Long Text Area field fails.

Advancedknowledgesoqlusing-scope

How does the WITH clause for data categories or the USING SCOPE clause work?

You need "My Team's" Opportunities or Knowledge articles in a category from Apex.

Advanceddata-modelreportingdenormalisation

How do you design for reporting when the data model is highly normalised?

The model has six levels of objects, and users cannot build the reports they need because report types allow only four objects.

Beginnerdata-modellookupdelete-behaviour

What is the difference between a lookup "Clear the value" and "Don't allow deletion" option?

Deleting a Product should not leave Order Lines with blank product references.

Architectdata-clouddata-modellarge-data-volume

How would you design an object for event-style data like web clicks?

Marketing wants every website page view stored against Contacts in Salesforce, about 5 million per month.

Intermediatedata-modelheaptext-fields

What is a Text Area field limit and when do you hit heap issues with large text?

An integration stores full JSON payloads (up to 100 KB) in a Long Text Area field and batch jobs run out of heap.

Intermediateintegrationsoqldelta-sync

How do you fetch only records changed since the last sync?

An integration exports all 2 million Accounts every night, though only a few thousand change.

Beginnersoqlorder-by

What does ORDER BY NULLS FIRST / NULLS LAST do?

A list sorted by Close Date shows blank dates at the top.

Beginnerbasicssoql

Explain SOQL to a SQL developer: what works differently?

Opening question in a developer interview.

Beginnerbasicssoqlorder-by

Write a query to get the 10 most recently created Accounts in India.

Live coding question.

Beginnersoqllikewildcards

How does the LIKE operator work in SOQL?

Find Contacts whose last name starts with "Pat".

Beginnersoqlin-operatorbind-variables

What is the IN operator and how is it used with bind variables?

You have a Set of Account Ids from a trigger and need their Contacts.

Beginnerapexsoqlcollections

What is the difference between a Set, List and Map when working with query results?

You need to look up Accounts by Id quickly inside a loop.

Beginnersoqlrelationship-queryowner

How do you query the Name of the record owner?

A report-like query needs Opportunity name and owner name.

Beginnersoqlaggregatehaving

What is the difference between WHERE and HAVING?

Find Accounts with more than 5 open Cases.

Intermediatesoqlschemadynamic-soql

What is a Schema describe and why use it with SOQL?

A generic export tool needs to query all accessible fields of any object.

Beginnerdata-modelrecord-id

What is the difference between Id, 15-character Id and 18-character Id?

An Excel VLOOKUP on exported Ids matches the wrong rows.

Intermediatesoqlcustom-metadatacustom-settings

How do you query a custom setting or custom metadata in Apex?

Code queries a configuration object in every trigger execution and uses up SOQL limits.

Beginnergovernor-limitssoqldml

What is the maximum number of records a single DML statement can process?

Rapid-fire limits question.

Intermediatesoqlgroup-byrollup

What does the GROUP BY ROLLUP clause produce?

A finance summary needs totals per region and per product, plus a grand total.

Intermediatesoqlfields-function

What does the FIELDS() function do and what are its limits?

You want to quickly see all fields on a record while exploring an org.

Advanceddata-modeljunction-objecthistory

How do you design objects for a many-to-many relationship with history?

Track which consultants worked on which projects, with start and end dates and roles, over years.

Beginnerdata-modelself-relationship

What is a self-relationship and when do you use one?

Cases need a "Parent Case" to group related customer issues.

Beginnertroubleshootinggovernor-limitssoql

What does "Too many SOQL queries: 101" mean?

A user saving a single record gets this error.

Beginnerdata-modellookupownership

What is the difference between a lookup to User and the OwnerId field?

A custom "Account Manager" lookup to User is added, but it does not grant access.

Intermediatesoqlaggregateduplicates

How do you find duplicate values in a field using SOQL?

Find Contacts that share the same email address.

Intermediatedata-modelperformanceformula-fields

What are the differences between a Formula field and a stored field for querying?

A frequently used filter on a formula field makes a large list view slow.

Intermediatesoqlfilescontent-document

How do you query Files (ContentDocument) related to a record?

A component needs all files attached to an Opportunity.

Advancedperformancesoqlselectivity

A query that ran in 200 ms now takes 12 seconds after data grew. How do you investigate?

A service console component slowed down as the Case object grew from 500,000 to 8 million records.

Architectdata-modelexperience-cloudperformance

How do you design sharing-efficient data models for large external user bases?

A customer portal will have 2 million customer users, each needing to see only their own orders.

Advancedsoqllwcdesign

How do you query across multiple objects to build a "360 view" without hitting limits?

An Account 360 component shows contacts, open opportunities, recent cases, orders and invoices.

Advanceddata-modeldesignpolymorphic

What is the difference between polymorphic lookups and creating separate lookups per object?

A custom Note object should relate to either an Account, a Case, or a Project.

Architectdata-modelperformancelocking

How do you handle record locking contention on a heavily updated parent record?

Every incoming order line updates a running total on one "Daily Totals" record; concurrent integrations fail with lock errors.

Architectdata-modelperformanceskinny-tables

What is a skinny table and when would you request one?

A report and list views on a 30-million-row Account object are slow despite indexes.

Advanceddata-modelexternal-idmigration

How do you migrate data with complex relationships into Salesforce?

Migrating 5 years of data: Accounts, Contacts, Opportunities, line items and Cases from a legacy CRM.

Intermediatesecuritysoqlfls

Explain the difference between record-level, field-level and object-level filtering in queries.

A junior developer asks why their query returns fewer records for a sales rep than for an admin.

Advancedperformancelwcsearch

How would you implement a typeahead search over 2 million Contacts?

Agents need instant search by name, email or phone in a custom component.

Intermediatedata-modeldependenciesfield-deletion

What happens to queries and data when a field is deleted?

An admin wants to delete an old field that an integration still queries.

Advanceddata-modeltranslationproducts

How do you design a data model for multi-language product content?

Product descriptions must be shown in 6 languages on the customer portal.

Advancedsoqlsemi-joinanti-join

How do you write a query to find Accounts where all Opportunities are closed lost?

Sales ops wants a list of Accounts to re-engage: they had deals, but never won any and have none open.

Beginnerdata-modelobject-settings

What is the impact of the "Allow Reports" and "Allow Search" object settings?

A new custom object does not appear in reports or global search.

Advanceddata-modelperformanceroll-up

How do you calculate a value across a large child set without hitting limits on save?

Each Project has up to 40,000 Time Entries, and Project needs total hours updated on every entry change.

Advancedintegrationsoqlanalytics

How would you expose a read-only reporting dataset to an external BI tool?

The BI team wants to query Salesforce directly every hour for dashboards.

Intermediatedata-modelauditapproval-process

How do you design a data model for approvals history and audit?

Auditors want to see every approval decision with comments for 7 years.

Beginnerdata-modelexternal-idunique

What is the difference between a unique field and an External ID?

An admin wonders whether to mark an Employee Number field as unique, external ID, or both.

Advanceddata-modellarge-data-volumetime-series

How do you handle time-series data such as daily account metrics?

Product wants a daily usage metric per account for 2 years, for 50,000 accounts.

Intermediatesoqlindexes

What are indexes on standard fields that you get for free?

Rapid-fire performance question.

Intermediatedata-modelauditsoft-delete

How would you implement soft delete instead of hard delete?

Legal requires that customer agreements are never physically deleted, but users want to "remove" them.

Advancedsoqlaggregatelimitations

Find the second-highest Opportunity Amount per Account in SOQL — is it possible?

A tricky interview question to test SOQL limits.

Advancedsoqlsharingshare-objects

How do you query records shared with a specific group?

Security asks which Accounts are shared with the "Partners EMEA" group.

Advanceddata-modeldesignconcurrency

Design an object model for event registrations with capacity limits.

Events have limited seats; attendees register online and sometimes cancel.

Intermediatesoqlsales-cloudcontact-roles

How do you query Opportunity Contact Roles and why are they important?

Marketing attribution needs the contacts involved in each deal.

Advanceddata-modelmulti-orgsalesforce-connect

How do you handle a lookup to a record in another Salesforce org?

Two orgs (sales and service) need to reference each other's Accounts.

Intermediateperformancesoqlactivities

Explain how you would query and display the last activity for each Account efficiently.

A list of 500 Accounts must show the date of the latest Task or Event.

Beginnerapexsoqlaggregate

What is an AggregateResult and how do you read it in Apex?

You need total pipeline per owner in Apex.

Advancedsoqlflssecurity-enforced

How does the "WITH SECURITY_ENFORCED" clause behave with relationship fields?

A query including Account.Industry fails for some users with an insufficient access error.

Intermediateintegrationsoqlbulk-api

What are the benefits of the Bulk API 2.0 for queries?

A nightly extract of 20 million records over REST takes hours.

Intermediatedata-modeldesignaddresses

How do you model addresses for customers with multiple locations?

Business customers have billing, shipping and many site addresses; service technicians visit sites.

Beginnerapisoqlquery-all

What is the difference between "Query" and "QueryAll" in the API?

An integration misses deleted records when syncing.

Intermediatedata-modelhierarchyproducts

How would you store and query hierarchical product categories?

An e-commerce catalogue has categories up to 6 levels deep, and products belong to multiple categories.

Beginnersoqlpicklists

How do you query records by a picklist value that has been deactivated?

Old Cases still use a deactivated "Legacy" reason.

Intermediatedata-modelplanningstorage

How do you estimate storage impact before adding a new object?

A new feature will create one record per customer interaction, about 30,000 per day.

Advancedsoqlstatefulbatch-apex

What is the difference between Database.Stateful and querying again in batch Apex finish?

A batch needs to report how many records failed across all chunks.

Beginnersoqlnulls

How do you write a query that returns Contacts without an Account?

Find private Contacts not linked to any Account.

Intermediatesoqlfield-history

How do you query the history of a field change?

Find when each Case's Status changed to Escalated last week.

Intermediatedata-modelaccount-contact-relationship

Explain the Account-Contact Relationship (Contacts to Multiple Accounts).

A consultant works with three client companies and should appear on each.

Intermediatesoqlgeolocation

What is GEOLOCATION and DISTANCE in SOQL?

Find service technicians within 25 miles of a customer.

Architectdata-modelprivacygdpr

How do you design a data model that supports GDPR right-to-be-forgotten requests?

A customer asks the company to delete all their personal data.

Beginnersoqlrelationship-query

Write a query for Contacts with their Account's owner name.

Live coding.

Beginnersoqldate-literals

How do you find Opportunities closing in the next 30 days?

Live coding.

Beginnersoqlbind-variables

How do you query records created today by the current user?

Quick coding question.

Beginnerdata-modellookupformula-fields

What is the difference between a lookup field and a formula referencing a parent?

Show the Account Industry on Opportunity.

Intermediatedata-modeldesign

How do you design an object to store product reviews?

Customers review products on a portal.

Beginnersoqlall-rows

What is the "ALL ROWS" keyword?

Quick question.

Beginnersoqlaggregate

How do you count records per Owner in SOQL?

Live coding.

Intermediatesoqlflssystem-mode

What happens when you query a field the user cannot see in Apex system mode?

A junior expects Apex to hide salary fields automatically.

Intermediatedata-modelapprovals

How do you design a data model for approvals with multiple approvers and comments?

Custom approval needs per-approver decisions.

Beginnersoqlpolymorphictypeof

What is SOQL's TYPEOF used for in one sentence?

Quick question.

Advancedtriggerssoqlselectivity

How do you avoid hitting limits when querying in a trigger on a large object?

A trigger query fails on a 5M-row object.

Beginnerdata-modelpicklists

What is the difference between a Text field and a Picklist for categorisation?

Users type "Hi", "High", "HIGH" in a Priority text field.

Advancedsoqlsubquery

How do you query the newest Case per Account?

Show each Account with its most recent case.

Beginnerdata-modelrecord-types

What is the role of Record Types in data modeling?

Quick data modeling question.

Intermediatesoqldelta-sync

How do you find records changed in the last hour for an integration?

Live coding.

Intermediatesoqlindexes

What is a Custom Index and who can create one?

Quick performance question.

Beginnerdata-modeljunction-object

How do you model many-to-many between Contacts and Events (conferences)?

Track which contacts attended which conferences.

Beginnersoqlaggregateroll-up

What is the difference between COUNT() in SOQL and a roll-up summary?

Count child records for display.

Intermediatedata-modelonboarding

How do you design a model for multi-step onboarding progress?

Each new customer goes through 8 onboarding steps.

Beginnersoqlrelationship-query

How do you query records based on a field in a grandparent object?

Find Cases whose Account's parent is in Germany.