Skip to main content

ZTeraDB Query Builder Guide

The ZTeraDBQuery class helps you build database queries without writing SQL.


🎯 What is ZTeraDBQuery?

It is a chainable query builder that lets you perform:

  • SELECT
  • INSERT
  • UPDATE
  • DELETE
  • Filtering
  • Sorting
  • Pagination
  • Related field lookups (joins)

Example:

query = ZTeraDBQuery("user").select()

🧠 How Query Building Works

Start Query
↓
Choose Type (select/insert/update/delete)
↓
Add Fields (optional)
↓
Apply Filters
↓
Run the Query

πŸ— Creating a Query

query = ZTeraDBQuery("schemaName")

schemaName β†’ table/schema in your ZTeraDB instance


πŸ”₯ Query Types

1️⃣ SELECT​

query = ZTeraDBQuery("user").select()

2️⃣ INSERT​

query = (
ZTeraDBQuery("user")
.insert()
.fields({
"email": "test@site.com",
"status": True
})
)

3️⃣ UPDATE​

query = (
ZTeraDBQuery("user")
.update()
.fields({"status": False})
.filter({"id": 1})
)

4️⃣ DELETE​

query = (
ZTeraDBQuery("user")
.delete()
.filter({"id": 5})
)

🏷 fields() β€” Selecting, Inserting, Updating

SELECT Specific Fields​

query.select().fields({
"email": 1,
"status": 1
})

INSERT New Row​

query.insert().fields({
"name": "John",
"email": "john@test.com",
"status": True
})

UPDATE Existing Row​

query.update().fields({
"status": False
})

🎯 Basic Filters (filter)

query.filter({"status": True})
query.filter({"id": 10})
query.filter({"email": "abc@test.com"})

Equivalent SQL:

WHERE status = true

πŸŽ› Advanced Filters (filterCondition)

Advanced filters allow:

  • Math operations
  • AND / OR conditions
  • String filters
  • Comparisons (>, <, >=, <=)
from zteradb.filter_condition import ZTEQUAL, ZTMUL

query.filterCondition(
ZTEQUAL(
ZTMUL(["price", "quantity"]),
200
)
)

Equivalent SQL:

WHERE price * quantity = 200

πŸ”— relatedFields() β€” Joins Made Easy

Fetch data from related schemas.

userFilter = (
ZTeraDBQuery("user")
.select()
.fields({"email": 1})
.filter({"status": True})
)

query = (
ZTeraDBQuery("order")
.select()
.relatedFields({
"user": userFilter
})
)

πŸ“š Sorting

query.sort({"price": 1})   # ascending
query.sort({"price": -1}) # descending

Equivalent:

  • 1 β†’ ASC
  • -1 β†’ DESC

πŸ“ limit(start, end) β€” Pagination

query.limit(0, 10)

πŸ”’ count()

Returns number of matching records instead of row data.

query.count()

πŸ§ͺ Full Example

query = (
ZTeraDBQuery("product")
.select()
.fields({"name": 1, "price": 1})
.filter({"status": "A"})
.sort({"price": 1})
.limit(0, 20)
)

πŸ›‘ Common Mistakes

❌ Using filterCondition for simple equality
βœ” Use .filter() unless advanced logic is needed

❌ Not calling .fields() for insert/update
βœ” Always define fields for INSERT and UPDATE

❌ Wrong sort values
βœ” Only use 1 or -1

❌ Missing schemaName
βœ” Always pass a valid schema name to constructor


πŸŽ‰ You’re Ready for Filtering Logic!

Continue to:
πŸ‘‰ filter-condition.md