Как удалить строку в sql

от admin

Как удалить строку в sql

Для удаления применяется команда DELETE :

Например, удалим строки, у которых id равен 9:

Или удалим все товары, производителем которых является Xiaomi и которые имеют цену меньше 15000:

Более сложный пример — удалим первые два товара, у которых производитель — Apple:

После первого оператора FROM идет выборка двух строк из таблицы Products. Этой выборке назначается псевдоним Selected с помощью оператора AS. Далее устанавливаем условие, что если Id в таблице Products имеет то же значение, что и Id в выборке Selected, то строка удаляется.

Если необходимо вовсе удалить все строки вне зависимости от условия, то условие можно не указывать:

SQL Оператор DELETE

SQL оператор DELETE используется для удаления одной или нескольких записей из таблицы.

Синтаксис

Синтаксис оператора DELETE в SQL:

Параметры или аргументы

Примечание

Вам не нужно перечислять поля в операторе DELETE, так как вы удаляете всю строку из таблицы.

Пример оператора DELETE с одним условием

Если вы запустите оператор DELETE без условий в предложении WHERE, все записи из таблицы будут удалены. В результате вы чаще всего будете включать предложение WHERE, по крайней мере с одним условием, в свой оператор DELETE.

Давайте начнем с простого примера запроса DELETE, который имеет одно условие в предложении WHERE.

В этом примере у нас есть таблица suppliers со следующими данными:

supplier_id supplier_name city state
100 Yandex Moscow Moscow
200 Google Lansing Michigan
300 Oracle Redwood City California
400 Bing Redmond Washington
500 Yahoo Sunnyvale Washington
600 DuckDuckGo Paoli Pennsylvania
700 Qwant Paris Ile de France
800 Facebook Menlo Park California
900 Electronic Arts San Francisco California

Введите следующий оператор DELETE:

Будет удалена 1 запись. Снова выберите данные из таблицы поставщиков:

Вот результаты, которые вы должны получить:

supplier_id supplier_name city state
200 Google Lansing Michigan
300 Oracle Redwood City California
400 Bing Redmond Washington
500 Yahoo Sunnyvale Washington
600 DuckDuckGo Paoli Pennsylvania
700 Qwant Paris Ile de France
800 Facebook Menlo Park California
900 Electronic Arts San Francisco California

В этом примере удаляются все записи из таблицы suppliers , где supplier_name — Yandex.

Вы можете проверить количество строк, которые будут удалены. Вы можете определить количество строк, которые будут удалены, выполнив следующий запрос SELECT перед выполнением удаления:

Этот запрос вернет количество записей, которые будут удалены при выполнении оператора DELETE.

COUNT(*)
1

Пример — оператор DELETE с более чем одним условием

Вы можете иметь более одного условия в инструкции DELETE в SQL, используя либо условие AND, либо условие OR. Условие AND позволяет вам удалить запись, если все условия выполнены. Условие OR удаляет запись, если выполняется одно из условий.

Давайте рассмотрим пример использования оператора DELETE с двумя условиями с использованием условия AND.
В этом примере у нас есть таблица products со следующими данными:

product_id product_name category_id
1 Pear 50
2 Banana 50
3 Orange 50
4 Apple 50
5 Bread 75
6 Sliced Ham 25
7 Kleenex NULL

Введите следующий оператор DELETE:

Будет удалены 3 записи. Снова выберите данные из таблицы products :

Вот результаты, которые вы получите:

product_id product_name category_id
1 Pear 50
5 Bread 75
6 Sliced Ham 25
7 Kleenex NULL

В этом примере удаляются все записи из таблицы products , у которых category_id равен 50, а product_name НЕ ‘Pear’.

Пример — использование EXISTS с оператором DELETE

Вы также можете выполнять более сложные удаления.

Вы можете удалить записи в одной таблице на основе значений в другой таблице. Поскольку вы не можете перечислить более одной таблицы в предложении FROM при выполнении удаления, вы можете использовать предложение EXISTS.

Name already in use

sql-docs / docs / t-sql / statements / delete-transact-sql.md

  • Go to file T
  • Go to line L
  • Copy path
  • Copy permalink
  • Open with Desktop
  • View raw
  • Copy raw contents Copy raw contents

Copy raw contents

Copy raw contents

Removes one or more rows from a table or view in [!INCLUDEssNoVersion].

