COQL API in Zoho CRM - Part I

COQL API in Zoho CRM - Part I

Hi everyone! Welcome back to another week of Kaizen

This week, we will discuss the COQL Queries in detail.

COQL (CRM Object Query Language) is a powerful query language based on SQL syntax that allows users to write their own queries and fetch records using module API names and field API names. In this post, we will discuss the operators supported by COQL in detail and also provide examples to help you understand better.  Please note that the information in the article holds true for version 4 of Zoho CRM APIs.

When should you use the Query API?

Use Query API when you want to query for a module's data and/or it's look up related data using various comparators, or for records that fall into a custom view without actually creating one. For example, if you want to query for all products in a specific price range, with a 5 star rating and sort the results by price, use the Query API. Similarly you can use Query API to query for records from cross-modules (linked via lookup field), such as filtering products based on the vendor's details. 

What types of queries are supported by COQL?

COQL supports only the SELECT query, which is used to select data from the CRM, based on the conditions specified by the clauses. 

Here is a sample query:
SELECT {field_api_names} FROM {module_api_name} WHERE {field_api_name} {comparator} {logical_operator} {value} ORDER BY {field_api_name} ASC/DESC LIMIT {limit} OFFSET {offset}

What are the clauses & aggregate functions supported by COQL?

WHERE - used to select records based on specific conditions.
FROM - specifies the module from which to fetch the records.
ORDER BY - used to sort the results in ascending or descending order.
LIMIT - used to limit the number of records returned by the query.
OFFSET - used to skip a specified number of records while retrieving the records.


{
 "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"
}


For example, the above query retrieves the Last_Name, First_Name, Mobile and Final_score of all Leads whose status equals 'Not Contacted'. The results will be sorted in descending order based on the Final_Score field, and only the 5 records after skipping the first 10 will be returned.

NOTE : You can also use the syntax "LIMIT offset, limit" to achieve the same result. For 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, 10"
}


Aggregate functions can perform calculations on a set of values and return a single value. 
SUM() - to get the sum of the values of an aggregate field in a module.
MAX() - to get the maximum value of an aggregate field.
MIN() - to get the minimum value of an aggregate field.
AVG() - to get the average value of the values of a field.
COUNT() - to get the number of records that satisfy the criteria.

Wildcard Character Support in COQL

In COQL queries, the only supported wildcard character is %. This % wildcard can be used with the like operator to achieve functionality similar to the contains, starts_with and ends_with operators. For instance, '%tech" queries for field values ending with tech, 'C%' queries for the values starting with C, and '%tech%' translates to contains 'tech'.

Supported field types and Comparators

The following table gives a gist of the field types whose data you can query for, and the comparators for each field type.
Field TypeComparators
Text and Picklist=, !=, 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=

Supported field types and Comparators

1) Text and Picklist Fields

Supported comparators : =, !=, like, not like, in, not in, is null, is not null. Please note that the like operator is used for starts_with, ends_with, contains, and not like operator is used for not contains

Sample Query 1: (=, like, in)

{
    "select_query": "SELECT First_Name, Last_Name FROM Leads WHERE (((Lead_Status = 'Pre-Qualified') and (Company like '%zylker%')) and Industry in ('Technology', 'ERP'))"
}

This SELECT query retrieves the First_Name and Last_Name of all Leads whose Lead_Status is Pre-QualifiedCompany contains zylker, and Industry is either Technology or ERP

Sample Query 2:(not in, like, not null)

{
"select_query": "SELECT First_Name, Last_Name FROM Leads WHERE (((Lead_Status not in ('Closed-Won', 'Closed-Lost')) and (Lead_Source like '%Web%')) and (Skype_ID is not null)) LIMIT 2"
}

This query will return the first name and last name of all leads whose lead status is not Closed-Won or Closed-Lost, whose Lead Source fields contains web, and whose Skype ID field is not empty.

Sample Query 3:( !=, not like, null)

{
    "select_query": "SELECT First_Name, Last_Name, Mobile FROM Leads WHERE (((Lead_Source != 'Webinar') and (City not like '%New York%')) and (Skype_ID is null))"
}

This query retrieves the first name, last name and mobile of leads where the lead source is not a webinar, the city is not New York, and the Skype ID field is empty or null.

2. Lookup Fields

