MySql - Subqueries in SELECT, INSERT, UPDATE, and DELETE

MySQL Subqueries - Detailed Notes

Subqueries in MySQL

Key Characteristics of Subqueries

  • Nested Structure: A subquery is executed within the context of an outer query.
  • Parentheses: Subqueries must always be enclosed in parentheses ().
  • Comparison Operators: Subqueries can be used with operators like =, >, <, IN, NOT IN, EXISTS, etc.
  • Single-Row vs. Multi-Row Subqueries: Subqueries may return a single value or multiple values, affecting how they can be used in the outer query.

Subqueries in SELECT Statements

Subqueries are commonly used in SELECT statements to filter data based on the results of another query.

Example: Employees in USA Offices


SELECT 
    lastName, firstName
FROM
    employees
WHERE
    officeCode IN (SELECT 
                       officeCode
                   FROM
                       offices
                   WHERE
                       country = 'USA');

In this example, the subquery retrieves the office codes for offices located in the USA. The outer query then selects employees who work in those offices.

Subqueries in INSERT Statements

Subqueries can be used in INSERT statements to insert data retrieved from another table.

Example: Copying Data to a Backup Table


INSERT INTO products_bkp (product_id, product_name, price)
SELECT product_id, product_name, price
FROM products
WHERE category = 'Electronics';

This query copies all electronic products from the products table into the products_bkp backup table.

Subqueries in UPDATE Statements

Subqueries can be used in UPDATE statements to update records based on data from another table.

Example: Updating Prices Based on Average


UPDATE products
SET price = price * 1.1
WHERE price < (SELECT AVG(price) FROM products);

This query increases the price by 10% for all products priced below the average price.

Subqueries in DELETE Statements

Subqueries can be used in DELETE statements to delete records based on conditions derived from another query.

Example: Deleting Inactive Customers


DELETE FROM customers
WHERE customer_id NOT IN (
    SELECT DISTINCT customer_id
    FROM orders
    WHERE order_date >= CURDATE() - INTERVAL 1 YEAR
);

This query deletes customers who have not placed any orders in the past year.

Types of Subqueries

  • Scalar Subquery: Returns a single value.
  • Row Subquery: Returns a single row with multiple columns.
  • Table Subquery: Returns multiple rows and columns.
  • Correlated Subquery: References columns from the outer query and is evaluated once for each row processed by the outer query.

Example of a Correlated Subquery


SELECT e1.employee_id, e1.salary
FROM employees e1
WHERE e1.salary > (
    SELECT AVG(e2.salary)
    FROM employees e2
    WHERE e2.department_id = e1.department_id
);

This query selects employees whose salary is above the average salary of their respective departments.

Best Practices

  • Ensure subqueries are optimized for performance, especially correlated subqueries.
  • Use indexes on columns involved in subquery conditions to improve efficiency.
  • Consider rewriting subqueries as joins when appropriate for better performance.

Subqueries are powerful tools in MySQL that allow for complex and dynamic data operations. By understanding how to effectively use subqueries in SELECT, INSERT, UPDATE, and DELETE statements, you can write more efficient and maintainable SQL queries.

logo

MySQL

Beginner 5 Hours
MySQL Subqueries - Detailed Notes

Subqueries in MySQL

Key Characteristics of Subqueries

  • Nested Structure: A subquery is executed within the context of an outer query.
  • Parentheses: Subqueries must always be enclosed in parentheses ().
  • Comparison Operators: Subqueries can be used with operators like =, >, <, IN, NOT IN, EXISTS, etc.
  • Single-Row vs. Multi-Row Subqueries: Subqueries may return a single value or multiple values, affecting how they can be used in the outer query.

Subqueries in SELECT Statements

Subqueries are commonly used in SELECT statements to filter data based on the results of another query.

Example: Employees in USA Offices

SELECT lastName, firstName FROM employees WHERE officeCode IN (SELECT officeCode FROM offices WHERE country = 'USA');

In this example, the subquery retrieves the office codes for offices located in the USA. The outer query then selects employees who work in those offices.

Subqueries in INSERT Statements

Subqueries can be used in INSERT statements to insert data retrieved from another table.

Example: Copying Data to a Backup Table

INSERT INTO products_bkp (product_id, product_name, price) SELECT product_id, product_name, price FROM products WHERE category = 'Electronics';

This query copies all electronic products from the products table into the products_bkp backup table.

Subqueries in UPDATE Statements

Subqueries can be used in UPDATE statements to update records based on data from another table.

Example: Updating Prices Based on Average

UPDATE products SET price = price * 1.1 WHERE price < (SELECT AVG(price) FROM products);