. image type=»icon» source=»../../includes/media/topic-link-icon.svg» border=»false». Transact-SQL syntax conventions

WITH <common_table_expression>
Specifies the temporary named result set, also known as common table expression, defined within the scope of the DELETE statement. The result set is derived from a SELECT statement.

Common table expressions can also be used with the SELECT, INSERT, UPDATE, and CREATE VIEW statements. For more information, see WITH common_table_expression (Transact-SQL).

TOP (expression) [ PERCENT ]
Specifies the number or percent of random rows that will be deleted. expression can be either a number or a percent of the rows. The rows referenced in the TOP expression used with INSERT, UPDATE, or DELETE are not arranged in any order. For more information, see TOP (Transact-SQL).

FROM
An optional keyword that can be used between the DELETE keyword and the target table_or_view_name, or rowset_function_limited.

table_alias
The alias specified in the FROM table_source clause representing the table or view from which the rows are to be deleted.

server_name
Applies to: [!INCLUDEsql2008-md] and later.

The name of the server (using a linked server name or the OPENDATASOURCE function as the server name) on which the table or view is located. If server_name is specified, database_name and schema_name are required.

database_name
The name of the database.

schema_name
The name of the schema to which the table or view belongs.

table_or_view_name
The name of the table or view from which the rows are to be removed.

A table variable, within its scope, also can be used as a table source in a DELETE statement.

The view referenced by table_or_view_name must be updatable and reference exactly one base table in the FROM clause of the view definition. For more information about updatable views, see CREATE VIEW (Transact-SQL).

rowset_function_limited
Applies to: [!INCLUDEsql2008-md] and later.

Either the OPENQUERY or OPENROWSET function, subject to provider capabilities.

WITH ( <table_hint_limited> [. n] )
Specifies one or more table hints that are allowed for a target table. The WITH keyword and the parentheses are required. NOLOCK and READUNCOMMITTED are not allowed. For more information about table hints, see Table Hints (Transact-SQL).

<OUTPUT_Clause>
Returns deleted rows, or expressions based on them, as part of the DELETE operation. The OUTPUT clause is not supported in any DML statements targeting views or remote tables. For more information about the arguments and behavior of this clause, see OUTPUT Clause (Transact-SQL).

FROM table_source
Specifies an additional FROM clause. This [!INCLUDEtsql] extension to DELETE allows specifying data from <table_source> and deleting the corresponding rows from the table in the first FROM clause.

This extension, specifying a join, can be used instead of a subquery in the WHERE clause to identify rows to be removed.

For more information, see FROM (Transact-SQL).

WHERE
Specifies the conditions used to limit the number of rows that are deleted. If a WHERE clause is not supplied, DELETE removes all the rows from the table.

There are two forms of delete operations based on what is specified in the WHERE clause:

Searched deletes specify a search condition to qualify the rows to delete. For example, WHERE column_name = value.

Positioned deletes use the CURRENT OF clause to specify a cursor. The delete operation occurs at the current position of the cursor. This can be more accurate than a searched DELETE statement that uses a WHERE search_condition clause to qualify the rows to be deleted. A searched DELETE statement deletes multiple rows if the search condition does not uniquely identify a single row.

<search_condition>
Specifies the restricting conditions for the rows to be deleted. There is no limit to the number of predicates that can be included in a search condition. For more information, see Search Condition (Transact-SQL).

CURRENT OF
Specifies that the DELETE is performed at the current position of the specified cursor.

GLOBAL
Specifies that cursor_name refers to a global cursor.

cursor_name
Is the name of the open cursor from which the fetch is made. If both a global and a local cursor with the name cursor_name exist, this argument refers to the global cursor if GLOBAL is specified; otherwise, it refers to the local cursor. The cursor must allow updates.

cursor_variable_name
The name of a cursor variable. The cursor variable must reference a cursor that allows updates.

OPTION ( <query_hint> [ ,. n] )
Keywords that indicate which optimizer hints are used to customize the way the [!INCLUDEssDE] processes the statement. For more information, see Query Hints (Transact-SQL).

To delete all the rows in a table, use TRUNCATE TABLE . TRUNCATE TABLE is faster than DELETE and uses fewer system and transaction log resources. TRUNCATE TABLE has restrictions, for example, the table cannot participate in replication. For more information, see TRUNCATE TABLE (Transact-SQL)

