Kaizen 207 - Answering Your Questions | Advanced Queries using COQL API

Kaizen 207 - Answering Your Questions | Advanced Queries using COQL API



Hi everyone, and welcome to another Kaizen week!

As part of Kaizen #200 milestone, many of you shared topics you would like us to cover, and we have been addressing them one by one over the past few weeks. Today, we are picking up one of those requests - a deep dive into advanced queries using Zoho CRM’s COQL APIs.

When you start building complex applications on top of Zoho CRM, you may feel that basic record fetch APIs like GET records are not enough. Business logic often demands far more, like combining data from multiple modules, applying conditional filters, grouping results, or even running aggregate calculations.

This is exactly where COQL (CRM Object Query Language) shines. If you have already used COQL for straightforward queries, this post will help you go further. 

COQL Recap - Why Use It?

COQL is your go-to when you need more than what the standard GET Records API can provide. It gives you:

  • SQL-like flexibility for querying CRM data.
  • Access to related records across multiple modules using lookups and joins.
  • Powerful filtering, aggregation, and sorting well beyond simple searches.

In short: use COQL when you want fine-grained control over results, complex reporting logic, or performance improvements in large data environments.

Understanding COQL Queries

The Query API (COQL) is best when you need flexible record retrieval without chaining multiple API calls or creating custom views.

Instead of building and maintaining complex filters in the UI, you can describe your data needs in one SQL-like query.

For example, with COQL you can:

  • Fetch all products within a certain price range that also have a 5-star rating, sorted by price.
  • Filter deals based on details from a related module, like the Vendor’s status.
  • Pull a precise slice of data on-demand without altering CRM views.

What kind of queries are supported?

COQL currently supports only the SELECT statement, which lets you pick fields, apply conditions, sort results, and control pagination.

A typical query looks like this:

