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

    Nederlandse Hulpbronnen


      • Recent Topics

      • How to activate RFQ? What if a price list has ladder price for items?

        Where can I find the option to activate request for quotation? How does it work? If the item has ladder price, does it gets calculated depending on how many items are in the cart?
      • Cannot access KB within Help Center

        Im working with my boss to customize our knowledge base, but for some reason I can see the KB tab, and see the KB categories, but I cannot access the articles within the KB. We have been troubleshooting for weeks, and we have all permissions set up, customers
      • Can't join canal Developers Zoho User

        Hello, I received an invitation to join this channel, but I get an error when I try to join it, and I get the same error when I go to the Zoho Cliq interface > Search for a channel. Is this because I don't have a license linked to this email address?
      • Desk Email reply - set default font / use custom font

        Hello, in our e-mails, which we send to our customers, a certain font must be used (Corporate Design): Segoe UI https://en.wikipedia.org/wiki/Segoe#Segoe_UI How can this be included? How can this be set as the default font to ensure that this font is
      • Notes created in mobile can no longer be accessed in desktop

        Working with a 2013 Mac running OS 10.14.6; Desktop Notebook version 4.5.3. Using Motorola Moto G Power 5G - 2024; Android app version 6.7 I have been using Notebook for some years. Starting several weeks ago, the notes newly created ion the phone can
      • PDF Templates - Checkbox Borders

        Is there a way to remove the border of a radio/checkbox on a PDF? I'd like to use the function of checkbox but if there's no easy way to remove the border (the PDF form already has a rectangle so it gets cluttered), then I'm forced to create a single
      • Zoho CRM's custom views are now deployable from sandboxes

        This feature is now available for users in the AU, JP, and CN DCs. New update: This feature is now available for users in CA and SA DCs. Hello everyone, We're excited to announce that you can now deploy custom views from sandboxes to your production environment
      • Generate a link for Zoho Sign we can copy and use in a separate email

        Please consider adding functionality that would all a user to copy a reminder link so that we can include it in a personalized email instead of sending a Zoho reminder. Or, allow us to customize the reminder email. Use Case: We have clients we need to
      • Settings Icon No Longer in ZOHO Desk?

        In ZOHO desk, there has been a gear icon for settings. as of yesterday, it is no longer there. I showed up briefly this morning but is gone again. Anybody else experiecing this?
      • Introducing the all-new email parser!

        Greetings, We are pleased to introduce to you, a brand-new, upgraded version of the Zoho CRM Email Parser, which is packed with fresh features and has been completely redesigned to meet latest customers needs and their business requirements. On that note,
      • Tip #43 - Track, Review, and Analyze Your Assist Sessions with Reports-'Insider Insights'

        Did you know you can generate detailed reports for both remote support sessions and unattended access sessions in Zoho Assist? This makes it easy to monitor technician activity, measure efficiency, and review customer interactions. Let us now take a closer
      • Can we generate APK and IOS app?

        Dears, I want to know the availability to develop the app on zoho and after that .. generate the APK or IOS app  and after that I added them to play store or IOS store.. Is it possible to do this .. I want not to use zoho app or let my customers use it. thanks 
      • Simplified Call Logging

        Our organization would like to start logging calls in our CRM; however, with 13 fields that can't be removed, our team is finding it extremely cumbersome. For our use case, we only need to record that a call happened theirfor would only need the following
      • Sub form doesn't as formula field

        Is it possible to get formula field in sub form in futures?
      • Week date range in pivot table

        Hello, I need to create a report that breakouts the data by week.  I am using the pivot table report, and breaking out the date by week, however the date is displayed as 'Week 1 2014' format.  Is there anyway to get the actual dates in there? ex. 1/6/2014-1/12/2014 Thanks,
      • How do I get Status History data of my Projects?

        I want to build a table in Zoho Analytics that Groups by Date, when Projects entered a certain status. I cannot find Status History or any such useful data available in the Setup of my Data Source sync. Please advise how I can achieve this?
      • Is it possible to hide fields in a Subform?

        Since layout rules cannot be used with Subforms, is there another way, or is it even possible, to hide fields in a subform based on a picklist fields within said subform? For example, if the Service Provided is Internet, then I do not want to see the
      • Single Task Report

        I'd like a report or a way to print to PDF the task detail page. I'd like at least the Task Information section but I'd also like to see the Activity Stream, Status Timeline and Comments. I'd like to export the record and save it as a PDF. I'd like the
      • Weekly Tips :Instantly find what you need with Attachment Viewer

        Your inbox must be packed with project emails, shared notes, and scattered attachments. You are looking for one specific file—a presentation slide or maybe a media clip from a team update—but don’t want to dig through endless email threads or switch between
      • Putting Watermark on Zoho Sheet

        Can this be done?
      • Missing Zoho Desk integration option for form workflows

        According to the help page "Configure Zoho Desk integration in form workflows" we should be able to select Zoho Desk as an integration target but when I open the integrations list then Zoho Desk is not being listed in it. We are on the Premium plan which should already support Zoho Desk integrations.
      • CRM x WorkDrive: File storage for new CRM signups is now powered by WorkDrive

        Availability Editions: All DCs: All Release plan: Released for new signups in all DCs. It will be enabled for existing users in a phased manner in the upcoming months. Help documentation: Documents in Zoho CRM Manage folders in Documents tab Manage files
      • Gantt for 2 or more projects

        Hello, I'm trying the free version of your produtc. It is veryyy good!!!! I don't know if in the Standard plan, I can overview a Gantt Graph for 2 or more Projects Milestone. This would be very helpfull for managing teams and taking decisions about who I will assign a task to. In the paid plan Do I have this possibility? Thank you.
      • Integrating a Zoho Project Gantt Chart into Reports

        Is is possible to integrate a Zoho Project Gantt Chart into a Zoho Report Dashboard. I am in the process of creating Project Status Dashboards for the projects that we track in Zoho Projects and I would like to incorporate the gantt chart within Reports.  Please let me know! Thanks
      • ZOHO BOOKS - EXCESSIVELY SLOW TODAY

        Dear Zoho Books This is not the first time but it seems to be 3 times per week now that the system is extremely slow. I work on Zoho Books 95% of my day so this is very frustrating. Zoho you need to do something about this. I have had my IT guy check
      • Gantt Chart - Zoho Analytics

        Are there any plans to add Gantt Charts capabilities to Zoho Analytics?
      • Displaying related quotes in sales order and back

        Hi, My colleague liked to see to which sales orders, the quote has been converted. Quote shows Invoices, but not SO. Same, they would like to see the quotes in the sales order, as they can see invoices, packages, shipment, How can we achieve this ? Thank
      • Tip of the Week #71–Auto-move incoming messages to the right inboxes with keywords

        We all know that customer-facing teams, especially your sales and support teams, can’t afford to miss even a single customer conversation. But sometimes, sales queries or support requests can easily get lost in a crowded inbox or even end up in the wrong
      • Clearing Fields using MACROS?

        How would I go about clearing a follow-up field date from my deals? Currently I cannot set the new value as an empty box.
      • Migrating a Zoho Forms form into Zoho Creator

        Hi, How can I migrate my Zoho Forms form into Zoho Creator? Thanks. Truly, Emad
      • Is there any way to recall an email sent using Zoho CRM?

        If an email is sent using Zoho Mail, there is a recall option/functionality that is available to the sender. Is there any way to recall an email if it was sent using Zoho CRM? I can't seem to find that option. Any help would be appreciated.
      • Quick Create needs Client Script support

        As per the title. We need client scripts to apply at a Quick Create level. We enforce logic on the form to ensure data quality, automate field values, etc. However, all this is lost when a user attempts a "Quick Create". It is disappointing because, from
      • is it possible to add more than one Whatsapp Phone Number to be integrated to Zoho CRM?

        so I have successfully added one Whatsapp number like this from this User Interface it seems I can't add a new Whatsapp Number. I need to add a new Whatsapp Number so I can control the lead assignment if a chat sent to Whatsapp Phone Number 1 then assign
      • Problem with reports due to "Connected" items change - Yes this IS a problem

        Now that the change has been made to use "connected" items I can no longer run the reporting I need in CRM. I should be able to start with Deals as the parent, connect down to the Account (Account_Name) on the deal as the child, then to any child items
      • Zoho sheet desktop version

        Hi Zoho team Where can I access desktop version of zoho sheets? It is important as web version is slow and requires one to be online all the time to do even basic work. If it is available, please guide me to the same.
      • Introducing notifications in the vendor portal

        Imagine this: You're a recruiter working with multiple vendors on a high-volume hiring project. You’ve just updated a job description after a last-minute change from the hiring manager. One of your vendors, however, is still working off the older version
      • CRM limit reached: only 2 subforms can be created

        we recently stumbled upon a limit of 2 subforms per module. while we found a workaround on this occasion, only 2 subforms can be quite limiting in an enterprise setting. @Ishwarya SG I've read about imminent increase of other components (e.
      • LESS_THAN_MIN_OCCURANCE - code 2945

        Hi I'm trying to post a customer record to creator API and getting this error message. So cryptic. Can someone please help? Thanks Varun
      • How to update "Lead Status" to more than 100 records

        Hello Zoho CRM, How do I update "Lead Status" to more than 100 records at once? To give you a background, these leads were uploaded or Imported at once but the lead status record was incorrectly chosen. So since there was a way to quickly add records in the system no matter how many they are, we are also wondering if there is a quicker way to update these records to the correct "Lead Status". I hope our concern makes sense and that there will be a fix for it. All the best, Jonathan
      • Analytics for notes created

        Is there a way I can see how many notes were created per day? Via reporting or analytics?
      • Next Page