Reusable queries

Writing Reusable SQL Queries For Your Application with DbVisualizer Scripts

Author: Ochuko Onojakpor
Length: 7 MINS
Type: Guide
Published: 2023-01-12
Intro
Writing reusable code is an essential aspect of being a good engineer. In this blog, we will teach you how to write queries using SQL and DbVisualizer.
Tools used in the tutorial
Tool
Description
DbVisualizer
Top rated database management tool and sql client

The most outstanding data scientists and engineers are frequently distinguished from others by their ability to build reusable code. It is essential to have this skill, especially if you oversee database operations, which have a significant impact on how smoothly your application runs. In other words, your codebase will function poorly if it contains pointless or repetitious code, but it will work well if it has useful or reusable code.

This tutorial will cover writing some popular SQL queries executed regularly in most applications, making them reusable and saving them with the features available in DbVisualizer.

Connecting To Our Database Server

First, we'll need to use the DbVisualizer program to establish a connection to our database server. You can learn how to do that by following this guide. All of your databases ought to appear on the left side once you've established a connection. To create a new database for this tutorial, right-click on Databases and choose "create database."

The database tree.

↑  The database tree

Creating a Script

At this point, we will need to create a script to store each SQL query separately so we can easily refer to them when we want to use them again. To create a script, follow the steps listed below:

Step 1: Click on the play icon with a plus next to it.

Showing the add script icon

↑  Showing the add script icon

It will open up a SQL commander tab where you can write your queries.

The SQL commander tab

↑  The SQL commander tab

Step 2: After writing your queries, click on the blue diskette icon to name your script and save it.

Showing the blue diskette icon

↑  Showing the blue diskette icon

Step3: You can view all your saved scripts in your bookmarks.

Showing the saved scripts in bookmarks tab

↑  Showing the saved scripts in bookmarks tab

Writing Reusable SQL Queries

For this tutorial, we'll create SQL queries for a few common database operations and then save them as scripts in the DbVisualizer program. The following are the queries we have:

The CREATE TABLE Query

Databases allow us to create tables and save data in them. We can achieve this using the CREATE TABLE command. Below is an example of creating a table:

1
CREATE TABLE `employees` (
2
`serial_number` varchar(100) NOT NULL,
3
`company_name` varchar(100) DEFAULT NULL,
4
`employee_markme` varchar(100) DEFAULT NULL,
5
`description` varchar(100) DEFAULT NULL,
6
`leave` varchar(100) DEFAULT NULL,
7
8
PRIMARY KEY (`serial_number`),
9
UNIQUE KEY `serial_number` (`serial_number`),
10
),;

Copy the query above into the SQL commander tab and click on the play icon to execute it.

Executing the create table query script

↑  Executing the create table query script

It works perfectly. But how do we make this query more configurable for broader use cases? By using DbVisualizer’s variable feature, we can set variables in our SQL query as parameters and prompt for their values when the query is executed. We can achieve this by wrapping the variables we choose like so “$”. Here is the reusable version of the CREATE TABLE query:

1
CREATE TABLE `${table_name}$` (
2
`${first_column}$` varchar(100) NOT NULL,
3
`${second_column}$` varchar(100) DEFAULT NULL,
4
`${third_column}$` varchar(100) DEFAULT NULL,
5
`${fourth_column}$` varchar(100) DEFAULT NULL,
6
`${last_column}$` varchar(100) DEFAULT NULL,
7
8
PRIMARY KEY (`${primary_key}$`),
9
UNIQUE KEY `${unique_key}$` (`${unique_key}$`)
10
);

Executing the query above creates the prompt in the image below.

Entering parameter values in the create table query

↑  Entering parameter values in the create table query

Click on “Continue” to execute the query using your provided values. Our CREATE TABLE query is now configurable.

Currently, we have an empty contacts table. We can populate it by importing data from this CSV file. To import data, right-click on the contacts table we just created, then click on the import table data option from the dropdown.

Selecting database to import table data