Use the @@ROWCOUNT function to return the number of deleted rows to the client application. For more information, see @@ROWCOUNT (Transact-SQL).

You can implement error handling for the DELETE statement by specifying the statement in a TRY. CATCH construct.

The DELETE statement may fail if it violates a trigger or tries to remove a row referenced by data in another table with a FOREIGN KEY constraint. If the DELETE removes multiple rows, and any one of the removed rows violates a trigger or constraint, the statement is canceled, an error is returned, and no rows are removed.

When a DELETE statement encounters an arithmetic error (overflow, divide by zero, or a domain error) occurring during expression evaluation, the [!INCLUDEssDE] handles these errors as if SET ARITHABORT is set ON. The rest of the batch is canceled, and an error message is returned.

DELETE can be used in the body of a user-defined function if the object modified is a table variable.

When you delete a row that contains a FILESTREAM column, you also delete its underlying file system files. The underlying files are removed by the FILESTREAM garbage collector. For more information, see Access FILESTREAM Data with Transact-SQL.

The FROM clause cannot be specified in a DELETE statement that references, either directly or indirectly, a view with an INSTEAD OF trigger defined on it. For more information about INSTEAD OF triggers, see CREATE TRIGGER (Transact-SQL).

Limitations and Restrictions

When TOP is used with DELETE , the referenced rows are not arranged in any order and the ORDER BY clause can not be directly specified in this statement. If you need to use TOP to delete rows in a meaningful chronological order, you must use TOP together with an ORDER BY clause in a subselect statement. See the Examples section that follows in this topic.

TOP cannot be used in a DELETE statement against partitioned views.

By default, a DELETE statement always acquires an intent exclusive (IX) lock on the table object and pages it modifies, an exclusive (X) lock on the rows it modifies, and holds those locks until the transaction completes.

With an intent exclusive (IX) lock, no other transactions can modify the same set of data; read operations can take place only with the use of the NOLOCK hint or read uncommitted isolation level. You can specify table hints to override this default behavior for the duration of the DELETE statement by specifying another locking method, however, we recommend that hints be used only as a last resort by experienced developers and database administrators. For more information, see Table Hints (Transact-SQL).

When rows are deleted from a heap the [!INCLUDEssDE] may use row or page locking for the operation. As a result, the pages made empty by the delete operation remain allocated to the heap. When empty pages are not deallocated, the associated space cannot be reused by other objects in the database.

To delete rows in a heap and deallocate pages, use one of the following methods.

Specify the TABLOCK hint in the DELETE statement. Using the TABLOCK hint causes the delete operation to take an IX lock on the object instead of a row or page lock. This allows the pages to be deallocated. For more information about the TABLOCK hint, see Table Hints (Transact-SQL).

Use TRUNCATE TABLE if all rows are to be deleted from the table.

Create a clustered index on the heap before deleting the rows. You can drop the clustered index after the rows are deleted. This method is more time consuming than the previous methods and uses more temporary resources.

[!NOTE]
Empty pages can be removed from a heap at any time by using the ALTER TABLE <table_name> REBUILD statement.

The DELETE statement is always fully logged.

DELETE permissions are required on the target table. SELECT permissions are also required if the statement contains a WHERE clause.

DELETE permissions default to members of the sysadmin fixed server role, the db_owner and db_datawriter fixed database roles, and the table owner. Members of the sysadmin , db_owner , and the db_securityadmin roles, and the table owner can transfer permissions to other users.

Category Featured syntax elements
Basic syntax DELETE
Limiting the rows deleted WHERE • FROM • cursor •
Deleting rows from a remote table Linked server • OPENQUERY rowset function • OPENDATASOURCE rowset function
Capturing the results of the DELETE statement OUTPUT clause

Examples in this section demonstrate the basic functionality of the DELETE statement using the minimum required syntax.

A. Using DELETE with no WHERE clause

The following example deletes all rows from the SalesPersonQuotaHistory table in the [!INCLUDEssSampleDBnormal] database because a WHERE clause is not used to limit the number of rows deleted.

Limiting the Rows Deleted

Examples in this section demonstrate how to limit the number of rows that will be deleted.

B. Using the WHERE clause to delete a set of rows

The following example deletes all rows from the ProductCostHistory table in the [!INCLUDEssSampleDBnormal] database in which the value in the StandardCost column is more than 1000.00 .

