Database queries are essential for displaying dynamic content on your site. However, inefficient queries can slow down your site's performance by transferring unnecessary data between the server and browser. Common inefficiencies include retrieving unfiltered results, loading complete sets of data at once, and requesting unused fields.
The following techniques optimize your database queries and improve site performance by helping you retrieve only the data you need, when you need it.
Use filter methods to query only the data you need. Instead of retrieving all items from a collection, apply filters to get specific items that match your criteria.
Some filter methods include:
eq(): Items equal to a specific valuegt(): Items greater than a specific valuelt(): Items less than a specific valuecontains(): Items that contain specific textstartsWith(): Items that start with specific textView more filter methods in the WixDataFilter API reference.
Populate a repeater with only "active" items from a collection:
Note: You can also filter data using datasets in the editor.
Query only the fields you need rather than entire records to reduce data transfer and improve performance.
For example, if your page displays only a few fields from a collection with many fields, retrieve just those specific fields.
Use the fields() method to retrieve only the "title" and "status" fields:
Speed up query execution by omitting the total item and page counts.
By default, the returnTotalCount data option in the find() method is false. This means the query won't count the total number of items that match your query, which makes it run faster.
Only set returnTotalCount to true when you need the total counts. For example, to show page numbers or "X items found".
Use find() without setting returnTotalCount, defaulting it to false:
Set returnTotalCount to true to get the total count of items:
Instead of loading all items at once, use the limit() method in your query to retrieve data in smaller batches. By default, queries return up to 50 items, but you can adjust this limit based on your needs. This improves initial page load time and allows you to load additional items as needed using paging methods like hasNext() and next().
Load the first 6 items with a Load More button for additional results:
Note: You can also configure pagination limits for datasets in the Editor.