Câu hỏi phỏng vấn SQL
Câu hỏi

Describe the difference between truncate and delete

Câu trả lời

To answer the interview question "Describe the difference between TRUNCATE and DELETE in SQL," you can provide a detailed comparison highlighting the key differences between these two commands:

TRUNCATE vs. DELETE in SQL

Definition and Usage

  • DELETE: The DELETE command is a Data Manipulation Language (DML) command used to remove specific rows from a table based on a condition specified in the WHERE clause. If no condition is specified, it deletes all rows from the table.
  • TRUNCATE: The TRUNCATE command is a Data Definition Language (DDL) command used to remove all rows from a table. It does not allow for conditions and deletes all rows in one operation.

Syntax

  • DELETE:
    sql Copy
    DELETE FROM table_name WHERE condition;
    Example:
    sql Copy
    DELETE FROM Employee WHERE City = 'San Antonio';
  • TRUNCATE:
    sql Copy
    TRUNCATE TABLE table_name;
    Example:
    sql Copy
    TRUNCATE TABLE Employee;

Logging and Performance

  • DELETE: Each row deletion is logged individually in the transaction log, which can make the operation slower, especially for large tables. This logging allows for the possibility of rolling back the operation if it is part of a transaction.
  • TRUNCATE: TRUNCATE deallocates the data pages used by the table, which is a faster operation as it does not log individual row deletions. Instead, it logs the deallocation of the data pages. This makes TRUNCATE significantly faster than DELETE for large tables.

Identity Columns

  • DELETE: Does not reset the identity column values. The identity values continue from where they left off.
  • TRUNCATE: Resets the identity column values to the seed value defined for the column.

Triggers

  • DELETE: Can activate triggers defined on the table because it operates on individual rows.
  • TRUNCATE: Does not activate triggers because it does not operate on individual rows but rather on the entire table.

Rollback

  • DELETE: Can be rolled back if it is part of a transaction.
  • TRUNCATE: Can also be rolled back if it is part of a transaction, contrary to some misconceptions.

Permissions

  • DELETE: Requires DELETE permissions on the table.
  • TRUNCATE: Requires ALTER table permissions.

Space and Statistics

  • DELETE: Does not free the space occupied by the table; it retains the space and object statistics.
  • TRUNCATE: Frees the space occupied by the table and removes all statistics and allocated space.

Use Cases

  • DELETE: Use DELETE when you need to remove specific rows based on a condition or wh...
middle

middle

Gợi ý câu hỏi phỏng vấn

middle

Discuss INNER JOIN ON vs WHERE clause (with multiple FROM tables)

senior

What is the difference among UNION , MINUS and INTERSECT ?

middle

What is the difference between INNER JOIN , OUTER JOIN , FULL OUTER JOIN ?

Bình luận

Chưa có bình luận nào

Chưa có bình luận nào