The following example shows a more complex WHERE clause. The WHERE clause defines two conditions that must be met to determine the rows to delete. The value in the StandardCost column must be between 12.00 and 14.00 and the value in the column SellEndDate must be null. The example also prints the value from the @@ROWCOUNT function to return the number of deleted rows.

C. Using a cursor to determine the row to delete

The following example deletes a single row from the EmployeePayHistory table in the [!INCLUDEssSampleDBnormal] database using a cursor named complex_cursor . The delete operation affects only the single row currently fetched from the cursor.

D. Using joins and subqueries to data in one table to delete rows in another table

The following examples show two ways to delete rows in one table based on data in another table. In both examples, rows from the SalesPersonQuotaHistory table in the [!INCLUDEssSampleDBnormal] database are deleted based on the year-to-date sales stored in the SalesPerson table. The first DELETE statement shows the ISO-compatible subquery solution, and the second DELETE statement shows the [!INCLUDEtsql] FROM extension to join the two tables.

E. Using TOP to limit the number of rows deleted

When a TOP (n) clause is used with DELETE, the delete operation is performed on a random selection of n number of rows. The following example deletes 20 random rows from the PurchaseOrderDetail table in the [!INCLUDEssSampleDBnormal] database that have due dates that are earlier than July 1, 2006.

If you have to use TOP to delete rows in a meaningful chronological order, you must use TOP together with ORDER BY in a subselect statement. The following query deletes the 10 rows of the PurchaseOrderDetail table that have the earliest due dates. To ensure that only 10 rows are deleted, the column specified in the subselect statement ( PurchaseOrderID ) is the primary key of the table. Using a nonkey column in the subselect statement may result in the deletion of more than 10 rows if the specified column contains duplicate values.

Deleting Rows From a Remote Table

Examples in this section demonstrate how to delete rows from a remote table by using a linked server or a rowset function to reference the remote table. A remote table exists on a different server or instance of SQL Server.

Applies to: [!INCLUDEsql2008-md] and later.

F. Deleting data from a remote table by using a linked server

The following example deletes rows from a remote table. The example begins by creating a link to the remote data source by using sp_addlinkedserver. The linked server name, MyLinkServer , is then specified as part of the four-part object name in the form server.catalog.schema.object.

G. Deleting data from a remote table by using the OPENQUERY function

The following example deletes rows from a remote table by specifying the OPENQUERY rowset function. The linked server name created in the previous example is used in this example.

H. Deleting data from a remote table by using the OPENDATASOURCE function

The following example deletes rows from a remote table by specifying the OPENDATASOURCE rowset function. Specify a valid server name for the data source by using the format server_name or server_name\instance_name.

Capturing the results of the DELETE statement

I. Using DELETE with the OUTPUT clause

The following example shows how to save the results of a DELETE statement to a table variable in the [!INCLUDEssSampleDBnormal] database.

J. Using OUTPUT with <from_table_name> in a DELETE statement

The following example deletes rows in the ProductProductPhoto table in the [!INCLUDEssSampleDBnormal] database based on search criteria defined in the FROM clause of the DELETE statement. The OUTPUT clause returns columns from the table being deleted, DELETED.ProductID , DELETED.ProductPhotoID , and columns from the Product table. This is used in the FROM clause to specify the rows to delete.

K. Delete all rows from a table

The following example deletes all rows from the Table1 table because a WHERE clause is not used to limit the number of rows deleted.

L. DELETE a set of rows from a table

The following example deletes all rows from the Table1 table that have a value greater than 1000.00 in the StandardCost column.

M. Using LABEL with a DELETE statement

The following example uses a label with the DELETE statement.

N. Using a label and a query hint with the DELETE statement

This query shows the basic syntax for using a query join hint with the DELETE statement. For more information on join hints and how to use the OPTION clause, see OPTION Clause (Transact-SQL).

O. Delete using a WHERE clause

This query shows how to delete using a WHERE clause and not using a FROM clause.

P. Delete based on the result of joining with another table

This example shows how to delete from a table based on the result from joining with another table.

Как удалить строку в sql

Команда DELETE удаляет из указанной таблицы строки, удовлетворяющие условию WHERE . Если предложение WHERE отсутствует, она удаляет из таблицы все строки, в результате будет получена рабочая, но пустая таблица.

Подсказка

TRUNCATE реализует более быстрый механизм удаления всех строк из таблицы.

