Pages

Showing posts with label SQL SERVER. Show all posts
Showing posts with label SQL SERVER. Show all posts

12/05/2013

SQL Subquery

SQL Subquery

Subquery or Inner query or Nested query is a query in a query. A subquery is usually added in the WHERE Clause of the sql statement. Most of the time, a subquery is used when you know how to search for a value using a SELECT statement, but do not know the exact value in the database.
Subqueries are an alternate way of returning data from multiple tables.
Subqueries can be used with the following sql statements along with the comparision operators like =, <, >, >=, <= etc.
  • SELECT
  • INSERT
  • UPDATE
  • DELETE

    Subquery Example:

    1) Usually, a subquery should return only one record, but sometimes it can also return multiple records when used with operators like IN, NOT IN in the where clause. The query would be like,
    SELECT first_name, last_name, subject 
    FROM student_details 
    WHERE games NOT IN ('Cricket', 'Football'); 
    The output would be similar to:
    first_namelast_namesubject
    ------------------------------------
    ShekarGowdaBadminton
    PriyaChandraChess
    2) Lets consider the student_details table which we have used earlier. If you know the name of the students who are studying science subject, you can get their id's by using this query below,
    SELECT id, first_name 
    FROM student_details 
    WHERE first_name IN ('Rahul', 'Stephen'); 
    but, if you do not know their names, then to get their id's you need to write the query in this manner,
    SELECT id, first_name 
    FROM student_details 
    WHERE first_name IN (SELECT first_name 
    FROM student_details 
    WHERE subject= 'Science'); 
    Output:
    idfirst_name
    ---------------------
    100Rahul
    102Stephen
    In the above sql statement, first the inner query is processed first and then the outer query is processed.

    3) Subquery can be used with INSERT statement to add rows of data from one or more tables to another table. Lets try to group all the students who study Maths in a table 'maths_group'.
    INSERT INTO maths_group(id, name) 
    SELECT id, first_name || ' ' || last_name 
    FROM student_details WHERE subject= 'Maths' 

    4) A subquery can be used in the SELECT statement as follows. Lets use the product and order_items table defined in the sql_joins section.
    select p.product_name, p.supplier_name, (select order_id from order_items where product_id = 101) as order_id from product p where p.product_id = 101
    product_namesupplier_nameorder_id
    ----------------------------------------------
    TelevisionOnida5103

    Correlated Subquery

    A query is called correlated subquery when both the inner query and the outer query are interdependent. For every row processed by the inner query, the outer query is processed as well. The inner query depends on the outer query before it can be processed.
    SELECT p.product_name FROM product p 
    WHERE p.product_id = (SELECT o.product_id FROM order_items o 
    WHERE o.product_id = p.product_id); 
    NOTE:
    1) You can nest as many queries you want but it is recommended not to nest more than 16 subqueries in oracle.
    2) If a subquery is not dependent on the outer query it is called a non-correlated subquery.

INNER JOIN UPDATE : Update Table with INNER JOIN

INNER JOIN UPDATE Often we may need to update a column in a table based of another column in another table.
In SQL Server you can do this using UPDATE statement by joining tables together.
To understand this better let’s take a look at below contrived example.
USE [SqlAndMe]
GO

SELECT CustomerID, Name, OrderAmount
FROM   dbo.Customers
GO

SELECT OrderID, CustomerID, Amount
FROM   dbo.Orders
GO
Result Set:
CustomerID    Name          OrderAmount
3             Curtis        NULL
4             Lanna         NULL
5             Marlin        NULL
6             Henry         NULL

(4 row(s) affected)

OrderID       CustomerID    Amount
107           6             8745.00
123           5             4582.00
643           3             5693.00

(3 row(s) affected)
In the above data I want to update OrderAmount column of dbo.Customers with values fromAmount column of dbo.Orders.
To achieve this we can use UPDATE statement as below:
UPDATE CUST
SET    CUST.OrderAmount = ORDR.Amount
FROM   dbo.Customers CUST
INNER JOIN dbo.Orders ORDR ON CUST.CustomerID = ORDR.CustomerID
GO

(3 row(s) affected)
OrderAmount column in dbo.Customers Table is now updated based on JOIN condition.
SELECT CustomerID, Name, OrderAmount
FROM   dbo.Customers
GO
CustomerID    Name          OrderAmount
3             Curtis        5693.00
4             Lanna         NULL
5             Marlin        4582.00
6             Henry         8745.00

(4 row(s) affected)

ภาษาไทย

ถ้าเราต้องมีการ update หรือ delete ข้อมูลในฐานข้อมูลคราวละหลาย record ด้วยเงื่อนไขบางอย่าง ถ้าเป็นไปได้ควรจะเขียนให้ทำงานได้ด้วยคำสั่ง SQL Command เดียว หากเงื่อนไขนั้นอยู่ในตารางที่ต้องการจะลบอยู่แล้ว SQL Command ก็จะตรงไปตรงมา อย่างเช่นคำสั่ง update ก็จะเป็นประมาณนี้
1
update table1 set field1=0, field2='a' where field3 is null
และการ delete
1
delete from table1 where field3 is null
แต่หากเราต้องการ update ตาราง table1 แต่ว่าเงื่อนไขเราอยู่ในตารางอื่น หรือแม้แต่ข้อมูลที่จะมา update อยู่ในตารางอื่น
ใน SQL Server เราสามารถใช้การ join เข้ามาช่วยใน sql ได้ดังนี้
1
2
3
update t1 set t1.field1=0, t1.field2=t2.field2
from table1 t1 inner join table2 t2 on t1.joinfield=t2.joinfield
where t2.field3 is null
และการ delete
1
2
3
delete from t1
from table1 t1 inner join table2 t2 on t1.joinfield=t2.joinfield
where t2.field3 is null