SELECT {field_api_namesFROM {module_api_nameWHERE {field_api_name} {comparator} {valueGROUP BY {field_api_name} ORDER BY {field_api_nameASC/DESC LIMIT {limitOFFSET {offset}

  • FROM - specifies the module to query
  • WHERE - filters records based on conditions

  • GROUP BY - groups records by one or more fields for aggregation
  • ORDER BY - sorts results ascending or descending
  • LIMIT - restricts the number of records returned
  • OFFSET - skips a certain number of records before fetching results

Example:

{

 "select_query" : "select Last_Name, First_Name, Mobile, Final_Score from Leads where Lead_Status 'Not Contacted' order by Final_Score desc limit 5 offset 10"

}


The above query retrieves five Leads who have not been contacted, ordered by Final_Score, skipping the first 10(OFFSET). You can also use the shorthand LIMIT offset, limit:

{

 "select_query" : "select Last_Name, First_Name, Mobile, Final_Score from Leads where Lead_Status = 'Not Contacted' order by Final_Score desc limit 10, 5"

}


Supported Data Types & Operators

COQL supports multiple field types, each with dedicated operators:

Field Type

Supported Operators

Text, Picklist, Email, Phone, Website, Autonumber 

=, !=, like, not like, in, not in, is null, is not null

Lookup

=, !=, in, not in, is null, is not null

Date, DateTime, Number, Currency

=, !=, >=, >, <=, <, between, not between, in, not in, is null, is not null

Boolean

=

Formula

If the return type is:

  1. Decimal/Currency/Date/Datetime: =, !=, >=, >, <=, <, between, not between, in, not in, is null, is not null
  2. String: =, !=, like, not like, in, not in, is null, is not null
  3.  Boolean: =


Queries can be further refined with sorting (ORDER BY) and pagination using LIMIT and OFFSET.

Aggregate functions

COQL supports aggregate functions to summarize data:

  • SUM(field) – total of numeric values
  • MAX(field) – largest value
  • MIN(field) – smallest value
  • AVG(field) – average value
  • COUNT(*) – number of records matching criteria 


Please note that aggregate functions are supported only for numeric data types such as number, decimal, currency, etc.

Wildcards

The % character is supported with the LIKE operator for flexible text matching:

  • '%tech' → values ending with “tech”
  • 'C%' → values starting with “C”
  • '%tech%' → values containing “tech”


With these building blocks, you can already express a wide range of queries. Let’s now move into advanced scenarios where COQL really shines.

Beyond basics: COQL Patterns for real-world scenarios

Once you are comfortable with the basics of COQL, you can start combining them into more powerful query patterns. Some of these go beyond simple filtering and field selection, helping you minimize API calls, handle relationships, and emulate unsupported features.

1. Advanced Filtering & Conditions

Beyond equality, COQL supports operators like LIKEINBETWEEN, and date comparisons.

Example: Fetch Leads from the IT or Finance industry created in the year 2025.

{

 "select_query": "select Full_Name, Industry from Leads where Industry in ('IT', 'Finance') and Created_Time between '2025-01-01T00:00:00+05:30' and '2025-12-31T23:59:59+05:30'"

}


Use case: Run targeted campaigns or segment leads for analysis without multiple API calls.

2. Combining Multiple Conditions

You can query diverse conditions, combining exact, partial matches, and set memberships.

Example: Pre-qualified leads in target industries with company names containing “zylker”:

{

 "select_query": "select First_Name, Last_Name from Leads where (((Lead_Status = 'Pre-Qualified') and (Company like '%zylker%')) and Industry in ('Technology', 'Government/Military'))"

}



Use case: Sophisticated audience segmentation or analytics for campaigns.

3. Fetching related records and their fields using Joins (Dot notation)

COQL allows you to retrieve related records efficiently by navigating lookup relationships using dot notation. This makes it possible to pull in contextual information across modules without chaining multiple API calls.

Single-level join: Fetch contacts and their account names, excluding a specific account:

{

 "select_query": "select Last_Name, First_Name, Account_Name.Account_Name, Owner from Contacts where (Account_Name.Account_Name != 'Zylker') limit 2"

}


Sample use case: Retrieve all contacts along with their associated account names while excluding certain accounts (e.g., competitors or internal test accounts). This avoids multiple queries across modules and helps in cleaner campaign targeting.

Hierarchical / nested join: Fetch contacts whose accounts have a parent account named “Kings”:

{

 "select_query": "select Account_Name, Account_Name.Parent_Account.Account_Name from Contacts where Account_Name.Parent_Account.Account_Name = 'Kings' limit 5"

}


Sample use case: Easily retrieve multi-level relationships such as parent-child accounts for reporting, territory alignment, or hierarchical sales analysis.

Multi-Level Join with Extended Lookup : Fetch contacts, their accounts, the parent accounts of those accounts, and the owner of the parent account:

{

 "select_query": "select Last_Name, First_Name, Account_Name.Account_Name, Account_Name.Parent_Account, Account_Name.Parent_Account.Owner AS 'Parent Account Owner', Owner from Contacts where (Account_Name.Account_Name != 'Zylker') limit 2"

}


Sample use case: Useful in complex account management and escalation scenarios where responsibility spans multiple levels. For instance, sales managers may want to see not just the contact and their account, but also which parent account owner is responsible for the overall relationship. These types of queries are helpful in large enterprises with layered ownership structures.

4. Using Subqueries to detect missing relationships

COQL supports subqueries to filter based on related module data or detect missing relationships.

Example: Find contacts whose accounts have no closed deals:

{

 "select_query": "select Full_Name, Email from Contacts where Account_Name not in (select Account_Name from Deals where Stage = 'Closed Won')"

}


Use case: Identify potential follow-ups, audit compliance, or uncover opportunities.

These types of queries are handy for:

  • Sales follow-ups – identify contacts from accounts that haven’t yet converted.
  • Compliance checks – ensure certain accounts meet deal requirements.
  • Pipeline building – target untouched accounts for new opportunities.

By combining subqueries with conditions like NOT IN, COQL makes it easy to surface hidden opportunities that would otherwise require multiple API calls and custom logic.

NoteSubqueries in COQL can return a maximum of 100 records. If the inner query has more than 100 matches, any extra records are ignored. This means you may get incomplete results in larger datasets. In such cases, it is better to redesign the query using joins or multiple API calls, which can handle broader datasets without this limit.

Advanced COQL Querying: Real-World Patterns

Once you’ve mastered filters, joins, and subqueries, you can combine them for advanced business logic. 

1. Filtering Deals Based on Account Attributes

Generic Use Case:
You want to prioritize deals connected to high-value accounts that meet specific business criteria, such as strong credit ratings or key industries.

Retrieve all deals for accounts that:

  • Have a high credit rating (>750)
  • Belong to a specific industry, e.g., Communications

COQL Query:

{

 "select_query": "SELECT Deal_Name, Amount, Account_Name, Contact_Name.Email FROM Deals WHERE Account_Name in (SELECT id FROM Accounts WHERE Credit_Rating > 750 AND Industry = 'Communications') AND Stage != 'Closed Won'"

}


Dynamically filter deals by account attributes while fetching related contact details in a single query.

2. Emulating MIN/MAX for Date fields

When working with date fields in COQL, a common analytical need is to compare records against the latest date from a related subset. For example, identifying deals that closed before the most recent high-value deal.

Intuitively, one might try to use aggregate functions like MAX() on a date field in a subquery, such as:

{

 "select_query": "SELECT Deal_Name FROM Deals WHERE Closing_Date < (SELECT MAX(Closing_Date) FROM Deals WHERE Amount > 500000)"

}

Warning
However, COQL currently does not support aggregate functions like MAX() or MIN() on Date or DateTime fields. Attempting this will result in errors or unexpected behavior, as COQL aggregates are primarily designed for numeric fields.

Workaround: Using Subquery with ORDER BY and LIMIT

Instead of MAX(), the recommended COQL approach leverages sorting and limiting the result set to a single latest date within a subquery:

{

 "select_query": "select Deal_Name from Deals where Closing_Date < (select Closing_Date from Deals where Amount > 500000 order by Closing_Date desc limit 1)"

}


How this works:

The inner subquery fetches the single most recent Closing_Date where deals exceed $500,000, ordering by date descending and limiting to one record. The outer query then retrieves all deals closed before that date.

This pattern mimics the MAX() date comparison in a manner supported by COQL’s current capabilities. You can apply the same approach with ascending sort order to emulate MIN() as well.

3. Combining Multiple Subqueries for Complex Business Logic

Real-world CRM scenarios often require filtering records based on multiple interconnected conditions across different modules. Consider this sales intelligence use case: you want to identify Contacts who are:

  • Associated with Accounts that have annual revenue greater than $1000000000000
  • Connected to Deals that were created in the previous quarter    

{

 "select_query": "SELECT First_Name, Last_Name, Email, Account_Name.Account_Name FROM Contacts WHERE Account_Name in (SELECT Account_Name FROM Deals WHERE Created_Time >= '2025-06-01' AND Account_Name in (SELECT id FROM Accounts WHERE Annual_Revenue > 1000000000000)) "

}


Query Breakdown:

  • Innermost subquery: (SELECT id FROM Accounts WHERE Annual_Revenue > 1000000000000) identifies high-revenue accounts
  • Middle subquery: (SELECT Account_Name FROM Deals WHERE Created_Time >= '2022-07-02T15:18:31+05:30' AND Account_Name in (...)) filters for accounts with deals created after the specified date that are also high-revenue accounts
  • Main query: Retrieves contact details for all contacts associated with these filtered accounts while fetching the related account names via JOIN


This pattern finds contacts from high-value accounts that have had recent deal activity, combining temporal filtering with revenue-based account qualification in a single efficient query.

Dynamic Account and Deal Performance Analysis

Imagine you need to find all Leads from industries where accounts have historically closed high-value deals (over $100K) and those leads have "Hot" ratings.

This requires filtering leads based on:

  • Industry performance from accounts with successful deals
  • Lead rating criteria
  • Retrieving lead details with industry information


{

 "select_query": "SELECT First_Name, Last_Name, Lead_Source, Company, Industry FROM Leads WHERE Industry in (SELECT Industry FROM Accounts WHERE id in (SELECT Account_Name FROM Deals WHERE Amount > 100000 AND Stage = 'Closed Won') GROUP BY Industry) AND Rating = 'Hot'"

}


What makes this powerful:

  • Inner subquery (SELECT Account_Name FROM Deals WHERE Amount > 100000 AND Stage = 'Closed Won') identifies accounts with successful high-value deals
  • Outer subquery (SELECT Industry FROM Accounts WHERE id in (...) GROUP BY Industry) gets the industries of those successful accounts
  • Groups by Industry to get unique industry values and avoid duplicates
  • Main query finds leads in those proven successful industries with "Hot" ratings.

    Note: Both subqueries in this query are limited to 100 records each. If either the Deals or Accounts module returns more than 100 matches, the additional records are silently ignored. This can lead to incomplete results when working with larger datasets. For scenarios where the inner queries are expected to return more than 100 records, redesign the query using joins or break it down into multiple API calls for complete coverage.


Conclusion

By going beyond simple record fetches, COQL gives you the power to do true analytics and querying. By mastering patterns that range from straightforward joins to complex multi-module subqueries, you can consolidate multiple API calls into a single query, reduce complexity, and streamline performance. At the same time, dynamic filtering across modules facilitates richer business logic, while relationship-aware queries let you build automations that can handle real-world exceptions with precision.

As you implement these patterns, remember that the most powerful COQL queries often combine multiple techniques: JOINs for data enrichment, subqueries for dynamic filtering, and careful aggregation for performance optimization. However, it is equally important to understand COQL's limitations too. Being aware of these limitations will help you design effective workarounds and choose the right approach for your specific use cases. For a comprehensive list of limitations, please refer to our COQL Limitations documentation.

Start with simpler patterns and gradually build complexity as your use cases demand. The investment in mastering COQL will pay you with cleaner code base, better performance, lesser credit consumption, and more sophisticated CRM functionality.

We hope that you found this post on COQL useful. If you have any queries or need further assistance, please feel free to comment below or email us at support@zohocrm.com. We are here to help!




      • Sticky Posts

      • Kaizen #197: Frequently Asked Questions on GraphQL APIs

        🎊 Nearing 200th Kaizen Post – We want to hear from you! Do you have any questions, suggestions, or topics you would like us to cover in future posts? Your insights and suggestions help us shape future content and make this series better for everyone.
      • Kaizen #198: Using Client Script for Custom Validation in Blueprint

        Nearing 200th Kaizen Post – 1 More to the Big Two-Oh-Oh! Do you have any questions, suggestions, or topics you would like us to cover in future posts? Your insights and suggestions help us shape future content and make this series better for everyone.
      • Celebrating 200 posts of Kaizen! Share your ideas for the milestone post

        Hello Developers, We launched the Kaizen series in 2019 to share helpful content to support your Zoho CRM development journey. Staying true to its spirit—Kaizen Series: Continuous Improvement for Developer Experience—we've shared everything from FAQs
      • Kaizen #193: Creating different fields in Zoho CRM through API

        🎊 Nearing 200th Kaizen Post – We want to hear from you! Do you have any questions, suggestions, or topics you would like us to cover in future posts? Your insights and suggestions help us shape future content and make this series better for everyone.
      • Client Script | Update - Introducing Commands in Client Script!

        Have you ever wished you could trigger Client Script from contexts other than just the supported pages and events? Have you ever wanted to leverage the advantage of Client Script at your finger tip? Discover the power of Client Script - Commands! Commands

        • Recent Topics

        • Marketing Automation List Entry Criteria is no longer an option

          For a couple of years now we have used the "List Entry Criteria" option to filter our Journey recipient list. All of a suddent the option no longer exists for New Lists and I can only delete the option from existing lists but can no longer edit it. Anyone
        • GCLID arrives not in CRM with iframe integrated ZOHO Form

          Hello amazing community, I enabled Adwords integration in ZOHO CRM. I have a ZOHO Form integrated in a wordpress. I tested iframe and Javascript. I enabled the "handover" GCLID in the ZOHO Form. When I add a GLID with http://www.example.com/?gclid=TeSter-123.
        • How to overcome Zoho Deluge's time limit?

          I have built a function according to the following scheme: pages = {1,2,3,4,5,6,7,8,9,10}; for each page in pages { entriesPerPage = zoho.crm.getRecords("Accounts",page,200); for each entry in entriesPerPage { … } } Unfortunately, we have too many entries
        • Add Webhook Response Module to Zoho Flow

          Hi Zoho Flow Team, We’d like to request a Webhook Response capability for Zoho Flow that can return a dynamic, computed reply to the original webhook caller after / during the flow runs. What exists today Zoho Flow’s webhook trigger can send custom acknowledgements
        • Bidirectional sync between Zoho Bookings and Zoho CRM - Part 1

          Hey, community members! The default integration between Zoho CRM and Zoho Bookings is unidirectional, which means that any appointments booked, rescheduled, or deleted in Zoho Bookings will be reflected in Zoho CRM. However, any modifications made to
        • Is it possible to edit placeholder text?

          In the master slides I want to make sure my templates have more meaning for the users and want to replace the standard placeholder text with something more instructional. Instead of "Click to edit Mast subtitle styles" I want to have "Click to enter reporting
        • Delay function execute

          I've got a workflow which uses a webhook to send information to Flow, which in return updates a record in Creator. Problem is, by the time this has executed, the rest of my script has run and can't find the (yet to be) updated info in the record. Is there
        • How to allow download of a file AFTER information is collected?

          I can't find this anywhere. Can someone help with what seems to be a pretty basic web function today? - File is stored in Workdrive - Prospect goes to a URL where the file is located - System requests prospect to enter "Name" and "Email" - An email is
        • Add Baseline methods to API

          There are no API methods for creating or querying baselines,  Use case: Customer is notified of the current project start date according to plan via another product/integration. We would like to auto create a baseline (Automated via API) at the point
        • Bulk Fill In & Edit PO/Bill/SO/Invoice

          Hello, I am adding stock in bulk on a PO, the system is automatically populating the Rate (price) and Tax from the item data. Problem is that the bill rate is different from the rate on the item data, so I have to manually erase each and enter the price.
        • Fixed Assets beg balance

          Hello, I trust you are well I'm a new zoho books user and I find it difficult to plug in the fixed assets balance and here's what I have done: 1- I imported the fixed assets data into the fixed assets module as per the instructions 2- the import process
        • Syncing with Google calendar, Tasks and Events

          Is it possible to sync Zoho CRM calendar, task and events with Google Calendar's tasks and events. With the increasing adoption by many major tool suppliers to sync seamlessly with Google's offerings (for instance I use the excellent Any.do task planning
        • CRM Deluge how can link attach file with workdrive file.

          Hi, We have create file at workdrive and would like to link to attachment at crm module by deluge. Right now can only upload it to attachment but can not link the file from workdrive. Thank you
        • Feature announcement: AI-powered document generator in Zoho Sign

          Hi there! We recently announced manual document creation by offering an editor within Zoho Sign. Today, we are excited to announce AI-powered document generation to help you draft agreements, purchase orders, and other important business documents in
        • Permanently deleted files

          Is there a way to get back permanently deleted files from your account if they were accidentally deleted and no longer recoverable from the recycling bin? I know I am probably screwed but I just figured I would ask.
        • Shared Mailbox in iOS app

          Hi, On the desktop I am using a Shared mailbox for our company's general mailbox that somebody else should be able to view. In the iOS app however I can't find it? Old sources on the internet says this isn't possible but that can't be right? Somebody
        • Tip #41- Simplify Compliance and Efficiency with Zoho Assist’s Data Cleanup Feature- 'Insider Insights'

          Managing device data efficiently is just as important as securing remote access. With Zoho Assist’s Data Cleanup feature, admins can easily remove outdated or unnecessary device records, keeping the console organized and secure. This action is carried
        • Revenue Management: #6 Revenue Recognition in Professional Services Industry

          If you run a consulting firm, agency, or any service-based business, you have a situation where you have signed the contract, maybe even sent the invoice, and have received some initial payments. So, can you consider this as revenue? What if the project
        • Zoho fsm scheduled maintenance dispatch

          Hi, I'm reaching out regarding an issue I'm encountering with the Scheduled Maintenance feature in Zoho FSM. I’m trying to configure it so that it automatically dispatches all maintenance jobs scheduled within the next 150 days, starting from today. However,
        • Template modifiactions

          Hello, I am struggling with the templates in ZOHO Books. Especially with the placement of some items, like company address, ship to, bill to etc.  For example: One item I like from template X (placement of ship to and bill to next to each other in the
        • zoho.inventory.getRecords returns no records

          I running a custom function (Deluge) in Zoho Flow with a connection to Zoho Inventory. To debug the problem, I created the test function below. It returns "Number of contacts fetched: 0". This confirms that there's no issue with the org ID or connection
        • Zoho Campaigns Event timestamps do not propagate to Zoho CRM

          We have integrated Zoho CRM and Zoho Campaigns. But when looking at Contact records, the Campaign event data is missing the actual timestamps: especially when a particular email was sent. They're not in the Campaigns related list, and the cannot be found
        • Feature announcement - Simplifying document creation with Zoho Sign

          Hi there, We are pleased to announce the release of our document creation feature, enabling you to create, edit, and finalize documents like agreements, purchase orders, and contracts without relying on external tools or applications. &lt;br&gt; This
        • Integrating File Attachments in Zoho Flow Email Notifications

          Hi, I would like to be able to send an email once an entry is made in a form, and in this email, I would like to attach a file that has been added to the form using the ImageUpload (or FileUpload) widget. So, I started by creating a flow that will trigger
        • Zoho Mail SMTP IP addresses

          We are using Zoho Mail and needs to whitelist IP for some redirections from your service to another e-mails. You can provide IP address list for Zohomail SMTP servers?
        • Zoho project purchases

          Hi Folks, I think having a purchase module in projects will help in putting together a project p and L. Project wise purchases and expenses.  Do let me know your thoughts.
        • Create Tasklist with Tasklist Template using API v3

          In the old API, we could mention the parameter 'task_template_id' when creating a tasklist via API to apply a tasklist template: https://www.zoho.com/projects/help/rest-api/tasklists-api.html#create-tasklist In API v3 there does not seem to be a way to
        • How can I restore all the deleted Time entries of a Task in Zoho Projects

          How can I restore all the deleted Time entries of a Task in Zoho Projects? Query: In Zoho Projects, I cloned a task and deleted the time entries from the cloned task. However, this also deleted the time entries from the original task. How can I restore
        • Is there a way to make an account inactive in ZoHo Desk

          We have a few Clients "Accounts" that we no longer do business with. It would be beneficial for them to not show up in lists. However, we want to go back and view tickets, time, etc.
        • How to set the value of the Phone field importing contacts in Zoho Desk

          Hi everyone, i'm new in Zoho Desk, we're setting up the environment and i'm importing contacts from another CRM using a file CSV and i'm getting a problem with phone numbers (italian): the leading zero is cut away, also if the value is inside double quotes.
        • Set Custom Icon for Custom Modules in new Zoho CRM UI

        • Deprecation Notice: OpenAI Assistants API will be shut down on August 26, 2026

          I recieved this email from openAI what does it means for us that are using the integration and what should we do? Earlier this year, we shared our plan to deprecate the Assistants API once the Responses API reached feature parity. With the launch of Conversations,
        • How to center a field inside a section?

          I’ve been trying to center a field inside a section in Zoho Canvas. When I align it visually, it looks centered in the editor, but after clicking Save, the field appears misaligned on the actual canvas. I also tried setting the field to full width, but
        • Kaizen #192 - Implementing Custom Token Persistence in Python SDK

          Welcome back to another week of Kaizen! Last week, we discussed how to implement Login with Zoho using OAuth 2.0 and saw how to bring it to life in a real-world application with the Zoho CRM Python SDK. We also discussed how Zylker Academy built a custom
        • Showing the map along with mileage expense

          When you use the GPS to track mileage, it shows you the map of the actual path travelled. It would be very useful and practical to save that map with the mileage expense, so that when the report is created, it provides a map of each mileage expense associated
        • Enable Validation Rule for Multi-Select Picklist Field

          Zoho, Please allow validation rules for multi-select fields.
        • File Upload field not showing in workflow

          Hi, I have added a field on Zoho CRM. I want to use it in a workflow where that particular field is updated based on another field, however it is not showing up in the field list to select it in the workflow. Why is this please?
        • CRM Custom function updating a module record shows the Super Admin user as the record modifier

          Dear Zoho CRM Team, Is there any way to update this so that when a custom function has updated a record the Super Admin user doesn't become the modifier? This happens on the record as a modifier and shows up in the audit logs. It would be more useful
        • Best practice importing items and matching assemblies

          Hi, I was wondering what would be the best practice to import items and composite items (assemblies) From my backup, what should I import first? The items or the composite items? I am on Zoho one, using inventory and books. Kind regards, Sabine
        • Best way to fetch employee names from Zoho People into Zoho Creator Inventory Stock Form field Employee Name Lookup

          Hi Team, I have a requirement in my Zoho Creator application (Inventory Stock Adjustment) where I need to fetch employee names from Zoho People and use them as a lookup in a form. Currently, I am considering using an integration field to fetch this data
        • Next Page