DEV Community

Dmitry Romanoff
Dmitry Romanoff

Posted on

2

How to find the number of SELECTs, INSERTs, DELETEs, and UPDATEs on a specific table in PostgreSQL?

Knowing the ratio of SELECT, INSERT, DELETE, and UPDATE operations in PostgreSQL databases (or any other database management system) is crucial for several reasons, reflecting performance, optimization, and architectural planning.

To find the number of SELECTs, INSERTs, DELETEs, and UPDATEs on a specific table in PostgreSQL, you can utilize the pg_stat_all_tables view for basic DML statistics (INSERT, UPDATE, DELETE) but unfortunately, this view does not track SELECT operations directly.

For DML operations, you can query the pg_stat_all_tables view. This view provides counts for INSERTs, UPDATEs, and DELETEs, but not for SELECTs.

Here’s how you can get those counts for a specific table in a specific schema:

SELECT relname AS table_name,
schemaname AS schema_name,
coalesce(seq_scan, 0) + coalesce(idx_scan, 0) AS total_selects, 
n_tup_ins AS inserts,
n_tup_upd AS updates,
n_tup_del AS deletes
FROM pg_stat_all_tables
WHERE relname = 'your_table_name'
AND schemaname = 'public'
ORDER by (coalesce(seq_scan, 0) + coalesce(idx_scan, 0) + n_tup_ins + n_tup_upd + n_tup_del) DESC;
Enter fullscreen mode Exit fullscreen mode

Here’s how you can get those counts for all the tables in a specific schema:

SELECT relname AS table_name,
schemaname AS schema_name,
coalesce(seq_scan, 0) + coalesce(idx_scan, 0) AS total_selects, 
n_tup_ins AS inserts,
n_tup_upd AS updates,
n_tup_del AS deletes
FROM pg_stat_all_tables
WHERE schemaname = 'public'
ORDER by (coalesce(seq_scan,0) + coalesce(idx_scan,0) + n_tup_ins + n_tup_upd + n_tup_del) DESC;
Enter fullscreen mode Exit fullscreen mode

In these queries, seq_scan + idx_scan gives us an approximation of SELECT operations: it counts the number of sequential and index scans, which is not a direct measure of SELECT statements but can give you an idea of the reading activity on the table.

API Trace View

How I Cut 22.3 Seconds Off an API Call with Sentry 👀

Struggling with slow API calls? Dan Mindru walks through how he used Sentry's new Trace View feature to shave off 22.3 seconds from an API call.

Get a practical walkthrough of how to identify bottlenecks, split tasks into multiple parallel tasks, identify slow AI model calls, and more.

Read more →

Top comments (0)

Billboard image

Try REST API Generation for Snowflake

DevOps for Private APIs. Automate the building, securing, and documenting of internal/private REST APIs with built-in enterprise security on bare-metal, VMs, or containers.

  • Auto-generated live APIs mapped from Snowflake database schema
  • Interactive Swagger API documentation
  • Scripting engine to customize your API
  • Built-in role-based access control

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay