Subqueries and EXISTS in MariaDB
Last Updated :
16 Feb, 2024
Subqueries and EXISTS are powerful tools in MariaDB that enable us to write complex and efficient queries. Subqueries allow us to nest one query inside another and provide a flexible way to retrieve data. The EXISTS operator, on the other hand, it checks for the existence of rows returned by a subquery. In this article, we will look at what subqueries are, how they work, and how the EXISTS operator can be used to extend their functionality in MariaDB.
What are Subqueries?
A subquery, commonly referred to as a nested or inner query, is a query within another SQL statement, such as SELECT, INSERT, UPDATE, and DELETE that sometimes references an outer query. Rather, a subquery's outcome can be utilized in different parts of the main query including the WHERE clause, FROM clause, or another subquery.
Syntax:
SELECT column1 FROM table1 WHERE column2 = (SELECT column3 FROM table2 WHERE condition);
Explanation: In this syntax, the subquery (SELECT column3 FROM table2 WHERE condition) is enclosed within parentheses and returns a single value. This value is then compared to column2 in the outer query's WHERE clause.
What is an EXISTS Operator?
The EXISTS operator makes the subquery returns only the records that are present in the result set of the of query. It will return TRUE if the sub-query has one or more rows, if not it will return FALSE. EXISTS operator is regularly employed in conjunction with correlated sub-queries, where the first query is related to outer columns.
Syntax:
SELECT column1 FROM table1 WHERE EXISTS (SELECT * FROM table2 WHERE table2.column = table1.column);
Explanation: In the above Syntax, the EXISTS operator checks whether there are any rows in table2 that match the condition specified in the subquery. If at least one row exists, the outer query returns true.
Examples of Subqueries with Exists Operator
Here are the some examples of using subqueries with exists operator:
Let's first create table and insert values into it.
Create table customers:
CREATE TABLE customers (
customers_id INT AUTO_INCREMENT PRIMARY KEY,
name VARCHAR(50),
age INT
);
Insert data:
INSERT INTO customers (name, age) VALUES
('Minal', 25),
('Harsha', 30),
('Asad', 35),
('Mridul', 40);
Output:
Customers TableExplanation: As we can see our table got created successfully.
Create table orders.
CREATE TABLE orders(
order_id INT AUTO_INCREMENT PRIMARY KEY,
customers_id INT,
order_date DATE,
total_amount DECIMAL(10, 2),
FOREIGN KEY (customers_id) REFERENCES customers(customers_id)
);
Insert data:
INSERT INTO orders (customers_id, order_date, total_amount) VALUES
(1, '2024-01-01', 50.00),
(2, '2022-01-19', 100.00),
(3, '2024-01-15', 150.00),
(4, '2021-01-04', 200.00);
Output:
Orders TableExplanation: As we can see table got created successfully.
Example 1: Using EXISTS to Find Customers Older Than 30.
This query provides the names of customers who have placed orders but are more than 30 years old.
Query:
SELECT NAME FROM customers c WHERE EXISTS
(SELECT * FROM orders WHERE customers_id = c.customers_id) AND c.age > 30;
Output:
Example 1Explanation:
- SELECT NAME FROM customers c: It selects the name column from the customers table and as customers the aliases.
- WHERE EXISTS (SELECT * FROM orders WHERE customers_id = c.customers_id): This is a subquery that checks if there exists at least one record in the orders table where the customers_id matches the customers_id of the outer query (c.customers_id). It checks if the customer has any orders.
- AND c.age > 30: Such a condition restricts the result set to only include customers whose age (c.age) is greater than 30.
Example 2: Using EXISTS to Find Customers Whose Name Starts with 'M'
It finds the customers' names that have the first letter ‘M’ and who has at least one other customers with the same name beginning with ‘M’.
Query:
SELECT name FROM customers u WHERE EXISTS
(SELECT * FROM customers WHERE name LIKE 'M%' AND customers_id = u.customers_id);
Output:
Example 2Explanation:
- SELECT name FROM customers u: This will select the name column from the customer table and aliases it as u.
- WHERE EXISTS (SELECT * FROM customers WHERE name LIKE 'M%' AND customers_id = u.customers_id): This is the subquery that illustrates if at least one other customer and who is a group other than the one in the outer query, the name of which begins with 'M' and customers_ids matches the customers_ids of the outer one.
- The subquery displays customers with beginning with 'M' and interactions from the same interactions_id value of the customer in the outer query.
- Hence, if there is such an having to carry out then the EXISTS condition is met and the outer query (u.name ) is contained in the final result set.
Example 3: Using EXISTS to Find Customers Who have Made Orders with a Total Amount Greater Than 100.
This SQL query fetches names of customers who have made orders with a total sum greater than $100.
Query:
SELECT name FROM customers u WHERE EXISTS
(SELECT * FROM orders WHERE customers_id = u.customers_id AND total_amount > 100);
Output:
Example 3Explanation:
- SELECT name FROM customers u: This selects the name field from the customers table and aliases it as u.
- WHERE EXISTS (SELECT * FROM orders WHERE customers_id = u.customers_id AND total_amount > 100): This is a the query and subquery inherently is that one or more than one record exists in the orders list if the following holds:
- The equivalent of the subquery's customers_id (u.customers_id) is equal to the customers' id of the outer query.
- The the quantity of the entire order is larger than $100 (100<amount_total).
- This will involve the access of a record, satisfying the 'IF' condition in our outer query, and the customer's name (u.name) will also be fetched along.
Example 4: Using EXISTS to Find Customers Who have Made Orders in January 2024.
This query will only fetch those clients whose orders were placed in January 2024.
Query:
SELECT name FROM customers u WHERE EXISTS
(SELECT * FROM orders WHERE customers_id = u.customers_id
AND
YEAR(order_date) = 2024 AND MONTH(order_date) = 1);
Output:
Example 4Explanation:
- SELECT name FROM customers u: This is the outer query that selects the name column from the customers table and this becomes the u alias.
- WHERE EXISTS (SELECT * FROM orders WHERE customers_id = u.customers_id AND YEAR(order_date) = 2024 AND MONTH(order_date) = 1): This is a subquery, which is looking for the order_id, if there is the at least one record in the orders table for which (order_id):
- The joins_statement.customers_id = u.customers_id, which is a matching square cabinet of the queries to the outer query (u.customers_id).
- We shall find the order date in January of 2024. This query will check whether the user gives correct order month and year by casting order date Year() and order_date Month() and compare them with 2024 and 1 respectively.
- If the above mentioned record is there, EXISTS condition will be satisfied and the outer query will include customer name (u.name) in the final result set.
Advantages of Subqueries and EXISTS Operator
- Modularity: Subqueries provide code encapsulation resulting in easier to understand complex queries.
- Improved Performance: If carefully optimized, subqueries improve query performance because the database engine executes the inner query and then uses its result further.
- Conditional Filtering: EXISTS is used to filter rows conditionally based on the existence of rows in a subquery result, which makes query construction flexible.
Conclusion
Subqueries and EXISTS operator are important parts of MariaDB which allow developers to write powerful SQL queries. Through the knowledge of how to invoke subqueries and EXISTS you can make your database operations easier to read and more flexible in addition to faster. Practice with the presented ideas in your own projects in order to gain their full advantage and improve your SQL queries.
Similar Reads
MariaDB Subqueries
MariaDB utilizes SQL, a structured query language, as an open-source Relational database management system (RDBMS). It manages and manipulates data efficiently. One powerful function that contributes to the flexibility of MariaDB is using subqueries. This article will focus on MariaDB subqueries. We
5 min read
MariaDB Unique Index
MariaDB is a fast, scalable, open-source community-supported relational database management system thatâs also an enhanced version of MySQL. Content management systems (CMS) are a key application of MariaDB. A CMS is a publication system through which web creators can push and manage large quantitie
5 min read
Unique Constraint in MariaDB
MariaDB uses relational databases similar to SQL. SQL is the precedence of MariaDB similar to the SQL mariaDB also uses some of the querying language to process through the databases. The main advantage of the MariaDB is that it runs on various operating systems and supports many programming languag
7 min read
WHERE Clause in MariaDB
MariaDB uses SQL (Structured Query Language) and it is an open-source relational database management system (RDBMS) for managing and manipulating data. The WHERE clause in SQL queries is used to filter and obtain specific data. The ability to remove and retrieve specific data using the WHERE clause
3 min read
IN vs EXISTS in SQL
SQL stands for Structured Query Language. SQL is used for retrieving useful information from a large set of data and it is used for storing the data in the Database, modifying, or manipulating the data from the database. In this article, we are going to discuss IN Operator and EXISTS Operator in SQL
5 min read
MariaDB - Regular Expression
MariaDB is also a relational database language that is similar to SQL. However, the introduction of MariaDB took place as it is an extension to SQL and contains some more advanced operators rather than SQL. MariaDB contains operators similar to SQL like CRUD operations and between operators and othe
8 min read
Declaring Variable in MariaDB
Variables serve as essential components in database management systems like MariaDB facilitating the storage and manipulation of data within the database environment. Variable declaration in MariaDB is a fundamental concept, allowing users to store values temporarily, perform calculations, and strea
4 min read
Alter Table in MariaDB
MariaDB is an open-source RDBMS, that offers an extensive collection of features for handling database structures effectively. One important part of database management is changing tables to meet needs or improve performance. The ALTER TABLE command in MariaDB assists in these changes, allowing user
5 min read
Quote in MariaDB
Quotes play a crucial role in MariaDB, the open-source relational database management system known for its speed and reliability. Whether you're a beginner or an experienced user, understanding how to use quotes effectively can enhance your database management skills. In this article, we will learn
3 min read
INSERT RETURNING in MariaDB
MariaDB, an open-source relational database management system, continues to evolve with new features and enhancements. One such feature introduced in version 10.5 is the INSERT...RETURNING statement, which offers a convenient and efficient way to insert data into a table and retrieve the inserted ro
3 min read