SQL Subqueries
Hello, and welcome to the blog. In this blog we are going to talk about "Subqueries".
In the previous blog we have seen small topic of ALL, IN, ANY operators. Now we will see how write
a query inside a query. Don't worry I will elaborate how we are gonna do
it.
So, we are going to talk about
- What is Subquery?
- Rules of writing outer query.
- Rules of writing subquery.
- Basic types of Subquery.
- Correlated Subquery.
- Possible number of nesting in Subquery
- Subquery in Update, Delete and Insert Statement
- Subquery with Exists keyword.
let's jump into it
1) What is a subquery
- Subquery is a query inside a query or you can say it as nested query.
- It is mainly used as a part of where clause.
- Subquery returns data that will be used in the main query.
- Subquery can be used with SELECT, INSERT, UPDATE and DELETE statements.
- One more thing about subqueries is that subqueries can be alternatively formulated as JOINS.
-
Let's see a subquery :SELECT FirstNameFROM Employee1WHERE DepartmentId=(SELECT IdFROM DepartmentWHERE DepartmentName='IT'
-
As I said subqueries can be formulated as JOINS, let's see how we can do it with joins:SELECT FirstNameFROM Employee1 eINNER JOIN Department d ON e.DepartmentID=d.Id
- As you can see we got the same result
2) Rules for writing outer query of sub query
- A regular SELECT query including regular select list component.
- A regular FROM clause including one or more tables or views.
- optional WHERE clause.
- optional HAVING clause.
- optional GROUP BY clause.
3) Rules of Subquery
- The SELECT list of a subquery introduced with a comparison operator can include only one expression or column name(except that 'exists' and 'in' operator on select or a list).
- If where clause includes a column name it must be join compatible with column in subquery list.
- The ntext, text and image data types of SQL cannot be used in SELECT list of subqueries.
- Subquery must return a single value subqueries which are introduced without ANY or ALL keyword cannot include 'GROUP BY' or 'HAVING' clause.
4) Basic Subquery types
- Operator on list introduced with IN or comparison operator modified by ANY or ALL which we already know.
- Introduced with an unmodified comparison operator and must return a single value.
- Existence test introduced with exists.
5) Correlated Subquery
- Many queries can be evaluated by executing a subquery once and substituting the resulting value or values to the main query.
- In correlated subquery, the subquery depends on the outer query for its value.
- This means that the subquery is executed repeatedly, once for each row that might be selected by the outer query.
- Let's understand this concept with example
- Example: Find all the Employees who earns more than average salary in their respective department.
-
Solution:SELECT FirstName, Salary, DepartmentNameFROM Employee1 e1INNER JOIN Department d on e1.DepartmentId=d.IDWHERE SALARY>(SELECT avg(Salary)FROM Emploee1 e2WHERE e1.DepartmentId=e2.DepartmentIdGROUP BY DepartmentId
- Here in this query value of DepartmentId in subquery should match with DepartmentId in outer query that is why this query is "Correlated Subquery".
6) How many levels of nesting is possible?
- In SQL Server 32 levels of nesting is possible, this limit also varies depending upon available memory and complexity of memory.
- When it comes to oracle database. It imposes no limit on the number of subquery level in the FROM clause of top-level query. You can nest up to 255 levels of subqueries in where clause.
7) Subqueries in Update, Delete and Insert Statement.
7.1. Update Statement
-
Let's see a subquery in Update statement. This query might feel a little illogical to you but my point here is to explain
- Subquery in Update Statement
- Multiple level of nesting
UPDATE Employee SET Salary = Salary * 1.3 WHERE EmployeeId IN ( SELECT Id FROM Employee WHERE DepartmentId = ( SELECT Id FROM Department WHERE DepartmentName = 'IT' ) )
-
You can solve this query easily, I purposely made it complex. Easier version of this query is:UPDATE Employee1SET salary =salary*1.3
7.2. Subqueries in Insert Statement
- In insert statement when subquery is used the main purpose is to insert data into the table which is returned by subquery.
-
Whatever data is returned from the query is inserted into the table
-
Let's see a example:INSERT intoEmployee2 (FirstName, LastName, Department, Salary, Designation, ReportingManager)SELECT FirstName, LastName, Department, Salary, Designation, ReportingManagerFROM Employee1
-
This kind of insert is always done when you want to perform some critical operation which may lead to data loss. So to create backup of data a new "Backup Table" is generated with this kind of query.
- As we we are going for delete statement next this is the best time to take a backup.
7.3. Subqueries with DELETE statement
- Subquery with delete statement is very similar to what we have seen in UPDATE statement.
-
Let's see a example:DELETE from Employee1WHERE DepartmentId=(SELECT IdFROM Department
8) Subquery with Exists keyword
- When subquery is introduced with keyword "EXISTS" the subquery act as existence test.
- It check whether a record exists or not and returns True or False accordingly.
- Example:SELECT FirstNameFROM Employee1 eWHERE EXISTS(SELECT *FROM Department
Here we end Subquery. I know its little big but very informative and Congratulation's on learning subqueries.
See you in some other blog till then "Keep coding, keep learning because trust me you can make it big".
"Have a great day"
Nice article
ReplyDelete