Using INSERT, UPDATE, and DELETE with non-correlated subqueries

To show you an example of inserting with a non-correlated subquery, execute the following query to create a new table to hold the data:

USE lahmansbaseballdb;
CREATE TABLE salaries_avg (
teamID varchar(3) NOT NULL,
salaryavg double NOT NULL
);

Once you've created the table with the preceding script, you can execute the following script to insert data into the table: 

USE lahmansbaseballdb; 
INSERT INTO salaries_avg
SELECT teamid, average_salary
FROM
(SELECT teamid, AVG(salary) average_salary
FROM salaries
GROUP BY teamid) AS team_salary
WHERE team_salary.average_salary > 2000000;

Here, you can see that the non-correlated subquery is actually in the SELECT clause of the INSERT query. This is how you can insert data by using a subquery in the same way you use it in a SELECT clause and then use that SELECT clause to query the data you want to insert. The following screenshot shows the results of what was inserted into the salaries_avg table:

You can also update from a subquery, as shown in the following query: 

USE lahmansbaseballdb; 
UPDATE salaries_avg
SET
teamid = (SELECT teamid
FROM
(SELECT teamid, AVG(salary) average_salary
FROM salaries
GROUP BY teamid) AS team_salary
WHERE team_salary.average_salary > 2000000
LIMIT 1);

After the previous update, salary_avg table will look as follows. It's showing all ATL because that's what the previous UPDATE query ultimately did:

Additionally, you can delete with a subquery, as shown in the following query: 

USE lahmansbaseballdb; 
DELETE FROM salaries_avg
WHERE teamid IN (SELECT teamid
FROM
(SELECT teamid, AVG(salary) avgsalary
FROM salaries
GROUP BY teamid) AS team_salary
WHERE team_salary.avgsalary > 2000000
AND teamid = 'ATL');

Now, there will be no rows in salaries_avg table.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.128.78.30