Deep Dive into Advanced SQL Techniques with Examples

Despite its origins in the 1970s, SQL continues to be a vital skill for data science professionals, with demand for it projected to grow even more in the job market. Its enduring relevance can be attributed to its robust capabilities in handling big data, making it particularly effective for organizing and analyzing information.

Although SQL may not be as user-friendly as some modern tools, it excels as a versatile solution throughout the entire data lifecycle. From storing collected data in databases to cleaning, organizing, visualizing and modeling data.

SQL remains an indispensable tool in the field.

In this article we will explore 10 advanced features in SQL using MariaDB.

Maria DB Sample Database

The sample data can be found here. The nation database has 6 tables with information on countries, regions, languages, and statistics.

Schema for the nation database.

Database Client Tool

We will use database-client extension in VS Code.

Database client that improves productivity for users.

1. Access data from multiple tables – Joins

Using joins to fetch associated records in a single query is one of the ways to solve the N+1 problem. This reduces the number of queries from N+1 to just 1, improving performance by minimizing database load and query execution time. There are many types of join, but our example will use an inner join to list all languages spoken in Bangladesh.

2. Combines results of multiple queries – Unions

UNION is used to combine the results from multiple SELECT statements into a single result set. In this example, we list countries that speak French and countries that speak Italian in one result set.

3. Perform multi-step operations – Subqueries

We may also rewrite the previous query using a subquery in the WHERE clause to fetch the country_id for “Bangladesh” before joining.

4. Aggregation Functions

Aggregate functions are functions that are computed over a sequence of rows and return one result for the sequence of rows e.g. count,sum,max,min. You can also creating a custom aggregate function, see User defined functions section below.

Example showing countries that speak both French and Italian, using the count/having approach.

5. Common Table Expressions (CTEs)

Common Table Expressions (CTEs) are essentially temporary named result sets. They can also be recursive, see Recursive Queries section below.

In this example we list countries whose population is above the average population of all the countries in the country_stats table. i.e.30,041,784.

6. Recursive Queries

CTEs permit a query to reference itself. A recursive CTE will repeatedly execute subsets of the data until it obtains the complete result set. This makes it particularly useful for handing hierarchical or tree-structured data.

In the example below, we gather all countries in a specific continent and aggregate their GDP and population by language.

7. Conditional Logic – Case

This works like an IF-THEN-ELSE statement. In this example, we categorize countries into three categories based on their GDP: “Low GDP“, “Medium GDP“, and “High GDP“.

8. Reusable modules – User defined functions

We can convert the CASE statement above into a reusable function called categorize_gdp

We can the use the function categorize_gdp it in our query as follows.

9. Temporary tables

Temporary tables can be an effective way to enhance the performance of complex or resource-heavy queries. By dividing a complex query into several steps and utilizing temporary tables, you can boost efficiency by minimizing the data processed at each step or by calculating intermediate/transient results in advance.

This example will analyze the GDP and population data for countries within a specific continent, Africa in this case, grouped by region and further analyzed by the official languages spoken in those regions.

Lastly, join the 2 tables for the final result.

10. Transactions

An SQL-transaction (transaction) is a sequence of executions of SQL-statements that is atomic with respect to recovery. That is to say: either the execution result is completely successful, or it has no effect on any SQL-schemas or SQL-data.

Consider a scenario when updating the GDP and population for a country, and at the same time, inserting a new language for that country. If either operation fails, the database should roll back to its previous state to prevent data inconsistencies.

Since MariaDB

11. Query Optimization Techniques

Covered in a separate post MariaDB Query Optimization Strategies.

Conclusion

The techniques we’ve explored here are just the tip of the iceberg when it comes to the power and versatility of SQL. Each concept offers a pathway to more efficient and sophisticated data handling, but there is always more to uncover with real-world data scenarios.