C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML
SQL Sub QueryA Subquery is a query within another SQL query and embedded within the WHERE clause. Important Rule:
1. Subqueries with the Select StatementSQL subqueries are most frequently used with the Select statement. Syntax SELECT column_name FROM table_name WHERE column_name expression operator ( SELECT column_name from table_name WHERE ... ); Example Consider the EMPLOYEE table have the following records:
The subquery with a SELECT statement will be: SELECT * FROM EMPLOYEE WHERE ID IN (SELECT ID FROM EMPLOYEE WHERE SALARY > 4500); This would produce the following result:
2. Subqueries with the INSERT Statement
Syntax: INSERT INTO table_name (column1, column2, column3....) SELECT * FROM table_name WHERE VALUE OPERATOR Example Consider a table EMPLOYEE_BKP with similar as EMPLOYEE. Now use the following syntax to copy the complete EMPLOYEE table into the EMPLOYEE_BKP table. INSERT INTO EMPLOYEE_BKP SELECT * FROM EMPLOYEE WHERE ID IN (SELECT ID FROM EMPLOYEE); 3. Subqueries with the UPDATE StatementThe subquery of SQL can be used in conjunction with the Update statement. When a subquery is used with the Update statement, then either single or multiple columns in a table can be updated. Syntax UPDATE table SET column_name = new_value WHERE VALUE OPERATOR (SELECT COLUMN_NAME FROM TABLE_NAME WHERE condition); Example Let's assume we have an EMPLOYEE_BKP table available which is backup of EMPLOYEE table. The given example updates the SALARY by .25 times in the EMPLOYEE table for all employee whose AGE is greater than or equal to 29. UPDATE EMPLOYEE SET SALARY = SALARY * 0.25 WHERE AGE IN (SELECT AGE FROM CUSTOMERS_BKP WHERE AGE >= 29); This would impact three rows, and finally, the EMPLOYEE table would have the following records.
4. Subqueries with the DELETE StatementThe subquery of SQL can be used in conjunction with the Delete statement just like any other statements mentioned above. Syntax DELETE FROM TABLE_NAME WHERE VALUE OPERATOR (SELECT COLUMN_NAME FROM TABLE_NAME WHERE condition); Example Let's assume we have an EMPLOYEE_BKP table available which is backup of EMPLOYEE table. The given example deletes the records from the EMPLOYEE table for all EMPLOYEE whose AGE is greater than or equal to 29. DELETE FROM EMPLOYEE WHERE AGE IN (SELECT AGE FROM EMPLOYEE_BKP WHERE AGE >= 29 ); This would impact three rows, and finally, the EMPLOYEE table would have the following records.
Next TopicDBMS SQL Clauses
|