How to Write Complex SQL Sub-query

Here is a complex sub-query on how to write it using two tables explained. One is the customer table, and the other one is the order table.

Sub-queries are two types. Single row return and Multiple-row return. Below is the multiple-row return example that explains in detail.

Complex sub query

Sub-query Question

A subquery should get everything from the Customer_Table if the customer has an order in the Order_Table of greater than $400.

Customer_Table

CUstomer_numberCustomer_name
123Rao
567Kyte
897Robo
901Tup
991Vek
Advertisements

Order_table

Order_numberCustomer_numberOrder_total
1001123100.76
1002567200
1003897310
1004901450
1005991566

Here is Sub-query

select *
from customer_table
where customer_number in
(select customer_number
from order_table
where order_total > 400);

How it works

The sub-query is inside the parenthesis. First, it gets the customer_number from the order_table (the order_total greater than 400).

The outer query gets all the details of customer_table for all the matching customer numbers.

Summary

I chose to use sub-query, which ultimately reduced complexity, and we got the desired result.

Related posts

Get new content delivered directly to your inbox.

Tony Robbins Vocabulary: 50 Powerful Words and Phrases to Improve Your English

Learn 50 powerful Tony Robbins vocabulary words and phrases with simple meanings and example sentences to improve your English speaking skills

Migrating JSON Files from AWS S3 to PostgreSQL Using AWS Glue and PySpark

Migrating JSON files from AWS S3 to PostgreSQL using AWS Glue and PySpark is one of the most common data engineering challenges teams face today. In this guide, you will learn exactly how to build a production-grade AWS Glue JSON to PostgreSQL migration pipeline — from reading raw JSON files in S3 to writing clean,…

5 PySpark Performance Anti-Patterns on Databricks (And How to Fix Them)

Databricks makes scaling big data processing feel almost effortless. Under the hood, however, writing PySpark without understanding how Apache Spark and Delta Lake execute your code can quietly ruin performance, spike DBU costs, and cause out-of-memory (OOM) crashes. Below are 5 common PySpark anti-patterns seen in production, along with exact code fixes to keep your…

Discover more from Srinimf

Subscribe now to keep reading and get access to the full archive.

Continue reading