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

    • 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...
    • Change format of quantity format

      Hi,  I would like to change the qunatity format from 1,00 to 1.  Is this possible?   thanks!
    • Ticket Views: filter criteria -> dynamic date values in relation to the current date

      Hello all, It would be very helpful if you could build custom views in such a way that you do not have to adjust the criteria daily or at whatever interval in order to change the fixed date value as needed. For example, I would like to create a view that,
    • Captchas: No support for Google reCAPTCHA or similar

      Hi all, The current captcha integrated into Creator is very basic, and often near-impossible to read. I'm building an app for a charity which includes a couple of public-facing forms, and this is a real issue for people with dyslexia and related conditions - it's effectively excluding them if you want any form of spam protection at all on your published forms (and that being said, the current captcha doesn't even seem very effective - bots can often read it more easily than humans). I've raised this
    • Maintain consistency in ticket responses with shared snippets

      Hello everyone! We are excited to announce that our highly anticipated snippet sharing feature is now available to all users. As you know, snippets are pre-defined message templates, or canned messages, that help agents respond to tickets with efficiency.
    • Tickets - Zoho Desk

      Hi Team, My Clients need to see their tickets created and the status of the ticket in the Zoho Support Desk itself. How can I do this? My Client doesn't have a Zoho Account. They need to access the ticket by the provided link without signing in.
    • Automatically assign Contacts to Account owners

      Hi, I have a finite number of accounts set up in the CRM, and each new contact that comes in is automatically assigned to an Account according to a rule I set up. I want the Contact owner in the Contacts module to be assigned to the relevant Account owner.
    • Making Copies/Duplicates of Zoho Forms (Shared)

      Question to the community: is there a way to take a 'shared form' , make a duplicate copy and save under My Forms, so that i can use that which was already created as a template to make updates to and use as a test form and be able to have full access,
    • Using IMAP configuration for shared email inboxes

      Our customer service team utilizes shared email boxes to allow multiple people to view and handle incoming customer requests. For example, the customer sends an email to info@xxxx.com and multiple people can view it and handle the request. How can I configure
    • Can you help us creating a customised form with payment link?

      I would like to create a customised Transport form where the user will be asked to make payment basis the drop/ pick up they select.
    • Deleting or disabeling predefined ticket list views

      Is it possible to delete or disable predefined views or is this still not possible? For instance, we are not using the chat function and therefore have no use for the "Missed Chats" view. Thanks!
    • How to restore deleted Field

      I edited a field in zoho form and by accident I deleted a field (email address). The form is ongoing to be filled by respondent. Then, when I checked to the all entries and report, the email address is gone. I checked in audit log, there is a record that
    • Unable to load your extension. Please check your plugin-manifest or Resources.json.

      Hi Team, I am using the config module with multiple fields of different types, such as checkboxes and picklists. However, I am encountering the following issues: Error Message: When loading the extension, I get the error: "Unable to load your extension.
    • Remove or hide default views

      I'm looking to only have the views pertinent to my organization.  Is there a way to show only my custom views (or separate them to a different area or something)? If not, this should be a feature as switching from Zendesk we had this option...
    • No Sales Returns on SO's with Dropped Shipped items + Inventory Items

      We have encountered an issue in Zoho related to sales orders that include both dropshipped items and inventory items. Specifically, it is currently not possible to create sales returns for the company’s own inventory items from these sales orders. This
    • Layout Rules / Quick create

      Hello, is there a way to create a layout rule for quick create option? Regards, Katarzyna
    • Issue with Create Note Button and Popup Form in Leads Module

      Hello Zoho Community, I am trying to implement a "Create Note" button in the Leads module with the following functionality: 1. When the button is clicked, a form should pop up with fields to add notes. 2. After filling out the form and clicking Send,
    • Finding draft ticket replies

      Is there a way to see all tickets which have draft replies?
    • Guidance on Making Zoho Desk Connections Available for All Data Centers

      Hi Team, I’m currently developing an application using Zoho Desk connections to manage OAuth for my third-party products. Could you please advise on the steps required to make it available across all data centers? Looking forward to your thoughts on
    • Caso de Uso | Menos trámites, más salud: Clínicum optimiza sus recursos con Zoho One

      "La automatización del proceso de solicitud de bajas y su trazabilidad a través de Zoho nos ha supuesto una mejora en el ROI." - Carol Rodríguez, Responsable de Experiencia del Cliente interno y externo en Clínicum ¡Hola a todos! Estamos emocionados de
    • Is it possible to disable Chat Waiting Time, or to make it indefinite?

      We have used many online chat services over the years. However, Zoho's SalesIQ appears to be the only one we've tried that has a mandatory time limit where we must respond to new customer queries. We are a small business so we have no dedicated staff to monitor incoming chats, which makes this requirement very undesirable. (There have been no complaints from our clients when we're slower to follow up.) Is there an option I'm missing to turn Chat Waiting Time off, or to allow an infinite wait time?
    • Double opt-in notifications and customizable confirmation messages for your webforms

      Dear CRM Community, We are excited to announce a major upgrade to our Webforms feature. You can now customize the confirmation message shown to your users who double opt-in from your webform and also customize your confirmation emails when they submit
    • Bulk create tasks - Zoho Projects API

      Hi Zoho/Community, I am trying to create multiple tasks in a single API call, is there a way we can combine multiple request bodies into one single payload? The issue I am facing is the rate limiting on the API, I wanted to create certain amount of tasks
    • Task Due dates and Reminder Date & Time

      I like to have a reminder on many tasks in Zoho Recruit. I find the process cumbersome in that each task requires the following: 1. click and select due date 2. Click the reminder box 3. Click on (Reminder) Start Date 4. Click on (Reminder )Time If one
    • Unable to Access Admin Console and Email Sending Issues

      Hello Zoho Support Team and Community, I hope this post finds you well. I am currently facing two significant issues with Zoho services: Admin Console Access Issue: Every time I try to access the Zoho Admin Console, it gets stuck on the loading screen
    • Tracking new lead response time

      Hi, I have a team of Sales Development Reps, who have a KPI of responding to a lead within 20 mins or less once it hits the system.  I seem to recall that Zoho CRM had the capability to track this in a previous version, but don't see it anywhere.   It's
    • Getting The Following Error.. 550 5.4.6 Unusual sending activity detected

      I just launched a marketing campaign and I got this error. Everything was working fine previously. This is a big launch so need to fix it asap. Can anyone help?
    • mail

      Frequent sending of this email, what does this mean? How to solve it
    • Printing on 80mm bluetooth Pos Printer

      Hello. I am trying to print receipts and invoices using my 80mm bluetooth connectivity Pos printer. I have configured the Templates to Retail so that it matches the paper width of the Pos printer. However, when I click Print in zoho, first it opens the
    • Trying to integrate gmail but google keeps blocking Zoho access for integration??

      hi i am trying to integrate a gmail account so can track/access business emails this way. I have followed the instructions but after selecting my email account it gets re-routed to this message (screengrab below) Can anyone advise a way around this or
    • Which attribute in Zoho books invoice api represent branch attached to the invoice?

      Hi Zoho Team, We have done the integration with Zoho Books API. While fetching data from Invoice API we want to get branch value attached to the invoice. We could not figure out which field in "Get an Invoice" api represents branch value attribute. Thanks
    • How to Billed from two different GST Numbers

      How to Billed from two different GST Numbers. Suppose ABC & Co had GST registration in Delhi and Haryana and Zoho account is created with Delhi GST Registration number. Now i also want to issue invoice from Haryana GST Registration number. How can i proceed ?
    • How to hide Predefined views

      Hi, I would like to know how to hide: Predefined views and Recent views or some records from this list. If I'm using it form iPad I have to scroll to see User created views. Or maybe it's possibility to move User created views on the top. All the best,
    • Is it possible to trigger the review process when a record is edited?

      Hello, I need to trigger a review process whenever a field is updated to a specific value. This field is empty when the record is created and is only filled later. I know the approval process exists, but that's not what I'm looking for in this case. What
    • How to Customize Task Creation to Send a Custom Alert Using JavaScript in Zoho CRM?

      Hello Zoho CRM Community, I’m looking to customize Zoho CRM to send a custom alert whenever a task is created. I understand that Zoho CRM supports client scripts using JavaScript, and I would like to leverage this feature to implement the alert functionality.
    • Deleting Views

      How do you delete views? Please syd
    • Next Page