↑  Selecting database to import table data

Now select the CSV file in the file directory as shown in the image below:

Choosing a CSV file in directory

↑  Choosing CSV file in directory

Continue clicking “Next >” until you get to the “Import” button.

Importing the CSV file into the table

↑  Importing the CSV file into the table

Finally, click on “Import”. You should receive a success message to signify that the data has successfully been imported into your tables.

Import success message

↑  Import success message

The COUNT Query

The COUNT query counts each row in a chosen field and displays the total number of rows in the table. Users can also define the query partition clause if they specify the DISTINCT option. The ORDER BY clause and windowing clause are not allowed since this clause is a component of the analytic clause. The syntax is SELECT COUNT(colname) FROM table name. In our example below, we will be counting data grouped by a common description:

1
SELECT COUNT(${field_to_count}$), ${show_field}$
2
FROM ${table_name}$
3
GROUP BY ${group_field}$;

This will return the number of employees that have the same description value.

Entering parameter values for count data query

↑  Entering parameter values for count data query

Executing the count data query

↑  Executing the count data query

Swapping the Value of Two Columns In a Table

Let’s assume you’ve entered information for two fields and swapped their data incorrectly. To correct this issue, we’ll write a query to automatically switch the data in those two columns using the UPDATE command. Here is the query:

1
UPDATE employees
2
SET description=company_name, company_name=description
Entering parameter values for the swap columns query

↑  Entering parameter values for the swap columns query

Executing swap columns query

↑  Executing swap columns query

Returning Unique Values

Imagine for a moment that our data entry operator accidentally added duplicate data to the database table several times. To select only distinct (unique) values from the table, we will use SELECT DISTINCT to build a list of distinct data entries to solve the issue using the DISTINCT command:

1
SELECT DISTINCT ${distinct_field}$, ${show_field}$
2
FROM employees
Entering parameter values for the distinct data query

↑  Entering parameter values for the distinct data query

Executing the distinct data query

↑  Executing the distinct data query

Limiting Retrieved Data

If our database has thousands or even millions of entries and we want to limit the number of rows that are retrieved, we can use the LIMIT clause to tell MySQL a specific number of rows to return. This is what we are doing in this example:

1
SELECT * FROM ${table_name}$
2
LIMIT ${top_limit}$;
Entering parameter values for the LIMIT query

↑  Entering parameter values for the LIMIT query

Executing the LIMIT query

↑  Executing the LIMIT query

Problems Solved

In the examples above, we converted some of our regular SQL queries into reusable versions by making their variables configurable using DbVisualizer’s features. But why should we make our queries reusable? Here are some benefits:

  1. The variable and script features work together to allow us to develop SQL query templates, saving you time writing repetitive code and making your SQL much easier to understand.
  2. Writing reusable SQL queries also guarantees that your software adheres to a set standard, allowing you to create high-quality queries consistently.
DbVisualizer SQL Client.

Conclusion

Today we took one step forward toward the database performance highway by building more performant applications with the help of DbVisualizer. Feel free to play around with DbVisualizer and learn more from the documentation, and feel free to reach out to me on LinkedIn if you have any questions.

