- read

Prepared vs. Non-prepared SQL: Golang Comparison

Adam Szpilewicz 101

Photo by Rubaitul Azad on Unsplash

If you enjoy reading medium articles and are interested in becoming a member, I would be happy to share my referral link with you!

In the realm of database interactions, the manner in which we structure and execute our SQL queries can significantly influence the overall performance of an application. Among the myriad techniques developers employ to optimize database operations, the choice between using prepared statements and non-prepared statements often emerges as a pivotal decision point. Prepared statements, heralded for their efficiency and security benefits, have become an indispensable tool in the developer’s arsenal. However, to what extent do they outperform non-prepared statements in terms of speed, especially when executing repetitive operations? In this article, we dive deep into a comparative analysis, pitting prepared statements against their non-prepared counterparts to discern the tangible differences in their performance.

Below is an example of how you can use prepared statements and non-prepared statements in Go using the github.com/go-sql-driver/mysql driver, benchmarks for both, and a docker-compose.yml to set up a MySQL container:

Docker Compose for MySQL

version: '3'
services:
mysql:
image: mysql:8
platform: linux/arm64/v8
environment:
MYSQL_ROOT_PASSWORD: rootpass
MYSQL_DATABASE: benchmarkdb
MYSQL_USER: user
MYSQL_PASSWORD: userpass
ports:
- "3306:3306"

Start it using:

docker-compose up

SQL Statements

CREATE DATABASE IF NOT EXISTS benchmarkdb;

USE benchmarkdb;
CREATE TABLE IF NOT EXISTS test (
id INT NOT NULL AUTO_INCREMENT,
data VARCHAR(255) NOT NULL,
PRIMARY KEY (id)
);

Go Program with Benchmarks

Install the necessary driver:

go get -u github.com/go-sql-driver/mysql