This query increases the price by 10% for all products priced below the average price.

Subqueries in DELETE Statements

Subqueries can be used in DELETE statements to delete records based on conditions derived from another query.

Example: Deleting Inactive Customers

DELETE FROM customers WHERE customer_id NOT IN ( SELECT DISTINCT customer_id FROM orders WHERE order_date >= CURDATE() - INTERVAL 1 YEAR );

This query deletes customers who have not placed any orders in the past year.

Types of Subqueries

  • Scalar Subquery: Returns a single value.
  • Row Subquery: Returns a single row with multiple columns.
  • Table Subquery: Returns multiple rows and columns.
  • Correlated Subquery: References columns from the outer query and is evaluated once for each row processed by the outer query.

Example of a Correlated Subquery

SELECT e1.employee_id, e1.salary FROM employees e1 WHERE e1.salary > ( SELECT AVG(e2.salary) FROM employees e2 WHERE e2.department_id = e1.department_id );

This query selects employees whose salary is above the average salary of their respective departments.

Best Practices

  • Ensure subqueries are optimized for performance, especially correlated subqueries.
  • Use indexes on columns involved in subquery conditions to improve efficiency.
  • Consider rewriting subqueries as joins when appropriate for better performance.

Subqueries are powerful tools in MySQL that allow for complex and dynamic data operations. By understanding how to effectively use subqueries in SELECT, INSERT, UPDATE, and DELETE statements, you can write more efficient and maintainable SQL queries.

Related Tutorials

Frequently Asked Questions for MySQL

Use the command: CREATE INDEX index_name ON table_name (column_name); to create an index on a MySQL table.

To install MySQL on Windows, download the installer from the official MySQL website, run the setup, and follow the installation wizard to configure the server and set up user accounts.

MySQL is an open-source relational database management system (RDBMS) that uses SQL (Structured Query Language) for managing and manipulating databases. It is widely used in web applications for its speed and reliability.

Use the command: INSERT INTO table_name (column1, column2) VALUES (value1, value2); to add records to a MySQL table.

Use the command: mysql -u username -p database_name < data.sql; to import data from a SQL file into a MySQL database.

DELETE removes records based on a condition and can be rolled back, while TRUNCATE removes all records from a table and cannot be rolled back.

A trigger is a set of SQL statements that automatically execute in response to certain events on a MySQL table, such as INSERT, UPDATE, or DELETE.

The default MySQL port is 3306, and the root password is set during installation. If not set, you may need to configure it manually.

Replication in MySQL allows data from one MySQL server (master) to be copied to one or more servers (slaves), providing data redundancy and load balancing.

 A primary key is a unique identifier for a record in a MySQL table, ensuring that no two records have the same key value.

 Use the command: SELECT column1, column2 FROM table_name; to fetch data from a MySQL table.

 Use the command: CREATE DATABASE database_name; to create a new MySQL database.

Use the command: CREATE PROCEDURE procedure_name() BEGIN SQL_statements; END; to define a stored procedure in MySQL.

Indexing in MySQL improves query performance by allowing the database to find rows more quickly. Common index types include PRIMARY KEY, UNIQUE, and FULLTEXT.

Use the command: UPDATE table_name SET column1 = value1 WHERE condition; to modify existing records in a MySQL table.

CHAR is a fixed-length string data type, while VARCHAR is variable-length. CHAR is faster for fixed-size data, whereas VARCHAR saves space for variable-length data.

MyISAM is a storage engine that offers fast read operations but lacks support for transactions, while InnoDB supports transactions and foreign keys, providing better data integrity.

A stored procedure is a set of SQL statements that can be stored and executed on the MySQL server, allowing for modular programming and code reuse.

Use the command: mysqldump -u username -p database_name > backup.sql; to create a backup of a MySQL database.

Use the command: DELETE FROM table_name WHERE condition; to remove records from a MySQL table.

A foreign key is a column or set of columns in one MySQL table that references the primary key in another, establishing a relationship between the two tables.

Use the command: CREATE TRIGGER trigger_name BEFORE INSERT ON table_name FOR EACH ROW BEGIN SQL_statements; END; to create a trigger in MySQL.

Normalization in MySQL is the process of organizing data to reduce redundancy and improve data integrity by dividing large tables into smaller ones.

JOIN is used to combine rows from two or more MySQL tables based on a related column, allowing for complex queries and data retrieval.

Use the command: mysqldump -u username -p database_name > backup.sql; to export a MySQL database to a SQL file.

line

Copyrights © 2024 letsupdateskills All rights reserved