0Pricing
PostgreSQL Performance & Query Optimization · Lezione

Diagnosticare l'attività in corso con pg_stat_activity

Impari a usare la vista pg_stat_activity per vedere cosa sta facendo ogni connessione, trovare query di lunga durata o bloccate e annullare o terminare in sicurezza le sessioni problematiche.

Diagnosticare l'attività in corso con pg_stat_activity è una lezione PostgreSQL Performance & Query Optimization gratuita su CoddyKit. Questa è la lezione 4 di 4. Puoi leggere la lezione completa qui gratuitamente — poi esercitati direttamente nel browser con un editor di codice integrato e un tutor IA disponibile 24/7. Fa parte del percorso di apprendimento PostgreSQL Performance & Query Optimization, e i tuoi progressi si sincronizzano tra il web e l'app CoddyKit. Il corso PostgreSQL Performance & Query Optimization include 4 lezioni in totale.

Parti di questa lezione non sono ancora state tradotte e vengono mostrate in inglese.

Your Window into Live Sessions

The pg_stat_activity view has one row per server connection. It is the first place to look when the database feels slow or stuck, showing what each session is doing this instant.

The Key Columns

The most useful columns are:

  • pid: the backend process id
  • state: active, idle, idle in transaction
  • query: the current or last SQL text
  • wait_event: what the session is waiting on

A Basic Look

Select the essentials for all active sessions.

SELECT pid, usename, state, wait_event, query
FROM pg_stat_activity
WHERE state <> 'idle';

Finding Long-Running Queries

Compute how long each active query has been running by subtracting query_start from now.

SELECT pid, now() - query_start AS runtime, query
FROM pg_stat_activity
WHERE state = 'active'
ORDER BY runtime DESC;

Idle in Transaction Danger

A session in idle in transaction holds locks and pins the oldest XID without doing work. These can block vacuum and other sessions. Hunt them down.

SELECT pid, now() - xact_start AS tx_age, query
FROM pg_stat_activity
WHERE state = 'idle in transaction'
ORDER BY tx_age DESC;

Seeing What a Session Waits On

The wait_event_type and wait_event columns reveal whether a session is waiting on a lock, on I/O, or on a client. This pinpoints the bottleneck.

SELECT pid, wait_event_type, wait_event, query
FROM pg_stat_activity
WHERE wait_event IS NOT NULL;

Finding Who Blocks Whom

Combine activity with pg_blocking_pids to see which sessions are blocking others.

SELECT pid, pg_blocking_pids(pid) AS blocked_by, query
FROM pg_stat_activity
WHERE cardinality(pg_blocking_pids(pid)) > 0;

Cancelling a Query

pg_cancel_backend stops the current query in a session but leaves the connection open. Try this first — it is the gentler option.

SELECT pg_cancel_backend(12345);

Terminating a Connection

If cancelling is not enough, pg_terminate_backend closes the whole connection, rolling back its transaction. Use it for stuck idle-in-transaction sessions.

SELECT pg_terminate_backend(12345);

Building a Monitoring Habit

Good practice:

  • Set idle_in_transaction_session_timeout to auto-kill stragglers
  • Set statement_timeout to bound runaway queries
  • Watch pg_stat_activity during incidents before reaching for the kill switch

Counting Connections by State

To gauge overall pressure, summarize how many connections sit in each state. A pile of idle-in-transaction or active sessions hints at pooling or query problems.

SELECT state, count(*)
FROM pg_stat_activity
GROUP BY state
ORDER BY count(*) DESC;

Quick Check

Test your live-monitoring knowledge.

Recap

You learned live diagnosis with pg_stat_activity:

  • One row per connection with state, query, and wait info
  • Find long queries via now() - query_start
  • Hunt idle-in-transaction sessions that block vacuum
  • pg_blocking_pids reveals who blocks whom
  • Cancel a query or terminate a backend when needed

Domande Frequenti

La lezione «Diagnosticare l'attività in corso con pg_stat_activity» è gratuita?

Sì — il testo completo di «Diagnosticare l'attività in corso con pg_stat_activity» è gratuito qui sul web. Per esercitarvi in modo interattivo (un editor di codice integrato e un tutor IA 24/7) e sbloccare il resto del corso PostgreSQL Performance & Query Optimization, passa a CoddyKit PRO. Il corso PostgreSQL Performance & Query Optimization include 4 lezioni in totale.

Cosa imparerò in «Diagnosticare l'attività in corso con pg_stat_activity»?

Impari a usare la vista pg_stat_activity per vedere cosa sta facendo ogni connessione, trovare query di lunga durata o bloccate e annullare o terminare in sicurezza le sessioni problematiche. Eserciti PostgreSQL Performance & Query Optimization con codice pratico che esegui direttamente nel browser, e un tutor IA 24/7 risponde alle tue domande mentre lavori sulla lezione.

Ho bisogno di esperienza per iniziare PostgreSQL Performance & Query Optimization?

Non è richiesta alcuna esperienza precedente. PostgreSQL Performance & Query Optimization su CoddyKit è strutturato per principianti e studenti avanzati, quindi puoi iniziare da qui o dall'inizio e procedere al tuo ritmo. Questa è la lezione 4 di 4.

Quanto tempo richiede la lezione «Diagnosticare l'attività in corso con pg_stat_activity»?

La maggior parte delle lezioni CoddyKit richiede circa 5–10 minuti. Ogni lezione è breve e interattiva, quindi fai progressi costanti e riprendi esattamente da dove hai lasciato su web e app.

Posso scrivere ed eseguire codice in questa lezione PostgreSQL Performance & Query Optimization?

Sì. Ogni lezione PostgreSQL Performance & Query Optimization include un editor di codice integrato, quindi scrivi ed esegui codice reale direttamente nel tuo browser e ricevi feedback istantaneo dall'IA — nessuna configurazione locale necessaria.

Tutte le lezioni di questo corso

  1. Utilizzare pg_stat_statements e pg_buffercache
  2. Configurazione del logging per l’analisi
  3. Integrazione degli strumenti di monitoraggio esterni
  4. Diagnosticare l'attività in corso con pg_stat_activity
← Torna a PostgreSQL Performance & Query Optimization