Mysql
 sql >> Database >  >> RDS >> Mysql

Come troncare la tabella in MySQL

A volte potrebbe essere necessario eliminare tutte le righe in una tabella nel database MySQL. Esistono diversi modi per farlo utilizzando le istruzioni TRUNCATE TABLE, DROP TABLE e DELETE. In questo articolo, vedremo come troncare la tabella in MySQL usando l'istruzione MySQL TRUNCATE TABLE.

Come troncare la tabella in MySQL

Ecco come troncare la tabella in MySQL usando l'istruzione TRUNCATE TABLE. Ecco la sintassi dell'istruzione MySQL TRUNCATE TABLE.

TRUNCATE [TABLE] table_name;

Nella query precedente, devi specificare il nome della tabella da troncare, al posto di nome_tabella.

La parola chiave TABLE è facoltativa dopo TRUNCATE.

Bonus Lettura:MySQL DROP VIEW

Esempi di MySQL TRUNCATE TABLE

Supponiamo che tu abbia la tabella ordini in MySQL.

mysql> create table daily_orders(id int, order_date date,amount int);

mysql> insert into daily_orders(id, order_date, amount) 
       values(1, '2020-07-01',250),(2,'2020-07-02',320),
       (3,'2020-07-03',450);

mysql> select * from daily_orders;
+------+------------+--------+
| id   | order_date | amount |
+------+------------+--------+
|    1 | 2020-07-01 |    250 |
|    2 | 2020-07-02 |    320 |
|    3 | 2020-07-03 |    450 |
+------+------------+--------+

Ecco la query SQL per troncare la tabella in MySQL.

mysql> truncate table daily_orders;

mysql> select * from daily_orders;
Empty set (0.00 sec)

Bonus Leggi:Come creare un indice in MySQL

MySQL TRUNCATE vs DELETE

TRUNCATE TABLE è simile all'istruzione DELETE in MySQL. Tuttavia, ci sono alcune differenze chiave. Ecco la differenza tra TRUNCATE e DELETE in MySQL.

ELIMINA MySQL

  • DELETE è un'istruzione DML (Data Manipulation Language). Elimina una riga alla volta. Quindi viene eseguito utilizzando il blocco riga e ogni riga è bloccata per l'eliminazione
  • Le operazioni di DELETE vengono registrate
  • Puoi specificare la clausola WHERE nell'istruzione DELETE per eliminare solo righe specifiche nella tabella
  • DELETE è più lento di troncare poiché le operazioni di eliminazione vengono registrate

MySQL TRUNCATE

  • TRUNCATE è un comando DDL (Data Description Language) che blocca la tabella per l'eliminazione ma non le righe.
  • TRUNCATE rimuove tutti i dati nella tabella. Quindi non puoi specificare la clausola WHERE nell'istruzione TRUNCATE.
  • Le operazioni TRUNCATE non vengono registrate e sono quindi molto più veloci dell'istruzione DELETE.

Il rollback è possibile sia nelle istruzioni DELETE che TRUNCATE.

Bonus Leggi:Come creare stored procedure in MySQL

Come troncare la tabella con la chiave esterna

Se la tua tabella ha un vincolo di chiave esterna, quando esegui l'istruzione TRUNCATE per quella tabella otterrai il seguente errore.

ERROR 1217 (23000): Cannot delete or update a parent row: a foreign key 
constraint fails

Quindi è necessario accedere a MySQL e disabilitare i controlli della chiave esterna prima di troncare le tabelle, utilizzando il seguente comando

SET FOREIGN_KEY_CHECKS=0;

Dopo aver troncato le tabelle, riattiva i controlli della chiave esterna

SET FOREIGN_KEY_CHECKS=1;

Bonus Leggi:Come creare utenti in MySQL

Come troncare tutte le tabelle in MySQL

MySQL TRUNCATE TABLE ti consente di eliminare solo una tabella alla volta. Quindi, se vuoi eliminare più tabelle, devi emettere comandi TRUNCATE TABLE separati. Ecco un esempio per troncare più tabelle table1, table2, table3, …

mysql> TRUNCATE TABLE table1;
mysql> TRUNCATE TABLE table2;
mysql> TRUNCATE TABLE table3;

Bonus Leggi:Come creare database in MySQL

Ecco una query SQL per generare più istruzioni TRUNCATE TABLE, utilizzando i nomi delle tabelle nel database. Sostituisci DATABASE_NAME nella query seguente con il nome del tuo database.

mysql> SELECT Concat('TRUNCATE TABLE ',table_schema,'.',TABLE_NAME, ';')
     FROM INFORMATION_SCHEMA.TABLES where  table_schema in ('sample');
+------------------------------------------------------------+
| Concat('TRUNCATE TABLE ',table_schema,'.',TABLE_NAME, ';') |
+------------------------------------------------------------+
| TRUNCATE TABLE sample.a;                                   |
| TRUNCATE TABLE sample.calendar;                            |
| TRUNCATE TABLE sample.categories;                          |
| TRUNCATE TABLE sample.daily_orders;                        |
| TRUNCATE TABLE sample.login;                               |
| TRUNCATE TABLE sample.meeting;                             |
| TRUNCATE TABLE sample.order_status;                        |
| TRUNCATE TABLE sample.orders;                              |
| TRUNCATE TABLE sample.orders2;                             |
| TRUNCATE TABLE sample.orders3;                             |
| TRUNCATE TABLE sample.product_sales;                       |
| TRUNCATE TABLE sample.products;                            |
| TRUNCATE TABLE sample.sales;                               |
| TRUNCATE TABLE sample.user_data;                           |
| TRUNCATE TABLE sample.users;                               |
+------------------------------------------------------------+

Utilizzare il risultato della query precedente per troncare tutte le tabelle nel database. Si spera che ora sia possibile troncare la tabella in MySQL

Ubiq semplifica la visualizzazione dei dati in pochi minuti e il monitoraggio in dashboard in tempo reale. Provalo oggi!