Thanks to visit codestin.com
Credit goes to stategraph.com

SQL Commands

The stategraph sql command group provides access to SQL (Structured Query Language) for querying your infrastructure from the command line.

Commands

Command Description
stategraph sql query Execute a SQL query
stategraph sql schema Get the SQL schema

stategraph sql query

Execute a SQL query against your infrastructure. stategraph query is a top-level alias for the same command.

stategraph sql query <query>

Arguments

Argument Required Description
<query> Yes SQL query string

Options

Option Required Description
--state No Scope the query to a single state (UUID). Without it, queries run across all states in the tenant.
--format No Output format: table (default), json, or simple

By default, results print as a human-readable table. Pass --format json for JSON
(useful for piping to jq), or --format simple for one value per line with no headers.

Example

stategraph sql query "SELECT type, count(*) AS total FROM resources GROUP BY type" --format json

Output (with --format json):

[
  { "type": "aws_instance", "total": 20 },
  { "type": "aws_security_group", "total": 15 },
  { "type": "aws_subnet", "total": 6 }
]

More Queries

# Count total instances
stategraph sql query "SELECT count(*) FROM instances"

# List all resource types with counts (count is reserved; alias as total and order by the expression)
stategraph sql query "SELECT type, count(*) as total FROM resources GROUP BY type ORDER BY count(*) DESC"

# Find resources by type (type lives on the resources table)
stategraph sql query "SELECT address FROM resources WHERE type = 'aws_instance'"

# Scope a query to one state
stategraph sql query "SELECT count(*) AS total FROM resources" --state <state-id>

SQL Syntax Notes

Stategraph SQL supports a subset of standard SQL:

  • JOINs workINNER, LEFT, and RIGHT joins with ON conditions
  • Table aliases workFROM resources AS r lets you write r.type
  • Column aliases workcount(*) as total is supported
  • CTEs workWITH name AS (...) clauses, including UNION
  • ORDER BY worksORDER BY type ASC is supported
  • LIKE / ILIKE work — pattern matching with % and _ wildcards, plus NOT LIKE / NOT ILIKE
  • No comments-- and /* */ are not supported in queries

stategraph sql schema

Get the SQL schema for understanding available tables and columns.

stategraph sql schema --format json

Like sql query, sql schema defaults to a table; pass --format json for the structure
below. It shows all tables with column names and their PostgreSQL types:

{
  "tables": {
    "instances": {
      "columns": {
        "address": { "type": "text" },
        "attributes": { "type": "jsonb" },
        "dependencies": { "type": "text[]" },
        "resource_address": { "type": "text" },
        "state_id": { "type": "uuid" }
      }
    },
    "resources": {
      "columns": {
        "address": { "type": "text" },
        "module": { "type": "text" },
        "state_id": { "type": "uuid" },
        "type": { "type": "text" }
      }
    },
    "states": {
      "columns": {
        "id": { "type": "uuid" },
        "name": { "type": "text" },
        "group_id": { "type": "uuid" },
        "workspace": { "type": "text" }
      }
    }
  }
}

Run stategraph sql schema to see the full list of tables and columns — there are additional tables beyond what's shown here.

Scripting Examples

Export query results to CSV

stategraph sql query "SELECT address, type FROM resources" --format json | \
  jq -r '.[] | [.address, .type] | @csv' > resources.csv

Count resources and format output

stategraph sql query "SELECT type, count(*) AS total FROM resources GROUP BY type" --format json | \
  jq -r '.[] | "\(.type): \(.total)"'

Generate report

#!/bin/bash
echo "Infrastructure Report"
echo "===================="
echo ""
echo "Total resources:"
stategraph sql query "SELECT count(*) AS total FROM instances" --format json | jq -r '.[0].total'
echo ""
echo "By type:"
stategraph sql query "SELECT type, count(*) AS total FROM resources GROUP BY type" --format json | \
  jq -r '.[] | "  \(.type): \(.total)"'

Error Handling

Syntax Errors

stategraph sql query "SELEC * FROM instances"
# Exit code: 2
# Error: could not parse the query (unexpected token near the start of the statement).

Unknown Columns

stategraph sql query "SELECT foo FROM instances"
# Exit code: 2
# Error: Unknown column 'foo'.
#
# To fix: run 'stategraph sql schema' to see available columns for each table.

Tips

  1. Quote queries — Always wrap queries in quotes to prevent shell interpretation
  2. Use jq — Pipe output to jq for formatting and filtering
  3. Test incrementally — Build complex queries step by step
  4. Check schema — Use stategraph sql schema to see available columns
  5. Qualify columns when joining — Use a table name or alias (r.type) when querying multiple tables

Next Steps