{"id":37567,"date":"2024-08-04T11:58:34","date_gmt":"2024-08-04T01:58:34","guid":{"rendered":"https:\/\/database.guide\/?p=37567"},"modified":"2024-09-17T07:00:39","modified_gmt":"2024-09-16T21:00:39","slug":"using-update-with-a-subquery-in-sql","status":"publish","type":"post","link":"https:\/\/database.guide\/using-update-with-a-subquery-in-sql\/","title":{"rendered":"Using UPDATE with a Subquery in SQL"},"content":{"rendered":"\n<p class=\"\">Ever found yourself needing to update a bunch of rows in your database, but the condition for the update depends on data from another table? That&#8217;s where <code><a href=\"https:\/\/database.guide\/sql-update-for-beginners\/\" data-type=\"post\" data-id=\"11576\">UPDATE<\/a><\/code> with a subquery comes in handy. Let&#8217;s break it down.<\/p>\n\n\n\n<!--more-->\n\n\n\n<h2 class=\"wp-block-heading\">Sample Data<\/h2>\n\n\n\n<p class=\"\">First, let&#8217;s set up some sample tables:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>-- Create and populate the departments table\nCREATE TABLE departments (\n    dept_id INT PRIMARY KEY,\n    dept_name VARCHAR(50),\n    budget DECIMAL(10, 2)\n);\n\nINSERT INTO departments (dept_id, dept_name, budget)\nVALUES \n    (1, 'HR', 500000),\n    (2, 'IT', 1000000),\n    (3, 'Sales', 750000);\n\n-- Create and populate the employees table\nCREATE TABLE employees (\n    emp_id INT PRIMARY KEY,\n    name VARCHAR(50),\n    dept_id INT,\n    salary DECIMAL(10, 2)\n);\n\nINSERT INTO employees (emp_id, name, dept_id, salary)\nVALUES \n    (1, 'Homer Simpson', 1, 60000),\n    (2, 'Peter Griffin', 2, 75000),\n    (3, 'Beatrice Johnson', 2, 65000),\n    (4, 'Becky Brown', 3, 80000),\n    (5, 'Charlie Davis', 3, 70000);<\/code><\/pre>\n\n\n\n<p class=\"\">Now that we&#8217;ve got our tables set up, let&#8217;s start with a simple example. Say we want to give a 10% raise to all employees in the IT department.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">Start with a <code>SELECT<\/code> Statement<\/h2>\n\n\n\n<p class=\"\">When we use a subquery in the <code>UPDATE<\/code> statement, oftentimes we can use the same subquery that we&#8217;d use if we were simply selecting the rows we want to update. <\/p>\n\n\n\n<p class=\"\">Therefore, before going right ahead and writing the <code>UPDATE<\/code> statement, and then immediately running that against the database, it&#8217;s usually a good idea to start by selecting the data with a <code>SELECT<\/code> statement first. That way if we&#8217;ve made a mistake in our query logic, we can catch it and correct it before it&#8217;s too late.<\/p>\n\n\n\n<p class=\"\">So let&#8217;s go ahead with a <code>SELECT<\/code> statement:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>SELECT * FROM employees WHERE dept_id = 2;<\/code><\/pre>\n\n\n\n<p class=\"\">Result:<\/p>\n\n\n\n<pre class=\"wp-block-preformatted\">emp_id  name              dept_id  salary<br>------  ----------------  -------  ------<br>2       Peter Griffin     2        75000 <br>3       Beatrice Johnson  2        65000 <\/pre>\n\n\n\n<p class=\"\">OK, so there are two employees in the IT department.<\/p>\n\n\n\n<p class=\"\">But wait! What if we don&#8217;t know the department ID for IT?<\/p>\n\n\n\n<p class=\"\">Well, that&#8217;s where the subquery comes in:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>SELECT * FROM employees \nWHERE dept_id = (\n    SELECT dept_id \n    FROM departments \n    WHERE dept_name = 'IT'\n    );<\/code><\/pre>\n\n\n\n<p class=\"\">Result:<\/p>\n\n\n\n<pre class=\"wp-block-preformatted\">emp_id  name              dept_id  salary<br>------  ----------------  -------  ------<br>2       Peter Griffin     2        75000 <br>3       Beatrice Johnson  2        65000 <\/pre>\n\n\n\n<p class=\"\">Same result, as expected. All we needed to know was the department name, and the subquery went to work and dug up the corresponding ID for us. That was passed to the outer query and so the query was able to return the intended results.<\/p>\n\n\n\n<p class=\"\">So the same concept would apply if we wanted to update the table. We could use a subquery to identify the ID of the IT department.<\/p>\n\n\n\n<p class=\"\">So to reiterate, the good thing about running a <code>SELECT<\/code> statement first is that we can see which rows are going to be updated before we run the <code>UPDATE<\/code> statement. That way, if we&#8217;ve made a mistake in our query, we can correct it before updating any rows and making a complete mess of things.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">Convert it to an <code>UPDATE<\/code> Statement<\/h2>\n\n\n\n<p class=\"\">So we can now take our <code>SELECT<\/code> statement from above and modify the first couple of lines to convert it into an <code>UPDATE<\/code> statement:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>UPDATE employees\nSET salary = salary * 1.1\nWHERE dept_id = (\n    SELECT dept_id \n    FROM departments \n    WHERE dept_name = 'IT'\n    );<\/code><\/pre>\n\n\n\n<p class=\"\">So just to be sure, this subquery finds the ID of the IT department and then the outer <code>UPDATE<\/code> statement uses that ID in its <code>WHERE<\/code> clause.<\/p>\n\n\n\n<p class=\"\">Let&#8217;s check the result of the update:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>SELECT * FROM employees \nWHERE dept_id = (\n    SELECT dept_id \n    FROM departments \n    WHERE dept_name = 'IT'\n    );<\/code><\/pre>\n\n\n\n<p class=\"\">Result:<\/p>\n\n\n\n<pre class=\"wp-block-preformatted\">emp_id  name              dept_id  salary<br>------  ----------------  -------  ------<br>2       Peter Griffin     2        82500 <br>3       Beatrice Johnson  2        71500 <\/pre>\n\n\n\n<p class=\"\">Nice to see that they&#8217;ve received their well deserved raise!<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">Another <code>UPDATE<\/code> with a Subquery<\/h2>\n\n\n\n<p class=\"\">Let&#8217;s kick it up a notch. Suppose we want to give a 5% raise to all employees in departments with a budget over 700,000. Here&#8217;s how we can do that:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>UPDATE employees\nSET salary = salary * 1.05\nWHERE dept_id IN (SELECT dept_id FROM departments WHERE budget > 700000);<\/code><\/pre>\n\n\n\n<p class=\"\">In this case, our subquery might return multiple department IDs, so we use <a href=\"https:\/\/database.guide\/sql-in-operator-for-beginners\/\" data-type=\"post\" data-id=\"11733\">the <code>IN<\/code> operator<\/a> instead of <a href=\"https:\/\/database.guide\/sql-equals-operator-for-beginners\/\" data-type=\"post\" data-id=\"11781\">the equals operator (<code>=<\/code>)<\/a>.<\/p>\n\n\n\n<p class=\"\">Let&#8217;s take a look at the data now:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>SELECT \n    e.name, \n    d.dept_name, \n    e.salary \nFROM employees e\nINNER JOIN departments d ON e.dept_id = d.dept_id;<\/code><\/pre>\n\n\n\n<p class=\"\">Result:<\/p>\n\n\n\n<pre class=\"wp-block-preformatted\">name              dept_name  salary<br>----------------  ---------  ------<br>Homer Simpson     HR         60000 <br>Peter Griffin     IT         86625 <br>Beatrice Johnson  IT         75075 <br>Becky Brown       Sales      84000 <br>Charlie Davis     Sales      73500<\/pre>\n\n\n\n<p class=\"\">So the only person not to receive a raise was Homer Simpson from the HR department. <\/p>\n\n\n\n<h2 class=\"wp-block-heading\">More Subqueries<\/h2>\n\n\n\n<p class=\"\">Check out my article called <a href=\"https:\/\/database.guide\/understanding-the-sql-subquery\/\">Understanding the SQL Subquery<\/a> that goes over various types of subqueries, along with examples. <\/p>\n","protected":false},"excerpt":{"rendered":"<p>Ever found yourself needing to update a bunch of rows in your database, but the condition for the update depends on data from another table? That&#8217;s where UPDATE with a subquery comes in handy. Let&#8217;s break it down.<\/p>\n","protected":false},"author":1,"featured_media":0,"comment_status":"closed","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[7],"tags":[15,10,173],"class_list":["post-37567","post","type-post","status-publish","format-standard","hentry","category-sql","tag-create-query","tag-how-to","tag-subqueries"],"_links":{"self":[{"href":"https:\/\/database.guide\/wp-json\/wp\/v2\/posts\/37567","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/database.guide\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/database.guide\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/database.guide\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/database.guide\/wp-json\/wp\/v2\/comments?post=37567"}],"version-history":[{"count":5,"href":"https:\/\/database.guide\/wp-json\/wp\/v2\/posts\/37567\/revisions"}],"predecessor-version":[{"id":37576,"href":"https:\/\/database.guide\/wp-json\/wp\/v2\/posts\/37567\/revisions\/37576"}],"wp:attachment":[{"href":"https:\/\/database.guide\/wp-json\/wp\/v2\/media?parent=37567"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/database.guide\/wp-json\/wp\/v2\/categories?post=37567"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/database.guide\/wp-json\/wp\/v2\/tags?post=37567"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}