Go Query Optimization Techniques for PostgreSQL/MySQL
To optimize Go applications interacting with PostgreSQL or MySQL, focus on indexing, selective queries, connection handling, caching, and ORM efficiency. 1) Use proper indexing—identify frequently queried columns, add indexes selectively, and use composite indexes for multi-column queries. 2) Reduce data transfer—select only necessary columns, avoid SELECT *, paginate large datasets, and prevent N 1 queries with joins or batching. 3) Optimize connection handling—use a connection pool, set MaxOpenConns, MaxIdleConns, and ConnMaxLifetime appropriately. 4) Cache frequently accessed data—use Redis or Memcached, implement TTLs, and consider materialized views in PostgreSQL. 5) Manage ORM overhead—avoid unnecessary preloading, inspect generated queries, and prefer raw SQL when performance is critical.
When it comes to optimizing Go applications that interact with PostgreSQL or MySQL, the database layer is often where performance bottlenecks hide. The key isn't just writing clean Go code—it's understanding how your queries are executed and how your data is accessed.

Here’s what you can do to improve query performance in Go apps using PostgreSQL or MySQL.
Use Proper Indexing Strategically
One of the most common reasons for slow queries is missing or inefficient indexing. You might have a query that works fine with 100 rows but grinds to a halt at 100,000.

- Identify frequently queried columns, especially those used in WHERE, JOIN, and ORDER BY clauses.
- Add indexes selectively—too many indexes can slow down writes and take up unnecessary space.
- For composite queries (e.g., filtering by
user_id
andcreated_at
), consider composite indexes in the right order.
For example:
CREATE INDEX idx_user_created ON users (user_id, created_at);
Use EXPLAIN ANALYZE
in PostgreSQL or EXPLAIN
in MySQL to check if your query uses an index. If it says "Seq Scan" or "Using filesort", you probably need to revisit your indexing strategy.

