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

    • Issue with Save & Share Link – Works for Others but Not Creator

      I’ve enabled the "Save and Share" feature in Zoho Forms, and it works correctly for all users accessing the public link—except for me (the form creator). Issue Details: When I save and share the link, recipients see a “no permission” error. The form is
    • Save the pdf report from a registration form in a Folder

      Through Zoho Forms I created a registration form with quite a lot of rules to handle different variables (TEAM types, payment in installments, etc.), and the result is pretty good. The automatic PDF that is sent to the respondent upon submission is already
    • zoho forms integration to zoho work drive

      Scenario: A user fills out a Zoho Form, entering details such as email, mobile number, and other required information, and uploads supporting documents like PAN, Aadhaar, etc. Upon submission, the data is available in Zoho Forms Reports. Requirement:
    • Zoho Forms to Zoho CRM Integration failed - can I restart it?

      The integration of Zoho Form to Zoho CRM has failed. Is there a way for me to restart it for the impacted entry?
    • insert an equation, but in document, it shows an image not available.

      I'm new to Zoho writer and used Zoho writer in desktop app version . When I inserted an equation, I got an image not available sign. Any help is appreciated. Thanks, Charles
    • Zoho Desk Android app update - Swipe action customization

      Hello everyone! We have brought in support for the swipe action customization in latest version(v2.9.13) of the Zoho Desk Android app update, enabling you to configure left and right swipe gestures on tickets to carry out the actions swiftly without opening
    • Import KB template OR Export template for zoho desk?

      Greetings. Can you tell me if there is a way to get an EXPORT of my KB articles? OR is there a template you supply for importing KB articles into my zoho desk? I am looking for a method of understanding what fields can be imported, and what their possible
    • XML format to import knowledgebase into Zoho Desk

      Hi, We just started to use Zoho Desk and want to import our knowledgebase from our old support system (Freshdesk) to Zoho Desk. Can anyone give us information about the format of xml file to import? There is no explanation on the related page.
    • Zoho Desk integration with Power BI

      Hi, I want to be able to create a Power BI report which has live updates of ticket data from zoho desk, is this possile at all? Thanks Jack
    • Arranging Ticket Templates

      Is there any way to arrange our ticket templates? It doesn't look very organised when it's just arranged according to when they were created. We want the list to look more organised, by arranging/grouping them by topics, or even just by alphabetical
    • What they mean with "Portal"?

      I just downloaded this app to take my personal notes on digital art studio because it seemed to me the most comfortable app to do it, I use it very often, what do they mean by “no activity on your portal”? I have about 1 year of work here and I don't
    • Inactive User Auto Response

      We use Zoho One, and we have a couple employees that are no longer with us, but people are still attempting to email them. I'd like an autoresponder to let them no the person is no longer here, and how they can reach us going forward. I saw a similar
    • favorites no longer listed

      Hello, I can no longer navigate to my Favorites from the pulldown at the top of my grid view (see attached screenshot). I wasn't able to find it anywhere! Please help me display my Favorites. Thank you!
    • Notecards Disappeared

      Got a new phone. Downloaded and signed in Zoho Notebook. Not finding the Note cards. Just Empty Note books. Frustrating.
    • Table Errors

      Hello, I'm new to Zoho Notebook and using it on several Mac/Apple devices. My question is regarding tables: Why do they become broken, and how to fix the error without retyping all my data? (Please see the screenshot attached.)
    • Online Calculator with Zoho Forms?

      I'd like to build a custom calculator on my website. Zoho Forms seems to offer all the fields for basic calculations performed live without pressing any "Calculate" buttons. Unfortunately, there is still that "Submit" button at the bottom. There is nothing
    • Zoho Tables instead of Zoho Creator Spreadsheet reports <3

      That would make my day for sure. Zoho Creator is create, but miss data entering as AirTable/Spreadsheet can. Seeing Zoho putting effort in this makes me think maybe one day we could see a similar interface for Zoho Creator spreadsheet reports. B.
    • Zoho Sheet - Desktop App or Offline

      Since Zoho Docs is now available as a desktop app and offline, when is a realistic ETA for Sheet to have the same functionality?I am surprised this was not laucned at the same time as Docs.
    • Notebook Stack

      Hi Everyone I Hope you´re fine, I´m sorry if this idea was posted before (I made a search but I haven´t find anything related). So, Having the possibility of stacking notebooks would be an interesting way to order notebooks that correspond to the same
    • Writing on sketch cards is bugged when zoomed in

      When zoomed in, it writes a noticeable distance above or to the side of where you're actually trying to write. The further you're zoomed in, the more noticeable it is. Zooming is also entirely absent on the desktop version.
    • Swipe between notes on iPhone

      It'd be convenient if I could move from one note to the next in a notebook simply by swiping left to right.
    • Sales IQ chat is not working in signed android apk

      I have integrated ZOHO sales IQ support chat and i have followed each step and its working fine in my development build but when i create signed APK for it. Chat does not work in it and showing awaiting for detail. I previously asked the same query but
    • COQL order by COUNT not working

      Dear community, I am trying to get a list of deal amounts per planner working on it and sorted to get see who has the least amount of deals. For some reason, I am unable to use sort by in combination with a COUNT. My original code was: query = "select
    • I want to duplicate a report and name it something else

      Hi, I have created a report, and now want to reproduce it and call it something else. so that I will end up with TWO separate reports with different titles. Please tell me how do I copy / reproduce a report please
    • Zoho CRM: Sales Rep Professional Certification Program on Coursera

      We are happy to share that we have published the Zoho Sales Representative Professional Certificate in partnership with Coursera, a leading platform for online learning and career development that offers access to courses and degrees from leading universities
    • OS X Notebook quits immediately upon launch

      NoteBook for OS X (Sequoia, but also under Sonoma) always quits immediately upon launch (so I cannot use the "Attach user log" option). I've restarted my MacBook but the problem persists. If it helps, attached is a diagnostic report from Library>Log
    • Can External users upload files or images to WorkDrive?

      I want to know if it is possible for someone externally through a link and PW be able to upload files and images onto WorkDrive?
    • Multi-line fields character limits

      Is there a way to set the character limit higher on multi-line fields so that we are not losing information pasted into the field? When the text is entered or pasted, there is no error to say that the text is too large. After saving and going back to view most of the text is gone.   Also, when viewing the resume, the text is not wrapped in the multi line fields and can t be read without scrolling across the page.
    • Taz bot not working — What should I do to resolve this issue?

      I am experiencing issues with the Taz bot in Zoho Cliq—not receiving responses or it does not seem to work as expected. Could you please explain why the Taz bot might not be functioning and what steps I should take to resolve this issue? Thank you!
    • OneNote Migration

      I am trying to migrate two notebooks from OneNote. For five days now I have had no notification that migration has completed and the migration page show 50% complete - one notebook completed one not finished. It just stays like this. I am unable to cancel
    • Set various time slot reminders for task and event

      Hi I would like known if there is possibility to set various time reminders for a task or event like we have the possibility to do in google calendar or google task. For example I'am creating an event or task and I want to be alerted before 30min and
    • Zoho Calendar not functioning---cannot edit, add attendees, etc.

      Hello, My calendar is acting strange. I'm using Chrome as my browser and pop ups are not blocked (the calendar worked fine yesterday). When creating an event, I'm not able to "edit" the event and add attendees, etc. The link is non-responsive. I cannot
    • Unable to send message; Reason:554 5.1.8 Email Outgoing Blocked

      Hi, I sent few emails and got this: Unable to send message; Reason:554 5.1.8 Email Outgoing Blocked And now I have few days since I cant send any email. Is there something wrong I did? Also can someone fix this please
    • Spilt Axis for stacked column and line graph

      Each month around this time I prepare a business review deck. One of the biggest annoyances I have with Zoho, also happens to be something that most other platforms have provided for a long time now, and that is being able to create a chart with stacked
    • Pin a note on top

      Dear Zoho Notebook Team, Please highly consider adding ability to pin a note on top and arrange pinned notes. I have a lot of notes that I want to pin important ones on top and this feature is missing badly. Thank you.
    • Windows 11 app ver 2.2.8

      I have been trialing Zoho Notes syncing between my PC and iphone. No problems with iphone but the Windows 64 bit app ver 2.2.8 was very buggy and would lock up completely, needing a Control Alt Delete etc to close it down. It seemed to be connected to
    • Deluge Script: Onboarding → Access Form

      Hello everyone, Edit: Sorry, I think I put this topic in the wrong section. I’ve recently run into an issue that’s been giving me a bit of a headache for the past few weeks. Context: This is my first time using Deluge to create a script, but it’s not
    • Windows Device Authentication

      We have recently started using ManageEngine, and my boss saw a device management feature in the Zoho One directory. We thought it would either help give us more intergration into Zoho one through bringing ManageEngine services through Zoho one. Or, it
    • How can I change spell check language?

      I cannot find the way to change spell check language. My "display language" is English, and I want to have the same one for Spell Check, but it is Russian!!! How can I change it? In one of your explanations you mentioned that I have to choose it from
    • Mail is so slow - doesn't even work!

      Mail has been getting slower and slower - and today it's not even pulling up emails in either Inbox or Unread. This is beyond frustrating since email is a big part of business. Sent a request through the useless help portal - no response. Called the useless
    • Next Page