Delete (SQL)

Delete (SQL)

In the database structured query language (SQL), the DELETE statement removes one or more records from a table. A subset may be defined for deletion using a condition, otherwise all records are removed.[1]

Contents

Usage

The DELETE statement follows the syntax:

DELETE FROM table_name [WHERE condition];

Any rows that match the WHERE condition will be removed from the table. If the WHERE clause is omitted, all rows in the table are removed. The DELETE statement should thus be used with caution.

The DELETE statement does not return any rows; that is, it will not generate a result set.

Executing a DELETE statement can cause triggers to run that can cause deletes in other tables. For example, if two tables are linked by a foreign key and rows in the referenced table are deleted, then it is common that rows in the referencing table would also have to be deleted to maintain referential integrity.

Examples

Delete rows from table pies where the column flavour equals Lemon Meringue:

DELETE FROM pies WHERE flavour='Lemon Meringue';

Delete rows in trees, if the value of height is smaller than 80.

DELETE FROM trees WHERE height < 80;

Delete all rows from mytable:

DELETE FROM mytable;

Delete rows from mytable using a subquery in the where condition:

DELETE FROM mytable WHERE id IN (SELECT id FROM mytable2)

Delete rows from mytable using a list of values:

DELETE FROM mytable WHERE id IN (value1, value2, value3, value4, value5)

Example with related tables

Suppose there is a simple database that lists people and addresses. More than one person can live at a particular address and a person can live at more than one address (this is an example of a many-to-many relationship). The database only has three tables, person, address, and pa, with the following data:

person

pid name
1 Joe
2 Bob
3 Ann

address

aid description
100 2001 Main St.
200 35 Pico Blvd.

pa

pid aid
1 100
2 100
3 100
1 200

The pa table relates the person and address tables, showing that Joe, Bob and Ann all live at 2001 Main Street, but Joe also takes up residence on Pico Boulevard.

In order to remove joe from the database, two deletes must be executed:

 DELETE FROM person WHERE pid=1
 DELETE FROM pa WHERE pid=1

To maintain referential integrity, Joe's records must be removed from both person and pa. The means by which integrity is sustained can happen differently in varying relational database management systems[citation needed]. It could be that beyond just having three tables, the database also has been set up with a trigger so that whenever a row is deleted from person any linked rows would be deleted from pa. Then the first statement:

 DELETE FROM person WHERE pid=1

would automatically trigger the second:

 DELETE FROM pa WHERE pid=1

Related Commands

Deleting all rows from a table can be very time consuming. Some DBMS[clarification needed] offer a TRUNCATE TABLE command that works a lot quicker, as it only alters metadata and typically does not spend time enforcing constraints or firing triggers.

DELETE only deletes the rows. For deleting a table entirely the DROP command can be used.

References


Wikimedia Foundation. 2010.

Игры ⚽ Поможем написать реферат

Look at other dictionaries:

  • Delete (SQL) — У этого термина существуют и другие значения, см. Delete. DELETE  в языках, подобных SQL, DML операция удаления записей из таблицы. Критерий отбора записей для удаления определяется выражением where. В случае, если критерий отбора не… …   Википедия

  • SQL-92 — SQL (das Kürzel für Structured Query Language; offizielle Aussprache [ɛskjuːˈɛl], häufig auch [ˈsiːkwəl] →SEQUEL), ist eine Datenbanksprache zur Definition, Abfrage und Manipulation von Daten in relationalen Datenbanken. SQL ist von ANSI und ISO… …   Deutsch Wikipedia

  • SQL-99 — SQL (das Kürzel für Structured Query Language; offizielle Aussprache [ɛskjuːˈɛl], häufig auch [ˈsiːkwəl] →SEQUEL), ist eine Datenbanksprache zur Definition, Abfrage und Manipulation von Daten in relationalen Datenbanken. SQL ist von ANSI und ISO… …   Deutsch Wikipedia

  • SQL — Desarrollador(es) IBM ISO/IEC 9075 1:2008 Información general Paradigma Multiparadigma …   Wikipedia Español

  • DELETE — DELETE  в языках, подобных SQL, DML операция удаления записей из таблицы. Критерий отбора записей для удаления определяется выражением where. В случае, если критерий отбора не определён, выполняется удаление всех записей. В СУБД,… …   Википедия

  • SQL — Класс языка: Мультипарадигмальный Появился в: 1974 Автор(ы): Дональд Чэмбэрлин Рэймонд Бойс Релиз: SQL:2008 (2008) Типизация данных …   Википедия

  • SQL-92 — SQL 92  третья версия языка запросов к базам данных SQL. В отличие от стандарта SQL 89, третья версия стала весьма существенным обновлением языка. За исключением некоторых мелких противоречий стандарт SQL 89 практически полностью совместим… …   Википедия

  • SQL:2008 — SQL:2008  шестая версия (ревизия) языка запросов баз данных SQL. Содержание 1 Общие сведения 2 Новшества 3 …   Википедия

  • SQL Server Integration Services — (SSIS) is a component of Microsoft SQL Server 2005 and 2008. It replaces Data Transformation Services, which has been a feature of SQL Server since Version 7.0. Unlike DTS, which was included in all versions, SSIS is available in the Standard ,… …   Wikipedia

  • Delete — Delete: Delete оператор языка программирования C++. Delete операция в языках, подобных SQL. Delete клавиша на клавиатуре компьютера …   Википедия

Share the article and excerpts

Direct link
Do a right-click on the link above
and select “Copy Link”