Reduce Data Transfer with Selective Queries
Fetching more data than needed is a silent killer of performance. It increases memory usage on both the database and application side, and slows things down over the wire.
- Always specify only the columns you need instead of using
SELECT *
. - Avoid fetching large text/blob fields unless absolutely necessary.
- Paginate results when dealing with large datasets using
LIMIT
andOFFSET
, or cursor-based pagination for better scalability.
Example:
rows, err := db.Query("SELECT id, name FROM users WHERE status = $1 LIMIT 100", activeStatus)
Also, avoid N 1 queries by batching or joining related data upfront. Tools like pgx
for PostgreSQL or gorm
for MySQL can help manage eager loading effectively.
Optimize Connection Handling
Even the fastest queries won’t help if your app is waiting for a connection from the pool.
- Set appropriate connection limits based on your database capacity.
- Reuse connections using a connection pool (like
database/sql
in Go). - Tune parameters such as
MaxOpenConns
,MaxIdleConns
, andConnMaxLifetime
.
Example:
db, err := sql.Open("postgres", connString) db.SetMaxOpenConns(25) db.SetMaxIdleConns(25) db.SetConnMaxLifetime(time.Minute * 5)
Too many open connections can overwhelm your DB. Too few can create contention in high-load scenarios. Monitor actual usage and adjust accordingly.
Cache Frequently Accessed Data
Caching isn't just for HTTP layers—it's also powerful at the database level.
- Use Redis or Memcached to cache read-heavy data like configuration values or user profiles.
- Implement short TTLs for data that changes occasionally but not constantly.
- Consider materialized views in PostgreSQL if you're doing complex aggregations.
In Go, you can wrap query calls with a cache layer:
func getCachedUser(id string) (*User, error) { val, _ := redisClient.Get(id).Result() if val != "" { var user User json.Unmarshal([]byte(val), &user) return &user, nil } // Fallback to DB var user User err := db.QueryRow("SELECT ...").Scan(...) if err == nil { redisClient.SetEx(id, ..., time.Minute*10) } return &user, err }
This reduces repeated queries and speeds up response times significantly.
Bonus: Watch Out for ORM Overhead
ORMs like GORM are convenient, but they can introduce overhead if not used carefully.
- Avoid automatic preloading unless you really need it.
- Be cautious with auto-generated queries—they may not be optimized.
- Prefer raw SQL or builder libraries like
squirrel
orpgconn
when performance matters.
If you're seeing unexpected query patterns, log what your ORM is actually sending to the database. Sometimes a simple refactor can cut query count by half.
Optimizing queries in Go doesn’t always mean rewriting everything—it’s usually about identifying and fixing a few critical points. Start with the slowest queries, use proper tools, and don’t ignore the basics like indexing and connection handling.
Most of these improvements are low-effort compared to the gains they bring.
The above is the detailed content of Go Query Optimization Techniques for PostgreSQL/MySQL. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undress AI Tool
Undress images for free

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

The answer is: Go applications do not have a mandatory project layout, but the community generally adopts a standard structure to improve maintainability and scalability. 1.cmd/ stores the program entrance, each subdirectory corresponds to an executable file, such as cmd/myapp/main.go; 2.internal/ stores private code, cannot be imported by external modules, and is used to encapsulate business logic and services; 3.pkg/ stores publicly reusable libraries for importing other projects; 4.api/ optionally stores OpenAPI, Protobuf and other API definition files; 5.config/, scripts/, and web/ store configuration files, scripts and web resources respectively; 6. The root directory contains go.mod and go.sum

Using bufio.Scanner is the most common and efficient method in Go to read files line by line, and is suitable for handling scenarios such as large files, log parsing or configuration files. 1. Open the file using os.Open and make sure to close the file via deferfile.Close(). 2. Create a scanner instance through bufio.NewScanner. 3. Call scanner.Scan() in the for loop to read line by line until false is returned to indicate that the end of the file is reached or an error occurs. 4. Use scanner.Text() to get the current line content (excluding newline characters). 5. Check scanner.Err() after the loop is over to catch possible read errors. This method has memory effect

The if-else statement in Go does not require brackets but must use curly braces. It supports initializing variables in if to limit scope. The conditions can be judged through the elseif chain, which is often used for error checking. The combination of variable declaration and conditions can improve the simplicity and security of the code.

Go's flag package can easily parse command line parameters. 1. Use flag.Type() to define type flags such as strings, integers, and booleans; 2. You can parse flags to variables through flag.TypeVar() to avoid pointer operations; 3. After calling flag.Parse(), use flag.Args() to obtain subsequent positional parameters; 4. Implementing the flag.Value interface can support custom types to meet most simple CLI requirements. Complex scenarios can be replaced by spf13/cobra library.

gorun is a command for quickly compiling and executing Go programs. 1. It completes compilation and running in one step, generates temporary executable files and deletes them after the program is finished; 2. It is suitable for independent programs containing main functions, which are easy to develop and test; 3. It supports multi-file operation, and can be executed through gorun*.go or lists all files; 4. It automatically processes dependencies and uses the module system to parse external packages; 5. It is not suitable for libraries or packages, and does not generate persistent binary files. Therefore, it is suitable for rapid testing during scripts, learning and frequent modifications. It is an efficient and concise way of running.

Routing in Go applications depends on project complexity. 1. The standard library net/httpServeMux is suitable for simple applications, without external dependencies and is lightweight, but does not support URL parameters and advanced matching; 2. Third-party routers such as Chi provide middleware, path parameters and nested routing, which is suitable for modular design; 3. Gin has excellent performance, built-in JSON processing and rich functions, which is suitable for APIs and microservices. It should be selected based on whether flexibility, performance or functional integration is required. Small projects use standard libraries, medium and large projects recommend Chi or Gin, and finally achieve smooth expansion from simple to complex.

In Go, constants are declared using the const keyword, and the value cannot be changed, and can be of no type or type; 1. A single constant declaration such as constPi=3.14159; 2. Multiple constant declarations in the block are such as const(Pi=3.14159; Language="Go"; IsCool=true); 3. Explicit type constants such as constSecondsInMinuteint=60; 4. Use iota to generate enumeration values, such as const(Sunday=iota;Monday;Tuesday) will assign values 0, 1, and 2 in sequence, and iota can be used for expressions such as bit operations; constants must determine the value at compile time,

To connect to SQL databases in Go, you need to use the database/sql package and a specific database driver. 1. Import database/sql packages and drivers (such as github.com/go-sql-driver/mysql), note that underscores before the drivers indicate that they are only used for initialization; 2. Use sql.Open("mysql","user:password@tcp(localhost:3306)/dbname") to create a database handle, and call db.Ping() to verify the connection; 3. Use db.Query() to execute query, and db.Exec() to execute
