• What can be cooked from squid: quick and tasty

    Last updated: 07/13/2017

    The UPDATE command is used to modify existing rows in the table. It has the following formal syntax:

    UPDATE table_name SET column1 = value1, column2 = value2, ... columnN = valueN

    For example, let's increase the price of all products by 5000:

    UPDATE Products SET Price = Price + 5000

    We use the criterion and change the manufacturer's name from "Samsung" to "Samsung Inc.":

    UPDATE Products SET Manufacturer = "Samsung Inc." WHERE Manufacturer = "Samsung"

    More complex query - replace the Manufacturer field value "Apple" with "Apple Inc." in the first 2 lines:

    UPDATE Products SET Manufacturer = "Apple Inc." FROM (SELECT TOP 2 FROM Products WHERE Manufacturer = "Apple") AS Selected WHERE Products.Id = Selected.Id

    The subquery after the FROM keyword fetches the first two rows where Manufacturer = "Apple". This selection will be given the Selected alias. The alias is specified after the AS operator.

    Next comes the update condition Products.Id = Selected.Id. That is, in fact, we are dealing with two tables - Products and Selected (which is derived from Products). Selected contains the first two lines where Manufacturer = "Apple". In Products - in general, all lines. And the update is performed only for those rows that are in the Selected selection. That is, if there are dozens of products with the manufacturer Apple in the Products table, then the update will affect only the first two of them.

    Updating data in a database means changing values ​​in existing table records. In this case, it is possible both to change the values ​​of fields in a group of rows (even of all rows of the table), and to edit the value of a field in a separate row.

    In SQL, you can change a record in a database table using the UPDATE command. In its most minimal form, the data update command looks like this:

    UPDATE SET table field = value

    Here, UPDATE- command indicating that the request is to update the data;

    table- the name of the table in which the changes will be made;

    SET- a command, after which the fields with the values ​​assigned to them are indicated, separated by commas;

    field- the field of the table in which the change will be made;

    meaning- the new value to be entered into the field.


    For example, if you need to set a field in all rows of a table to be equal to zero, you can run the following query:

    UPDATE goods SET price = 0

    In this case, the price field in absolutely all available rows of the table will take the value 0.

    Changing one value

    Changing the value of all fields in a table is extremely rare. Most often it is necessary to change the value of a particular entry. To do this, at the end of the line with the UPDATE command, a WHERE directive will be added, which specifies a condition that determines which row to perform the update operation with.

    There is a table:

    For example, you need to update the cost of a product with its known value num. To do this, run the following query:

    UPDATE goods SET price = 150 WHERE num = 2

    Now, before the operation of changing the fields, a row will be selected that satisfies the condition num = 2. There is only one such row in the table. In this stock, the price will be changed to 150. As a result, we will get a table with the changed price of the product.

    Making changes to multiple lines with a selection condition

    If you remember all the variety of conditions in the query, you can imagine how diverse the samples can be. Therefore, update queries can be executed either with one row, or with a group of rows, or with all the rows of the table. It all depends on the task you are facing, as well as with which table rows you need to perform update operations.

    For example, we want to halve the price of all goods that now cost 100 or more. Inquiry:

    UPDATE goods SET price = price / 2 WHERE price> = 100

    Condition WHERE here contains a rule according to which only products with a price equal to or more than 100 will be selected, and those products with a price lower than 100 will not be affected by the request.

    price = price / 2- the formula by which the new price of goods will be calculated. The new price will be written equal to the old price divided by two.

    As a result of executing such a query, we get a table with changed records:

    Updating values ​​in multiple fields of a row

    If it is necessary to update several fields at once, all fields with their values ​​are indicated after the SET directive, separated by commas. For example, you need to change the name and price of a product with code 2 to "iron", costing 300:

    UPDATE goods SET title = "(! LANG: iron" , price = 300 WHERE num = 2 !}

    Such a query will assign a value to each corresponding field in the row. And the condition will indicate in which line the changes will be made.


    The above are the main types of update operations. On their basis, queries are formed to solve most of the tasks of changing data in development using SQL.

    SQL Server supports most of the core components of the ANSI UPDATE statement, but it does not support the ONLY and ARRAY keywords and does not support the ability to update arrays. SQL Server has extended the UPDATE statement functionality by adding table hints with the WITH clause, adding query hints with the OPTION clause, and more robust variable handling. The syntax is as follows.

    UPDATE (table_name | view_name | rowset))] SET (column_name = (DEFAULT | NULL | scalar_expression) |

    stirrup name = scalar_expression | variable_name = column_name = scalar_expression) [, ...]]

    WHERE (conditions | CURRENT OF cursor_name))]

    The syntax elements for the UPDATE statement in SQL Server are as follows.

    WITH hint

    Enables the use of table hints, overriding the default query optimizer behavior. Because the query optimizer is very good at choosing processing plans, use hints only if you have a very good understanding of the tables, indexes, and data affected by the operation. If there is no such understanding, using hints can lead not to an increase, but to a decrease in performance.

    variable_name

    SQL Server variables must be declared before using the UPDATE statement, in the form DECLARE @ variable. SET construct @ variable = column! = Expression! sets the variable to the final value of the updated column, and the SET @variable -column !, column! = expression sets the variable to the value in the column before the UPDATE statement.

    Provides the ability to create a highly selective join-based criterion to specify which rows to update. The FROM clause is unnecessary if only one table is used when specifying rows - the target table. The rowset functions in SQL Server are described in the "SELECT Statement" section.

    AS alias

    Allows you to assign an easy-to-use alias to a table, view, nested table subquery, or rowset function.

    Provides the ability to use standard ANSI syntax for table joins in conjunction with the FROM clause.

    A slight variation of the ANSI standard WHERE CURRENT OF clause. The WHERE CURRENT OF cursor name used in combination with a cursor causes SQL Server to update only the single record that the cursor is currently on. The cursor is assumed to be local, but you can also specify a global cursor using the GLOBAL keyword.

    OPTION hint

    Enables query hints by overriding the default query optimizer behavior. As with the WITH clause, use hints only if you have a very good understanding of the tables, indexes, and data affected by the operation. If there is no such understanding, using hints can lead not to an increase, but to a decrease in performance.

    The main extension that Microsoft SQL Server introduces to the ANSI UPDATE statement is the FROM clause. The FROM clause enables a JOIN clause, which makes it much easier to update the rows of the target table by linking the rows specified in the FROM clause to the rows updated by the UPDATE component table_name. The following example shows updating the result of a table join using ANSI style and a rather cumbersome subquery, and then updating using the FROM SQL Server clause. Both requests perform the same action, but in completely different ways.

    Performing such an update using the Transact-SQL style amounts to joining two tables, authors and titleauthor, to the titles table. To perform the same operation using ANSI code, you first need to find the au_id value in the authors table and pass it to the titleauthor table, and then you need to find the title_id value and pass it to the main UPDATE statement.

    The following example updates the state column for the first ten records in the authors table.

    UPDATE authors SET state = "ZZ" FROM (SELECT TOP 10 * FROM authors ORDER BY au_lname) AS t1 WHERE authors.au_id = t1.au_.id

    In this example, it is important to note that it is usually quite difficult to update the first n records with an UPDATE statement unless there is some explicit row sequence that can be defined using the WHERE clause. However, a nested table subquery in the FROM clause that uses the TOP keyword to retrieve the first 10 records helps avoid wasting effort on additional coding that would otherwise be necessary.

    Operator UPDATE changes the existing data in the table. The command has the following syntax:

    UPDATE SET (= (| NULL | DEFAULT), ...) [(WHERE)];

    Values ​​for any number of columns can be specified with a single operator. However, in the same UPDATE statement, you can make changes to each column of the specified table only once. Without a WHERE clause, all rows in the table are updated.

    If the column allows a NULL value, then it can be specified explicitly. Alternatively, you can replace the existing value with the default value (DEFAULT) for this column.

    SQL UPDATE Statement Examples

    There is the following Planets table:

    Example 1.Using the SQL UPDATE statement to change the name of the planet Neptune on Pluton:

    UPDATE Planets SET PlanetName = "Pluton" WHERE ID = 3;

    In this example, the SQL WHERE clause is required because without it, all fields in the PlanetName column in the entire table would change to Pluton. In this case, the ID column comes to the rescue, since it is the Primary Key that uniquely identifies the record.

    Example 2. Let's increase the salary of all teachers by 2 times, and the bonus by 10 times.

    UPDATE command- makes changes in an already existing record or in a set of records in a table SQL... Modifies existing values ​​in the table or in the main table of the view.

    UPDATE Command Command Syntax

    UPDATE Command Syntax

    UPDATE command. Basic keywords and parameters of the UPDATE command

    • schema - permission identifier, usually the same as the name of some user
    • table view - table name SQL in which the data is changed; if a view is defined, the data is modified in the main table SQL representation
    • subquery_1 - subquery which the server handles in the same way as the view
    • witholumn - table column SQL or presentation SQL whose value is changing; if table column is from sentence SET omitted, the column value remains unchanged
    • expr - ; this expression can contain main variables and optional indicator variables
    • subquery_2 - the new value to assign to the corresponding column
    • subquery_3 - the new value to assign to the corresponding column

    WHERE- defines the range of modified rows by those for which a certain condition is TRUE; if this phrase is omitted, all rows in the table or view are updated.
    When issuing an approval, any UPDATE trigger defined on the table.
    Subqueries... If the offer SET contains subquery, it returns exactly one row for each modified row. Each value in the result of the subquery is assigned to the corresponding columns in the parenthesized list. If the subquery does not return any rows, the column is assigned NULL. Subqueries can select data from the modified table. Offer SET can combine expressions and subqueries.

    UPDATE Command Example 1
    Changing the rating for all buyers by a value equal to 200:

    Customers SET rating = 200;

    UPDATE Command Example 2
    Substitution of a column value in all rows of a table is usually rarely used. Therefore, in a team, as in a team DELETE, you can use a predicate. To perform the specified replacement of the rating column values, for all buyers who are served by the seller Giovanni (snum = 1003), enter:

    Customers SET rating = 200 WHERE snum = 1001;

    SQL UPDATE Command Example 3
    In a sentence SET you can specify any number of values ​​for the columns, separated by commas:

    Emp SET job = 'MANAGER', sal = sal + 1000, deptno = 20 WHERE ename = 'JONES';

    UPDATE Command Example 4
    In a sentence SET you can specify NULL without using any special syntax (such as IS NULL, for example). So, if you want to set all ratings for buyers from London (city = ‘London’) to NULL, you would enter:

    Customers SET rating = NULL WHERE city = ‘London’;

    UPDATE Command Example 5
    Explains the use of the following command syntax:

    • Both offer forms SET together in one statement.
    • Subquery.
    • WHERE clause limiting the range of the modified rows.

    Emp a SET deptno =
    (SELECT deptno FROM dept WHERE loc = 'BOSTON'), (sal, comm) = ( SELECT 1.1 * AVG (sal), 1.5 * AVG (comm) FROM emp b WHERE a.deptno = b.deptno) WHERE deptno IN ( SELECT deptno FROM dept WHERE loc = 'DALLAS' OR loc = 'DETROIT');

    The above statement does the following:

    • Only modifies employees who work for Dallas or Detroit
    • Sets the value of the deptno column for Boston employees
    • Sets the salary of each employee to 1.1 times the average salary of the entire department
    • Sets the commission for each employee to be 1.5 times the average commission for the entire department