About the author
Ochuko Onojakpor.
Ochuko Onojakpor
Ochuko is a full-stack Python/React software developer and freelance Technical Writer. He spends his free time contributing to open source and tutoring students on programming in collaboration with Google DSC.
SIGN UP TO RECEIVE THE TABLE'S ROUNDUP
More from the table
TITLE
AUTHOR
Gayatri Sachdeva
TAGS
DBA'S
DronaHQ
TITLE
AUTHOR
Lukas Vileikis
TAGS
MySQL
TITLE
AUTHOR
Bonnie
TAGS
Generation
TITLE
AUTHOR
Bonnie
TAGS
Joins
TITLE
AUTHOR
Igor Bobriakov
TAGS
MySQL
Security
TITLE
AUTHOR
Lukas Vileikis
TAGS
MySQL
Operators
TITLE
AUTHOR
Lukas Vileikis
TAGS
MySQL
NULL
TITLE
AUTHOR
Lukas Vileikis
TAGS
MySQL
Reserved words
TITLE
AUTHOR
Igor Bobriakov
TAGS
Oracle
TITLE
AUTHOR
Antonello Zanini
TAGS
DELETE
TITLE
AUTHOR
Antonello Zanini
TAGS
PostgreSQL
TITLE
AUTHOR
Antonello Zanini
TAGS
PostgreSQL
MySQL
TITLE
AUTHOR
Antonello Zanini
TAGS
PostgreSQL
JSON
TITLE
AUTHOR
Antonello Zanini
TAGS
PostgreSQL
Null
TITLE
AUTHOR
Antonello Zanini
TAGS
Driver
JDBC
ODBC
TITLE
AUTHOR
Antonello Zanini
TAGS
PostgreSQL
Connection
TITLE
AUTHOR
Lukas Vileikis
TAGS
Deduplication
TITLE
AUTHOR
Ochuko Onojakpor
TAGS
SQL
Functions
TITLE
AUTHOR
Lukas Vileikis
TAGS
MySQL
Math
TITLE
AUTHOR
Ochuko Onojakpor
TAGS
Docker
MySQL
TITLE
AUTHOR
Ochuko Onojakpor
TAGS
Views
TITLE
AUTHOR
Lukas Vileikis
TAGS
MySQL
Index
TITLE
AUTHOR
Bonnie
TAGS
BigQuery
TITLE
AUTHOR
Leslie S. Gyamfi
TAGS
Join
TITLE
AUTHOR
Antonello Zanini
TAGS
PostgreSQL
TITLE
AUTHOR
Leslie S. Gyamfi
TAGS
PostgreSQL
TITLE
AUTHOR
Ochuko Onojakpor
TAGS
PrestoDb
TITLE
AUTHOR
Ochuko Onojakpor
TAGS
Ansible
Automation
TITLE
AUTHOR
Antonello Zanini
TAGS
PostgreSQL
TITLE
AUTHOR
Leslie S. Gyamfi
TAGS
PostgreSQL
NoSQL
JSON
TITLE
AUTHOR
Igor Bobriakov
TAGS
Oracle
Data types
TITLE
AUTHOR
TheTable
TAGS
ElasticSearch
TITLE
AUTHOR
Ochuko Onojakpor
TAGS
Security
TITLE
AUTHOR
Lukas Vileikis
TAGS
Language
Design
TITLE
AUTHOR
Lukas Vileikis
TAGS
CRUD
DELETE
TITLE
AUTHOR
Lukas Vileikis
TAGS
CRUD
UPDATE
TITLE
AUTHOR
Lukas Vileikis
TAGS
CRUD
SELECT
TITLE
AUTHOR
Lukas Vileikis
TAGS
CRUD
INSERT
TITLE
AUTHOR
Lukas Vileikis
TAGS
MySQL
TITLE
AUTHOR
Leslie S. Gyamfi
TAGS
PostgreSQL
TITLE
AUTHOR
TheTable
TAGS
Bug
TITLE
AUTHOR
Lukas Vileikis
TAGS
MySQL
Daemon
TITLE
AUTHOR
Lukas Vileikis
TAGS
MySQL
Partitions
TITLE
AUTHOR
Leslie S. Gyamfi
TAGS
Migration
MySQL
PostgreSQL
TITLE
AUTHOR
Antonello Zanini
TAGS
PostgreSQL
hstore
TITLE
AUTHOR
TheTable
TAGS
SQL
TITLE
AUTHOR
Igor Bobriakov
TAGS
SQL server
Security
TITLE
AUTHOR
Ochuko Onojakpor
TAGS
Visualize
TITLE
AUTHOR
TheTable
TAGS
MySQL
TITLE
AUTHOR
Lukas Vileikis
TAGS
SQL
Security
TITLE
AUTHOR
Antonello Zanini
TAGS
PostgreSQL
TITLE
AUTHOR
TheTable
TAGS
PostgreSQL
Docker
TITLE
AUTHOR
Antonello Zanini
TAGS
PostgreSQL
TITLE
AUTHOR
Lukas Vileikis
TAGS
MySQL
Connection
TITLE
AUTHOR
Lukas Vileikis
TAGS
Performance
TITLE
AUTHOR
Lukas Vileikis
TAGS
Security
TITLE
AUTHOR
Antonello Zanini
TAGS
Columns
TITLE
AUTHOR
Ochuko Onojakpor
TAGS
Performance
TITLE
AUTHOR
Ochuko Onojakpor
TAGS
SQL
TITLE
AUTHOR
Lukas Vileikis
TAGS
Performance
Indexes
TITLE
AUTHOR
Lukas Vileikis
TAGS
MySQL
Subquery
TITLE
AUTHOR
Lukas Vileikis
TAGS
Performance
TITLE
AUTHOR
Lukas Vileikis
TAGS
ACID
TITLE
AUTHOR
Lukas Vileikis
TAGS
ALTER TABLE
TITLE
AUTHOR
TheTable
TAGS
MySQL
Ports
TITLE
AUTHOR
Lukas Vileikis
TAGS
MySQL
Security
TITLE
AUTHOR
Lukas Vileikis
TAGS
ACID
MySQL
Security
TITLE
AUTHOR
Antonello Zanini
TAGS
BLOB
TITLE
AUTHOR
TheTable
TAGS
Foreign Key
PostgreSQL
TITLE
AUTHOR
Leslie S. Gyamfi
TAGS
PostgreSQL
Concurrency
TITLE
AUTHOR
Lukas Vileikis
TAGS
Security
Encryption
TITLE
AUTHOR
Lukas Vileikis
TAGS
Security
TITLE
AUTHOR
Bonnie
TAGS
Security
PostgreSQL
TITLE
AUTHOR
Antonello Zanini
TAGS
Subquery
TITLE
AUTHOR
Antonello Zanini
TAGS
Transactions
TITLE
AUTHOR
Ochuko Onojakpor
TAGS
Data structures
TITLE
AUTHOR
Antonello Zanini
TAGS
MySQL
TITLE
AUTHOR
Lukas Vileikis
TAGS
SSH
TITLE
AUTHOR
Antonello Zanini
TAGS
Stored procedure
MySQL
TITLE
AUTHOR
Antonello Zanini
TAGS
Triggers
TITLE
AUTHOR
Igor Bobriakov
TAGS
Microsoft SQL Server
Optimization
TITLE
AUTHOR
Bonnie
TAGS
PostreSQL
TITLE
AUTHOR
Ochuko Onojakpor
TAGS
Reusable queries
TITLE
AUTHOR
Antonello Zanini
TAGS
BIG Data
TITLE
AUTHOR
Lukas Vileikis
TAGS
MySQL
Security
TITLE
AUTHOR
TheTable
TAGS
Beginner
SQL
TITLE
AUTHOR
Ochuko Onojakpor
TAGS
CRUD
SQL Transactions
TITLE
AUTHOR
Lukas Vileikis
TAGS
MySQL
Security
TITLE
AUTHOR
Antonello Zanini
TAGS
PostgreSQL
JSON
TITLE
AUTHOR
Lukas Vileikis
TAGS
MySQL
InnoDB
ibdata1
TITLE
AUTHOR
Lukas Vileikis
TAGS
MySQL
TITLE
AUTHOR
Scott A. Adams
TAGS
Filter
TITLE
AUTHOR
Scott A. Adams
TAGS
SQLite
TITLE
AUTHOR
Scott A. Adams
TAGS
Excel
Export
TITLE
AUTHOR
Scott A. Adams
TAGS
ERD
Join

The content provided on dbvis.com/thetable, including but not limited to code and examples, is intended for educational and informational purposes only. We do not make any warranties or representations of any kind. Read more here.