=, !=, in, not in, is null, is not null are the supported comparators for lookup fields. If you want to get the name of the lookup field in the response, you must include the field API name in the query. Otherwise, the system will return only the ID of the field.

Sample Query 1: (=, not in, !=)

{
 "select_query": "select Last_Name, First_Name, Full_Name, Account_Name, Owner from Contacts where (((Account_Name.Account_Name != 'Zylker') and (Owner = 4876876000000327001)) and Vendor_Name.Vendor_Name not in ('Skytech','SR')) LIMIT 2"
}

This query retrieves the last name, first name, full name, account name, and owner of two contacts whose account name is not Zylker, whose owner ID is 4876876000000327001, and whose vendor name does not contain Skytech or SR.
Sample Response:
{
    "data": [
        {
            "First_Name": "John",
            "Full_Name": "John Wilson  ",
            "Owner": {
                "id": "4876876000000327001"
            },
            "Last_Name": "Wilson  ",
            "Account_Name": {
                "id": "4876876000000333089"
            },
            "id": "4876876000000333182"
        },
        {
            "First_Name": "Josephine",
            "Full_Name": "Josephine Darakjy",
            "Owner": {
                "id": "4876876000000327001"
            },
            "Last_Name": "Darakjy",
            "Account_Name": {
                "id": "4876876000000333090"
            },
            "id": "4876876000000333183"
        }
    ],
    "info": {
        "count": 2,
        "more_records": true
    }
}

In this query, the id of the account is returned but not the name since we have not specified the field API name in the query. To fetch the field name, specify the field API name in the query. Refer to the following sample query to know how.

Sample Query 2:  (in, is null, is not null)

{
    "select_query": "SELECT Deal_Name, Account_Name.Account_Name, Created_Time FROM Deals WHERE (((Account_Name.Account_Name in ('Grayson','Zylker')) and (Owner is not null)) and (Contact_Name is null)) ORDER BY Created_Time DESC LIMIT 2"
}

This query retrieves the Deal Name, Account Name, and Created Time of the 2 most recently created Deals whose Account Name contains Zylker or Grayson, and do not have a Contact Name associated with them but have a Deal Owner associated with them. The results will be ordered in descending order by the Created Time.
 
Sample Response:
{
    "data": [
        {
            "Deal_Name": "Westborne Deal",
            "Created_Time": "2023-04-06T10:04:02+05:30",
            "Account_Name.Account_Name": "Grayson",
            "id": "4876876000003548001"
        },
        {
            "Deal_Name": "Eastwing Deal",
            "Created_Time": "2023-04-05T19:10:55+05:30",
            "Account_Name.Account_Name": "Grayson",
            "id": "4876876000003526011"
        }
    ],
    "info": {
        "count": 2,
        "more_records": true
    }
}

