A MySQL subquery is a query that is nested inside another query such as SELECT, INSERT, UPDATE or DELETE. A MySQL subquery is also can be nested inside another subquery. A MySQL subquery is also called an inner query, while the query that contains the subquery is called an outer query.
Subqueries can be used with the SELECT, INSERT, UPDATE, and DELETE statements along with the operators like =, <, >, >=, <=, IN, BETWEEN etc.
There are a few rules that subqueries must follow:
- Subqueries must be enclosed within parentheses.
- A subquery can have only one column in the SELECT clause unless multiple columns are in the main query for the subquery to compare its selected columns.
- An ORDER BY cannot be used in a subquery, although the main query can use an ORDER BY. The GROUP BY can be used to perform the same function as the ORDER BY in a subquery.
- Subqueries that return more than one row can only be used with multiple value operators, such as the IN operator.
- The SELECT list cannot include any references to values that evaluate to a BLOB, ARRAY, CLOB, or NCLOB.
- A subquery cannot be immediately enclosed in a set function.
- The BETWEEN operator cannot be used with a subquery; however, the BETWEEN operator can be used within the subquery.Example Table For Practice:
Employee Emp_id Name Surname Salary Dept_id 1 Rajesh Khanna 45000 2 2 Sneha Gupta 55000 4 3 Sandeep Nehte 95000 1 4 Kirti Patil 25000 3 5 Nilesh Jadhav 45000 3 6 Dipesh Das 35000 5 7 Kailash Rane 62000 1 8 Kavita Deshpande 48000 3 9 Sanjay Datt 50000 3 10 Shruti Hasan 78000 1 Subqueries with the SELECT Statement:
Basic syntax:
SELECT column_name1, column_name2 FROM table1 , table2 WHERE column_name OPERATOR (SELECT column_name1 , column_name2 FROM table1 , table2 WHERE Condition) |
SQL Syntax:
SELECT * FROM Employee WHERE Emp_id IN ( SELECT Emp_id FROM Employee WHERE Salary > 55000 ) ; |
After execution:
Emp_id | Name | Surname | Salary | Dept_id |
3 | Sandeep | Nehte | 95000 | 1 |
7 | Kailash | Rane | 62000 | 1 |
10 | Shruti | Hasan | 78000 | 1 |
Subqueries with the INSERT Statement:
INSERT INTO table_name (column1 , column2 ) SELECT * column1 , column2 FROM table1 , table2 WHERE VALUE OPERATOR |
INSERT INTO employee_backup SELECT * FROM employee WHERE Emp_id IN ( SELECT Emp_id FROM employee ) |
No comments:
Post a Comment