Writing Reusable SQL Queries For Your Application with DbVisualizer Scripts
Tags: sql
Published: 2023-02-23 07:00:00

**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.**

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."
<br />

![The database tree](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/5y6qi7fa42gwhs3kfr1r.png)
<figure><figcaption>The database tree</figcaption></figure>
<br />
## 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.
<br />

![Showing the add script icon](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/nopxc8q4mm44cdel3r7i.png)
<figure><figcaption>Showing the add script icon</figcaption></figure>
<br />
It will open up a SQL commander tab where you can write your queries.
<br />

![The SQL commander tab](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/g77xzunqxd9c2t59x156.png)
<figure><figcaption>The SQL commander tab</figcaption></figure>
<br />
Step 2: After writing your queries, click on the blue diskette icon to name your script and save it.

![Showing the blue diskette icon](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/xbtypcfjtzl9qgjm4t69.png)
<figure><figcaption>Showing the blue diskette icon</figcaption></figure>
<br />
Step 3: You can view all your saved scripts in your bookmarks.

![Showing the saved scripts in bookmarks tab](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/y51ncyhv09mjp9vi4eum.png)
<figure><figcaption>Showing the saved scripts in bookmarks tab</figcaption></figure>
<br />

## 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:
<br />

## 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:

```
CREATE TABLE `employees` (
`serial_number` varchar(100) NOT NULL,
`company_name` varchar(100) DEFAULT NULL,
`employee_markme` varchar(100) DEFAULT NULL,
`description` varchar(100) DEFAULT NULL,
`leave` varchar(100) DEFAULT NULL,

PRIMARY KEY (`serial_number`),
UNIQUE KEY `serial_number` (`serial_number`),
),;
```
Copy the query above into the SQL commander tab and click on the play icon to execute it.

![Executing the create table query script](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/vbtipf7kzyuo7ji4d4jz.png)
<figure><figcaption>Executing the create table query script</figcaption></figure>
<br />
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:

```
CREATE TABLE `${table_name}$` (
`${first_column}$` varchar(100) NOT NULL,
`${second_column}$` varchar(100) DEFAULT NULL,
`${third_column}$` varchar(100) DEFAULT NULL,
`${fourth_column}$` varchar(100) DEFAULT NULL,
`${last_column}$` varchar(100) DEFAULT NULL,

PRIMARY KEY (`${primary_key}$`),
UNIQUE KEY `${unique_key}$` (`${unique_key}$`)
);
```
Executing the query above creates the prompt in the image below.


![Entering parameter values in the create table query](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/fk4mh2ct8ybbglsoo1ge.png)
<figure><figcaption>Entering parameter values in the create table query</figcaption></figure>
<br />
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](https://docs.google.com/uc?export=download&id=1W3Yb8Fr8WA8yU6zjjsvPJ8D1h_LYDzIL). 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](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/mh46zpa9xfi7agfpxelw.png)
<figure><figcaption>Selecting database to import table data</figcaption></figure>
<br />
Now select the CSV file in the file directory as shown in the image below:

![Choosing CSV file in directory](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/jk6q1s54q6vftd97bl33.png)
<figure><figcaption>Choosing CSV file in directory</figcaption></figure>
<br />
Continue clicking “Next >” until you get to the “Import” button.

![Importing the CSV file into the table](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/9zqfgoba20ebkhidzbw3.png)
<figure><figcaption>Importing the CSV file into the table</figcaption></figure>
<br />
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](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/eaybtusw6nu9cg8c4i5b.png)
<figure><figcaption>Import success message</figcaption></figure>
<br />

## 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:

```
SELECT COUNT(${field_to_count}$), ${show_field}$
FROM ${table_name}$
GROUP BY ${group_field}$;
```
This will return the number of employees that have the same description value.

![Entering parameter values for count data query](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/8x1lvq0trp9s0yst4x64.png)
<figure><figcaption>Entering parameter values for count data query</figcaption></figure>
<br /> 
<br />

![Executing the count data query](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/gvvu9felz80qzpyqnnnl.png)
<figure><figcaption>Executing the count data query</figcaption></figure>
<br />
<br />

## 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:

```
UPDATE employees
SET description=company_name, company_name=description
```
![Entering parameter values for the swap columns query](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/drne75svxmr93tv7eiwl.png)
<figure><figcaption>Entering parameter values for the swap columns query</figcaption></figure>
<br />

![Executing swap columns query](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/x3rgvq20mh4vsg3n8h4n.png)
<figure><figcaption>Executing swap columns query</figcaption></figure>
<br />

## 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:

```
SELECT DISTINCT ${distinct_field}$, ${show_field}$
FROM employees
```

![Entering parameter values for the distinct data query](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/smiq4xza0z3wirvjljen.png)
<figure><figcaption>Entering parameter values for the distinct data query</figcaption></figure>
<br />

![Executing the distinct data query](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/3g0ujhb8vl76ol0g5mfs.png)
<figure><figcaption>Executing the distinct data query</figcaption></figure>
<br />

## 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:

```
SELECT * FROM ${table_name}$
LIMIT ${top_limit}$;
```

![Entering parameter values for the LIMIT query](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/x22vh1x899e690zorz40.png)
<figure><figcaption>Executing the distinct data query</figcaption></figure>
<br />

![Executing the LIMIT query](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/d6gswla8735uoxzl15i7.png)
<figure><figcaption>Executing the LIMIT query</figcaption></figure>
<br />

## 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.

## 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](https://confluence.dbvis.com/display/UG140/Getting+Started?_gl=1*1ocpgt7*_ga*NjI4NzAzMTQ5LjE2MzUxNDg0MTM.*_ga_PTZV59MQGC*MTY3NjM3OTcyOC40NTIuMS4xNjc2Mzc5ODg1LjAuMC4w&_ga=2.252040585.1614933826.1676285297-628703149.1635148413), and feel free to reach out to me on [LinkedIn](https://www.linkedin.com/in/ochuko-onojakpor-5a156515b/) if you have any questions.

## About the author
Ochuko Onojakpor 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.