In the same query, if you want to use the Account ID instead of the name, replace ((Account_Name.Account_Name in ('Grayson','Zylker')) with ((Account_Name in (4876876000001236083, 4876876000002799001)) to include the IDs instead of the field API names and the account names.
{
    "select_query": "SELECT Deal_Name, Account_Name.Account_Name, Created_Time FROM Deals WHERE (((Account_Name in (4876876000001236083, 4876876000002799001)) and (Owner is not null)) and (Contact_Name is null)) ORDER BY Created_Time DESC LIMIT 2"
}

3. Date, DateTime, Number, Currency Fields

=, !=, >=, >, <=, <, between, not between, in, not in, is null, is not null are the supported comparators for these fields.

Sample Query 1: (between, <, >)

{

    "select_query": "SELECT Deal_Name, Amount, Stage, Probability FROM Deals WHERE (((Closing_Date between '2023-01-01' and '2023-03-31') and (Probability < 99)) and (Amount > 10000))"

}

This query retrieves the deal name, amount, stage, and probability of all deals whose closing date is between January 1, 2023 and March 31, 2023, and whose probability is less than 99 and amount is greater than 10000.

Sample Response:
{
    "data": [
        {
            "Deal_Name": "Chapman Deal",
            "Amount": 2500000,
            "Probability": 97,
            "Stage": "Closed Won",
            "id": "4876876000003550011"
        }
    ],
    "info": {
        "count": 1,
        "more_records": false
    }
}

Sample Query 2: (<=, !=, >=)

{
    "select_query": "SELECT Product_Name, Qty_in_Stock, Vendor_Name, Cost_Price FROM Products WHERE (((Sales_End_Date <= '2023-04-30') and (Qty_in_Stock != 0)) and (Cost_Price >= 500))"
}

This query retrieves the product name, quantity in stock, vendor name, and cost price for all products whose sales end date is on or before April 30, 2023, whose quantity in stock is not zero, and whose cost price is greater than or equal to 500. Since Vendor_Name is a lookup field, only the ID will be returned in the response.
Sample Response
{
    "data": [
        {
            "Cost_Price": 2000,
            "Vendor_Name": {
                "id": "4876876000001039017"
            },
            "Product_Name": "Sigma",
            "Qty_in_Stock": 30,
            "id": "4876876000001036109"
        }
    ],
    "info": {
        "count": 1,
        "more_records": false
    }
}

Sample Query 3: (not between, is not, >)

{
    "select_query": "SELECT Last_Name, First_Name, Referred_By.Full_Name FROM Leads WHERE (((Final_Score not between 10 and 20) and (Annual_Revenue is not null)) and (No_of_Employees > 200)) LIMIT 1"
}

This COQL query selects the last name, first name, and the full name of the lead's referred by field, for one lead whose final score is not between 10 and 20annual revenue is not null and whose number of employees is greater than 200
Sample Response
{
    "data": [
        {
            "First_Name": "Chau",
            "Last_Name": "Kitzman",
            "id": "4876876000000333403",
            "Referred_By.Full_Name": "Simmons Truhlar"
        }
    ],
    "info": {
        "count": 1,
        "more_records": true
    }
}

Sample Query 4: (>, not in, =, is null)

{
   "select_query":"SELECT PO_Number, PO_Date, Status, Discount FROM Purchase_Orders WHERE (((PO_Date = '2023-04-06') and (Due_Date not in ('2023-04-10','2023-04-11', '2023-04-12'))) or ((Discount > 10) and (Requisition_No is null)))"
}

This query selects the PO_Number, PO_Date, Status, and Discount from the Purchase_Orders module where the PO_Date is equal to '2023-04-06' and Due_Date is not any of '2023-04-10', '2023-04-11', or '2023-04-12'; OR Discount is greater than 10 and Requisition_No is null. In this query, we have used both AND and OR operators to combine the clauses.
Sample Response
{
    "data": [
        {
            "Status": "Created",
            "PO_Date": "2022-05-10",
            "Discount": 9990,
            "PO_Number": "PO-JL-3876",
            "id": "4876876000001125176"
        },
        {
            "Status": "Created",
            "PO_Date": "2023-04-06",
            "Discount": 370.37,
            "PO_Number": "PO-DA-1932",
            "id": "4876876000003561019"
        }
    ],
    "info": {
        "count": 2,
        "more_records": false
    }
}

We hope you found this post useful and that it has given you a better understanding of COQL queries. In our next post, we will discuss the rest of the field types, aggregate functions with more examples, and provide more queries to help you get started.

If you have any questions or feedback, please let us know in the comments below, or write to us at support@zohocrm.com. We would love to hear from you! 

Additionally, if you have any questions about the COQL API or how to construct a query, kindly let us know in the comments.

Additional Reading:


    • Recent Topics

    • Expanded data-capturing capabilities with enhanced tabular sections

      We are thrilled to announce an update to Zoho Recruit that brings even more flexibility and customization to your recruiting process. With the addition of 10 new field types to the tabular sections, you now have the power to enhance your tabular sections
    • Files Uploaded to Zoho WorkDrive Not Being Indexed by Search Engines

      Hello, I have noticed that the files I upload to Zoho WorkDrive are not being indexed by search engines, including Google. I’d like to understand why this might be happening and what steps I can take to resolve it. Here are the details of my issue: File
    • Marketing Automation Emails Going to Spam

      Google is trapping all the marketing automation emails in spam. My domain has a perfect reputation and it looks like Zoho has a low reputation which is sending it to spam. When I pull the email out of spam and click on a link in the email, I get this
    • I'm getting an "Invalid_scope" error, even though I used an access token generated with the correct scope.

      I'm getting an "Invalid_scope" error, even though I used an access token generated with the correct scope. Here’s what I did in Postman: Generated the code to create an access token using the following URL: https://accounts.zoho.eu/oauth/v2/auth?scope=ZohoCampaigns.contact.UPDATE&client_id=<client_id>&response_type=code&access_type=offline&redirect_uri=https://1882-2-26-193-161.ngrok-free.app
    • Customer can't comment on SO or Invoice

      Hi I just saw that my customers are not able to submit a comment either on invoices or sales order. What happens if my customer hits submit is just nothing. only a red line appears on top of the page which probalby indicates an error. I'm not able to
    • Convert Request to Forum Topic

      I know you can convert a forum topic to a request and a request to a solution in the knowledge base, but how do you convert a request to a forum topic?  Is this possible?  If not is this a feature coming down the pipe in the near future? Thanks!
    • Integration of Business Hours in Email Templates

      Dear Zoho Desk Team, We would like to propose a feature enhancement to Zoho Desk that would greatly improve the utility of the Business Hours settings and streamline communication with our clients. Feature Request: Integration of Business Hours in Email
    • Send To Zoho Sign not Showing

      The button send to Zoho sign is not showing on my Zoho CRM . Is there additional steps I need to take after installing Zoho Sign to CRM ?
    • Vivaldi will not open the Zoho Mail app when I click a email link in the browser

      I'm running Vivaldi on Arch with the Plasma desktop and have under default applications Zoho Mail set as my default email client. Whenever I click a email link in Vivaldi I get the below when it should be launching Zoho. Any ideas on rectifying this issue?
    • Zoho Creator Upcoming Updates - December 2024

      Hi all, We're excited to be back with the latest updates and developments on the Creator platform. Here's what we're going over this month: Deluge AI assistance Rapid error messages in Deluge editor QR code & barcode generator Expandable RTF and multi
    • Zoho Sign / Prefill By You - Editable by Them!

      Zoho Sign seems to have two field options available - an empty field for signer(s) to complete or a field that has been prefilled by you, that becomes read only once sent.  What I would like is an option on the pre-filled by you fields, to leave them
    • How to transfer all my mails from Zoho to Gmail or Office 365

      is there any option to move my emails from zoho to gmail or office 365. i would like to export more than 25k emails from zoho to office 365 or gmail. can anyone help me to guide properly. this will help me to access my emails easily i have both account and can easily  do it with office 365 or gmail. i want two options. direct from zoho to office 365  or exported eml files from zoho to gmail. please suggest me both if possible 
    • Is the Contacts sync between Campaigns and CRM bi-directional?

      Is the Contacts sync between Campaigns and CRM bi-directional?
    • Task does not syncing to google calendar shedual

      Hi why does the tasks activities do not syncing with the google calendar like the event option does?
    • Bug with Zobot Human transfer

      I have configured the brand, the operator, and the Zobot in Spanish. However, no matter what I do, it always says "YES" instead of "Sí" or "Sure, why not " instead of "Claro, ¿por qué no?" when asking if the user wants to contact a human operator. The
    • Error AS101 when adding new email alias

      Hi, I am trying to add apple@(mydomain).com The error AS101 is shown while I try to add the alias.
    • This mobile number has been marked spam. Please contact support.

      Hi Support, Can you tell me why number was marked as spam. I have having difficult to add my number as you keep requesting i must use it. My number is +63....163 Or is Zoho company excluding Philippines from their services?
    • email address autocomplete

      Is there a way to eliminate certain addresses from showing up in auto complete when entering an address? Many old and unused addresses currently show up, many of which I would like to get rid of. Thanks
    • Something went wrong. One or more fields contain errors

      I am getting this error but there is no way to debug what field is causing the issue . I have over 100 fields. Everything was working fine and then i fixed some fields that should have the same field names but had a typo and i am getting this error. It
    • Integrating Zoho Desk Instances from two separate organizations

      Is it possible to integrate Zoho Desk with an instance from another organization? For example, creating a ticket in one organization can cause the creation of a ticket in the second organization? Or certain tickets from one organization be viewable by
    • Send Whatsapp with API including custom placeholders

      Is is possible to initiate a session on whatsapp IM channel with a template that includes params (placeholders) that are passed on the API call? This is very usefull to send a Utility message for a transactional notification including an order number
    • Knowledge base bug - Error: Article couldn't be updated.

      It took me a while to figure this out, truly one of the most irritating bugs in Zoho. I hope you find this information helpful. When using the knowledge base to create articles, make sure your keywords are in lowercase and separated by commas. Otherwise,
    • Is this possible with Campaigns?

      My company is currently moving CRM's from Monday to Zoho One. Currently, our marketing lead process is send out 7 sms messages over 14 days if the lead is in a certain status. If we don't get a response the lead is put into a "Closed" status. Do we buy
    • How to view two portals (Zoho CRM & Zoho Books) in single login

      Hello there, I need to create a portal access for the Customers. Customer data present in two applications namely Zoho CRM & Zoho Books. My requirement is to show the two different portals(Zoho CRM Portal & Zoho books Portal) in single login. I could
    • Invoice status on write-off is "Paid" - how do I change this to "Written off"

      HI guys, I want to write off a couple of outstanding invoices, but when I do this, the status of the invoices shows as "Paid". Clearly this is not the case and I need to be able to see that they are written off in the customer's history. Is there a way
    • Zoho Flow or Schedules

      I have a process where we text our leads 7 times over a 14 day with different content for each text. I created one flow in Zoho Flow to do this, but wondering if there is a more efficient way to accomplish this via Schedules. It goes on for 6 more times
    • Updating Bounced Contacts in Campaigns to the CRM

      The article explains how to update Opt-outs from Campaigns to CRM, but not bounces. While Campaigns will automatically remove any bounced emails from future campaigns, is there a process by which a bounce will update or make a notification in the CRM
    • Bandwidth, voice and poor video

      Dear Team, The webinar has made things quite easy and convenient for educators around the world. We are an art & culture-based organization where students and researchers are our major audience.  While using the Zoho webinar platform, we have observed that the audio lags and the video is of poor quality and often freezes. Some participants don't hear what is being spoken.  We also found that even a slightly slow internet connection disrupts the webinar while it should be working well even on lower
    • No Hope for Zoho Meeting

      Zoho Meeting is just the poorest meeting app I've come across in a long time. The support sucks too. I called to see if there was anything that could be done on the backend and while I was on a test meeting with support the video was lagging and freezing
    • Zoho books and venmo

      Hi, Is there a way to hook Venmo into zoho books? I have a Venmo business account and want to be able to sync that. I know you can do it with the paypal integration but I dont want to use paypal for the fees and that doesnt allow me use/integrate my current
    • Associate Email API Internal Error

      I am trying to associate an already existing email within a function using the Related Emails API. To provide more context, I also have admin permissions and have ensured that the fields are correct and that I have admin permissions when associating the
    • Contacts Don't Always Populate

      I've noticed that some contacts can easily be added to an email when I type their name. Other times, a contact doesn't appear even though I KNOW it is in my contact list. It is possible the ones I loaded from a spreadsheet are not an issue and the ones
    • 550 5.4.6 Unusual sending activity detected. Please try after sometime. <a href=https://www.zoho.com/mail/help/usage-policy.html target=_blank>Learn more.</a>

      Please help me with this. Sending of mails is blocked.
    • Segmenting Contacts Based on Product Purchased

      I am trying to organize our main Marketing Automation email list in a way that segments contacts based on products they have purchased (for example in this case it is 3 different products). To my knowledge, this would require the sync from Zoho CRM to
    • Update a lookup field in CRM from Creator using deluge

      I have a Creator form that creates a new account. When it creates the new account in the Accounts Module, I need it to also populate the Parent Account, which is a lookup field coming from the Module Parent Accounts, field Parent Account Name. I have
    • Urgent Assistance Needed with DKIM Verification

      Hi, I have been trying to verify the DKIM for the past month using your instructions as well as other resources. Unfortunately, I have not been able to resolve the issue, and it remains persistent. I need to address this problem as soon as possible so
    • Someone made ActiveSync and Autodiscover work, with iOS and macOS

      Hi, I'm trying to set this up for the fifth day now and I"m not getting anywhere. Weird thing is that somewhen in the beginning, I had it working, when I still had VirtualServers and certificates mixed up. But now it's all fine, I have the XML file from
    • How do I attach tasks from one task to other tasks in the same project

      How do I attach tasks from one task to other tasks in the same project
    • Not able to change colors help center

      Hi. How can I change the orange color in the help center? You can change everything besides this font color And how can I remove the part on the bottom?
    • Zoho Books Invoice Salesperson: requires ID but there is no "Fetch salesperson" action

      Hi, I am trying to attach a Salesperson to a Zoho Books invoice. In Zoho Flow, the salesperson field required an ID. However, I only have the salesperson name, I need to fetch salesperson by name and then provide the ID. There is no option to fetch salesperson...
    • Next Page