OriginChainDB
Sql

Summarize rows by status

← SQL examples

The language tabs use earlier client interfaces. Check SDK versions and connection setup before running them.

Group orders by status and calculate counts and amounts. An aggregate turns several rows into a summary value, such as SUM or COUNT.

Before you run it: Every selected field must be grouped or calculated by an aggregate. HAVING filters the finished groups.

Turn order rows into a status summaryGrouping produces one result row per status, not one row per order.
  1. Start with individual ordersRead each row's status and amount.
  2. Group equal statusesCollect paid and pending orders into their groups.
  3. Calculate each groupCount orders and compute the requested sum or average.
  4. Filter group results if neededHAVING applies after the group calculation.

Follow the example

  1. Load the order sample.
  2. Group by status.
  3. Run the count, total and average query.
  4. Read one summary row per status.

Run the request

First register and load the orders sample: shop.orders has id, customer_id, amount_cents and status. Use its three sample rows for the results shown here.

curl -X POST "https://$OC_HOST/v1/tenants/$OC_TENANT/sql" \
  -H "Authorization: Bearer $OC_TOKEN" \
  -H "Content-Type: application/json" \
  -d '{
    "sql": "SELECT status, COUNT(*) AS n, SUM(amount_cents) AS total, AVG(amount_cents) AS avg_amt, MIN(amount_cents) AS min_amt, MAX(amount_cents) AS max_amt FROM shop.orders GROUP BY status"
  }'

Check the result

The result contains one row per group rather than one row per order.

{
  "kind": "select",
  "rows": [
    { "status": "paid",    "n": 2, "total":  6240, "avg_amt": 3120.0,  "min_amt": 1250, "max_amt":  4990 },
    { "status": "pending", "n": 1, "total": 12900, "avg_amt": 12900.0, "min_amt": 12900, "max_amt": 12900 }
  ]
}

Important limits and checks

  • Selecting a non-grouped column. Every column in SELECT must either be in GROUP BY or wrapped in an aggregate. Standard SQL rule.
  • Filtering on aggregates. Use HAVING - it executes server-side (e.g. GROUP BY status HAVING COUNT(*) > 3). It runs after grouping, so it can reference aggregates that WHERE can't.

Continue

Continue to sort and page through rows.

© 2026 Silicoyn Technologies Pvt Ltd

On this page