Introduction to Writing SQL Queries
Explore the fundamentals of writing SQL queries within application code, including best practices for formatting, debugging, and maintaining code. Understand the role of ORM, business logic considerations, and the importance of indexing strategies for effective database interactions with PostgreSQL.
We'll cover the following...
Now, we’re going to learn how to write SQL queries. There are several ways to accomplish this, both from the SQL syntax and semantics points of view, which will be covered later. Here, we want to address how to write SQL queries as part of our application code.
Object-relational mapping (ORM)
Some developers prefer to use an
Also, to debug what happens in production, we need to be able to easily spot where the query comes from, replay it, edit it, and update our code with the new fixed version of the query.
Writing software
Before we go into detail about the specifics of those concerns, it might be a good idea to review how SQL actually helps us write software, what parts of the code we’re writing in the database layer, and how much we can or should be writing. The question is this: Is SQL a good place to implement business logic?
Next, to get a more concrete example of the correct way to implement SQL queries in our code, we’re going to have a detailed look at a very simple application to work with a specific codebase.
After that, we’ll see those tools and habits that will help us use SQL in our daily lives. In particular, this chapter introduces the concept of indexing strategy and explains why this task is essential for an application developer.