DEV Community

Kovid Rathee
Kovid Rathee

Posted on

2

Defensive SQL Query Writing

Derived from defensive programming, defencive query writing is a practice which tries to make sure that a query run doesn't fail. Just like in application development, try to remove the scope for silly mistakes and control unforseen circumstances. Sometimes the decision comes down to whether you want your query to fail or you want it to run even if with some incorrect data. I'll share a couple of simple examples where we can employ these practices while writing queries.

Checking If Objects Exist

Take the very basic example of creating and dropping database objects. Rather than using a CREATE TABLE xyz, use CREATE TABLE IF NOT EXISTS xyz (id int) or if you want to recreate the table losing all the data you can run DROP TABLE IF EXISTS xyz and then CREATE TABLE IF NOT EXISTS xyz (id int).

The same practice can be used with the creation and deletion of databases, views, indexes, triggers, procedures, functions and more. I have come to realize that in most cases, using this is helpful.

Using database and column aliases

Prevent yourself from getting ambiguous column errors. See in the example below, the column city might be present both in TABLE_1 and TABLE_2. How do you expect the database to know which field you want it to pick up.

SELECT city,
FROM TABLE_1 AS t1
LEFT JOIN TABLE_2 as t2
ON t1.id = t2.id;

It's generally a very good practice to create aliases for database objects and then access those database objects and their child objects using the alias rather than the complete name. Obviously for doing this efficiently, you'd need to follow a SQL Style Sheet.

Using LIMIT

No, I'm not talking about using LIMIT to restrict the number of records in your final query. Rather, I am talking about queries like this.

SELECT t1.*,
(SELECT t2.field_name
FROM TABLE_2 AS t2
WHERE t1.id = t2.id
LIMIT 1
)
FROM TABLE_1 AS t1

The LIMIT clase in the subquery returning a column is important because it prevents the query from failing if the subquery returns more than one row, that is, if there is more than one record in TABLE_2 for every record in TABLE_1. This is a really useful trick to write better queries.

These are three of the most common scenarios which, if not taken care of, can prevent your query from running at all. Obviously, all of these come with an asterix. More on that later.

Please feel free to share other practices that you have followed!

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 (2)

Collapse
 
buinauskas profile image
Evaldas Buinauskas

The second query might prevent query from failing, but subquery returning more than a single row might be a bug in the data model and using LIMIT could be hiding that.

Collapse
 
kovidr profile image
Kovid Rathee

@Evaldas - You're right. I mentioned that. That's why it must be used carefully!

AWS Security LIVE!

Join us for AWS Security LIVE!

Discover the future of cloud security. Tune in live for trends, tips, and solutions from AWS and AWS Partners.

Learn More

👋 Kindness is contagious

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

Okay