Как удалить таблицу через запрос в sql
Для создания таблиц используется команда CREATE TABLE . Эта команды применяет ряд операторов, которые определяют столбцы таблицы и их атрибуты. Общий формальный синтаксис команды CREATE TABLE:
После команды CREATE TABLE идет название таблицы. Имя таблицы выполняет роль ее идентификатора в базе данных, поэтому оно должно быть уникальным. Затем в скобках перечисляются названия столбцов, их типы данных и атрибуты. В самом конце можно определить атрибуты для всей таблицы. Атрибуты столбцов, а также атрибуты таблицы указывать необязательно.
Создадим простейшую таблицу. Для этого выполним следующий скрипт:
Таблица не может создаваться сама по себе. Она всегда создается в определенной базе данных. Вначале здесь создается база данных productsdb. И затем, чтобы указать, что все дальнейшие операции, в том числе создание таблицы, будут производиться с этой базой данных, применяется команда USE .
Далее собственно идет создание таблицы, которая называется Customers. Она определяет четыре столбца: Id, Age, FirstName, LastName. Первые два столбца представляют идентификатор клиента и его возраст и имеют тип INT , то есть будут хранить числовые значения. Следующие столбцы представляют имя и фамилию клиента и имеют тип VARCHAR(20) , то есть представляют строку длиной не более 20 символов. В данном случае для каждого столбца определены имя и тип данных, при этом атрибуты столбцов и таблицы в целом отсутствуют.

И в результате выполнения этой команды будет создана база данных productsdb, в которой будет создана таблица Customers.
Переименование таблиц
Если после создания таблицы мы захотим ее переименовать, то для этого нужно использовать команду RENAME TABLE , которая имеет следующий синтаксис:
Например, переименуем таблицу Customers в Clients:
Полное удаление данных
Для полного удаления данных, очистки таблицы применяется команда TRUNCATE TABLE . Например, очистим таблицу Clients:
Удаление таблиц
Для удаления таблицы из БД применяется команда DROP TABLE , после которой указывается название удаляемой таблицы. Например, удалим таблицу Clients:
Как удалить таблицу через запрос в sql
Specify the schema containing the table. If you omit schema , then Oracle Database assumes the table is in your own schema.
Specify the name of the table to be dropped. Oracle Database automatically performs the following operations:
All rows from the table are dropped.
All table indexes and domain indexes are dropped, as well as any triggers defined on the table, regardless of who created them or whose schema contains them. If table is partitioned, then any corresponding local index partitions are also dropped.
All the storage tables of nested tables and LOBs of table are dropped.
When you drop a range-, hash-, or list-partitioned table, then the database drops all the table partitions. If you drop a composite-partitioned table, then all the partitions and subpartitions are also dropped.
When you drop a partitioned table with the PURGE keyword, the statement executes as a series of subtransactions, each of which drops a subset of partitions or subpartitions and their metadata. This division of the drop operation into subtransactions optimizes the processing of internal system resource consumption (for example, the library cache), especially for the dropping of very large partitioned tables. As soon as the first subtransaction commits, the table is marked UNUSABLE . If any of the subtransactions fails, then the only operation allowed on the table is another DROP TABLE . PURGE statement. Such a statement will resume work from where the previous DROP TABLE statement failed, assuming that you have corrected any errors that the previous operation encountered.
You can list the tables marked UNUSABLE by such a drop operation by querying the status column of the *_TABLES , *_PART_TABLES , *_ALL_TABLES , or *_OBJECT_TABLES data dictionary views, as appropriate.
Oracle Database VLDB and Partitioning Guide for more information on dropping partitioned tables.
For an index-organized table, any mapping tables defined on the index-organized table are dropped.
For a domain index, the appropriate drop routines are invoked. Refer to Oracle Database Data Cartridge Developer’s Guide for more information on these routines.
If any statistics types are associated with the table, then the database disassociates the statistics types with the FORCE clause and removes any user-defined statistics collected with the statistics type.
ASSOCIATE STATISTICS and DISASSOCIATE STATISTICS for more information on statistics type associations
If the table is not part of a cluster, then the database returns all data blocks allocated to the table and its indexes to the tablespaces containing the table and its indexes.
To drop a cluster and all its the tables, use the DROP CLUSTER statement with the INCLUDING TABLES clause to avoid dropping each table individually. See DROP CLUSTER.
If the table is a base table for a view, a container or master table of a materialized view, or if it is referenced in a stored procedure, function, or package, then the database invalidates these dependent objects but does not drop them. You cannot use these objects unless you re-create the table or drop and re-create the objects so that they no longer depend on the table.
If you choose to re-create the table, then it must contain all the columns selected by the subqueries originally used to define the materialized views and all the columns referenced in the stored procedures, functions, or packages. Any users previously granted object privileges on the views, stored procedures, functions, or packages need not be regranted these privileges.
If the table is a master table for a materialized view, then the materialized view can still be queried, but it cannot be refreshed unless the table is re-created so that it contains all the columns selected by the defining query of the materialized view.
If the table has a materialized view log, then the database drops this log and any other direct-path INSERT refresh information associated with the table.
Restrictions on Dropping Tables
You cannot directly drop the storage table of a nested table. Instead, you must drop the nested table column using the ALTER TABLE . DROP COLUMN clause.
You cannot drop the parent table of a reference-partitioned table. You must first drop all reference-partitioned child tables.
You cannot drop a table that uses a flashback data archive for historical tracking. You must first disable the table’s use of the flashback data archive.
Specify CASCADE CONSTRAINTS to drop all referential integrity constraints that refer to primary and unique keys in the dropped table. If you omit this clause, and such referential integrity constraints exist, then the database returns an error and does not drop the table.
Specify PURGE if you want to drop the table and release the space associated with it in a single step. If you specify PURGE , then the database does not place the table and its dependent objects into the recycle bin.
You cannot roll back a DROP TABLE statement with the PURGE clause, nor can you recover the table if you have dropped it with the PURGE clause.
Using this clause is equivalent to first dropping the table and then purging it from the recycle bin. This clause lets you save one step in the process. It also provides enhanced security if you want to prevent sensitive material from appearing in the recycle bin.
Oracle Database Administrator’s Guide for information on the recycle bin and naming conventions for objects in the recycle bin
DROP TABLE в SQL
Оператор DROP TABLE используется для удаления таблиц в базе данных. Например:
Здесь мы удаляем таблицу с именем my_table.
Также убедитесь, что у вас есть права администратора или (права) DROP для запуска этой команды.
Примечание: При удалении таблицы все записи в таблице также удаляются.
DROP TABLE IF EXISTS
При удалении несуществующей таблицы SQL выдаст ошибку. Чтобы решить эту проблему, мы можем добавить часть IF EXISTS при удалении таблицы. Например:
Здесь мы удалим таблицу только в том случае, если она существует с таким же именем.