Удалить строки в таблице, используя информацию из других таблиц в базе данных, можно двумя способами: применяя вложенные запросы или указав дополнительные таблицы в предложении USING . Выбор предпочитаемого варианта зависит от конкретных обстоятельств.

Предложение RETURNING указывает, что команда DELETE должна вычислить и возвратить значения для каждой фактически удалённой строки. Вычислить в нём можно любое выражение со столбцами целевой таблицы и/или столбцами других таблиц, упомянутых в USING . Список RETURNING имеет тот же синтаксис, что и список результатов SELECT .

Чтобы удалять данные из таблицы, необходимо иметь право DELETE для неё, а также право SELECT для всех таблиц, перечисленных в предложении USING , и таблиц, данные которых считываются в условии .

Параметры

Предложение WITH позволяет задать один или несколько подзапросов, на которые затем можно ссылаться по имени в запросе DELETE . Подробнее об этом см. Раздел 7.8 и SELECT . имя_таблицы

Имя (возможно, дополненное схемой) таблицы, из которой будут удалены строки. Если перед именем таблицы добавлено ONLY , соответствующие строки удаляются только из указанной таблицы. Без ONLY строки будут также удалены из всех таблиц, унаследованных от указанной. При желании, после имени таблицы можно указать * , чтобы явно обозначить, что операция затрагивает все дочерние таблицы. псевдоним

Альтернативное имя целевой таблицы. Когда указывается это имя, оно полностью скрывает фактическое имя таблицы. Например, в запросе DELETE FROM foo AS f дополнительные компоненты оператора DELETE должны обращаться к целевой таблице по имени f , а не foo . элемент_FROM

Табличное выражение, позволяющее добавить в условие WHERE столбцы из других таблиц. В этом выражении используется тот же синтаксис, что и в предложении FROM оператора SELECT ; например, в нём можно определить псевдоним для таблицы. Повторять в нём имя целевой таблицы нужно, только если требуется определить замкнутое соединение (в этом случае для данного имени должен определяться псевдоним). условие

Выражение, возвращающее значение типа boolean . Удалены будут только те строки, для которых это выражение возвращает true . имя_курсора

Имя курсора, который будет использоваться в условии WHERE CURRENT OF . С таким условием будет удалена строка, выбранная из этого курсора последней. Курсор должен образовываться запросом, не применяющим группировку, к целевой таблице команды DELETE . Заметьте, что WHERE CURRENT OF нельзя задать вместе с логическим условием. За дополнительными сведениями об использовании курсоров с WHERE CURRENT OF обратитесь к DECLARE . выражение_результата

Выражение, которое будет вычисляться и возвращаться командой DELETE после удаления каждой строки. В этом выражении можно использовать имена любых столбцов таблицы имя_таблицы или таблиц, перечисленных в списке USING . Чтобы получить все столбцы, достаточно написать * . имя_результата

Имя, назначаемое возвращаемому столбцу.

Выводимая информация

В случае успешного завершения, DELETE возвращает метку команды в виде

Здесь число — количество удалённых строк. Заметьте, что это число может быть меньше числа строк, соответствующих условию , если удаления были подавлены триггером BEFORE DELETE . Если число равно 0, это означает, что запрос не удалил ни одной строки (это не считается ошибкой).

Если команда DELETE содержит предложение RETURNING , её результат будет похож на результат оператора SELECT (с теми же столбцами и значениями, что содержатся в списке RETURNING ), полученный для строк, удалённых этой командой.

Замечания

Postgres Pro позволяет ссылаться на столбцы других таблиц в условии WHERE , когда эти таблицы перечисляются в предложении USING . Например, удалить все фильмы определённого продюсера можно так:

По сути в этом запросе выполняется соединение таблиц films и producers , и все успешно включённые в соединение строки в films помечаются для удаления. Этот синтаксис не соответствует стандарту. Следуя стандарту, эту задачу можно решить так:

В ряде случаев запрос в стиле соединения легче написать и он может работать быстрее, чем в стиле вложенного запроса.

Примеры

Удаление всех фильмов, кроме мюзиклов:

Очистка таблицы films :

Удаление завершённых задач с получением всех данных удалённых строк:

Удаление из tasks строки, на которой в текущий момент располагается курсор c_tasks :

Читать:
Как решать задачи с этажами

Похожие статьи