Auto decrement T-SQL ID when deleting records? - sql

In one of our apps, we read in data from a file and expand it into several tables. If any part of the file is corrupt, we halt the read, and delete whatever data got inserted.
The issue, here, is that we have an auto-increment ID on one of the import tables, and when we remove a problem file, the ID continues from its post-import value, rather than its pre-import value.
In other words...
ID starts at 50.
Insert 100 records, max ID is now 150.
Delete 100 records, max ID is still 150.
Insert 50 records, ID is 200.
We've "lost" the range of 100 records. Is there an "auto decrement" equivalent to go with the auto increment?

Autonumbers shouldn't be that meaningful to you. Their guarantee is they provide uniqueness nothing more. You can still reseed if you are using sql server DBCC CHECKIDENT.
Checks the current identity value for the specified table and, if it is needed, changes the identity value. You can also use DBCC CHECKIDENT to manually set a new seed value for the identity column.
From BOL:
The following example forces the current identity value in the Employee table in the AdventureWorks database to a value of 30.
USE AdventureWorks;
GO
DBCC CHECKIDENT ('HumanResources.Employee', RESEED, 30);
GO
I am not recommending this but just pointing it out. DBCC CHECKIDENT can throw an error if you try to reseed to a value that is already being used, in that case you'd have to have logic if you were relying upon such a task.
I question the thought process of what makes these numbers so important? It sounds like you want one additional field called LineNumber that is incremented or decremented, etc. But even in this case you have to handle the rows that come after the deleted record. So if you have 50 rows and you delete row 25 you have to renumber anything greater then 25:
UPDATE
MyTable
SET LineItemNumber = LineItemNumber - 1
WHERE
LineItemNumber > #LineItemNumberToBeDeleted

Auto decrementing on delete sounds like a bad idea. If done incorrectly, you can start injecting much bigger bugs into your code. If the IDs are a big deal, try giving it a batch number, and an incremented id for every item in the batch. You could also use guids, though they're not sequential.

You can reseed the AutoIncrement ID by doing:
DBCC CHECKIDENT
(
tablename
[, [NORESEED | RESEED [, newreseedvalue]]]
)
However I would not recommend this as a best practice. Your query should be atomic (It commits and updates the table or Rollsback if it fails (leaving the ID untouched). To implement an atomic query you could use a TRANSACTION.
BEGIN TRY
BEGIN TRANSACTION #TranName;
-- Your database logic here
COMMIT TRANSACTION #TranName;
END TRY
BEGIN CATCH
ROLLBACK TRAN #TranName;
END CATCH
GO
Sources:
http://msdn.microsoft.com/en-us/library/ms188929.aspx
http://www.techrepublic.com/blog/datacenter/how-do-i-reseed-a-sql-server-identity-column/406

In my experience, a best practice for this portion of an ETL (Extract Transform Load) process is to perform the bulk load in more than one step:
Load data from file(s) into empty "loading" or "staging" table(s) which exist just for this purpose. This detects file-level corruption.
Check data for referential integrity and other validations. This detects data-level errors.
Insert only valid data into the "real" tables. This avoids unnecessary deletes and avoids wasting auto increment values.
Log or report data which failed the import checks.
Immediately before the next run of this process, truncate the "loading" tables.

Related

How can I get the last issued sequence ID in vertica?

Background: I am migrating from postgreSQL to Vertica and found, that there are some issues in IDENTITY or AUTO_INCREMENT columns. One of these issues is, that vertica cannot assign values to IDENTITY columns or alter a column, that already has data into an IDENTITY column. Therefore I created a sequence and set the default value of the column to be unique doing:
SELECT MAX(id_column) FROM MY_SCHEMA.my_table;
which is 12345
CREATE SEQUENCE MY_SCHEMA.seq_id_column MINVALUE 12346 CACHE 1;
ALTER TABLE MY_SCHEMA.my_table
ALTER COLUMN id_column SET DEFAULT(MY_SCHEMA.seq_id_column.nextval);
ALTER TABLE MY_SCHEMA.log ADD UNIQUE(id_column);
Which works as expected. In this case, I have the cache deactivated, as I am on a single node installation and I want my ID column to be contiguous. However, this is not an option on a cluster installation as the needed lock leads to a bottleneck.
Question: In a vertica cluster with several nodes, how can I access the ID of the last insert in a session (without an additional select)?
E.g. in postgreSQL I could do something like
INSERT INTO MY_SCHEMA.my_table RETURNING id_column;
which does not work in Vertica. Furthermore, the LAST_INSERT_ID() function of Vertica does not work for named sequences. I also feel, that querying the current_value of MY_SCHEMA.seq_id_column could be giving wrong results due to caching, but I am unsure about this.
Why no additional SELECT?
To my knowledge, the select will only give correct values after a commit. I cannot do a commit after every single insert due to performance.
The comments from LukStorms pointed me in the right direction.
The NEXTVAL() function (as far as I have tested) gives contiguous values in the case, where one single session queries them. Furthermore, on concurrent access, if issued after an insert, CURRVAL retrieves the cached value, which is guaranteed to be unique but not necessarily contiguous. As I never call NEXTVAL anywhere else as in my default clause, this solves the problem for me, although there might be cases, where an additional call to NEXTVAL between inserts increments the sequence counter.
One case I can think of (and that I will test in the future) is what happens if AUTO COMMIT is set to OFF, which is ON by default for the vertica client drivers.
UPDATE:
This even seems to work with AUTOCOMMIT being OFF (shown using the vertica-python client driver, where C is the connection and cur the cursor):
cur.execute("SELECT NEXTVAL('my_schema.my_sequence');")
cur.fetchall()
--> 1
cur.execute("SELECT CURRVAL('my_schema.my_sequence');")
cur.fetchall()
--> 1
cur.execute("SET SESSION AUTOCOMMIT TO OFF")
cur.execute("SELECT NEXTVAL('my_schema.my_sequence');")
cur.execute("SELECT NEXTVAL('my_schema.my_sequence');")
cur.execute("SELECT NEXTVAL('my_schema.my_sequence');")
cur.execute("SELECT CURRVAL('my_schema.my_sequence');")
cur.fetchall()
--> 4
However, this seems to be unchanged during a rollback of the connection. So the following happens:
C.rollback()
cur.execute("SELECT CURRVAL('my_schema.my_sequence');")
cur.fetchall()
--> 4

AS400 DB2 Duplicate Key Error during Insert in Table with PK Identity Column

I got a Table with an Auto Increment Column which looks like:
ALTER TABLE SOMESCHEMA.SOMETABLE
ALTER COLUMN ID
SET DATA TYPE INTEGER GENERATED BY DEFAULT
SET INCREMENT BY 1
SET NO ORDER
SET NO CYCLE
SET MINVALUE 1
SET MAXVALUE 2147483647
SET NO CACHE;
As long as i let the DBMS generate the Ids everything works fine and I can get the generated Id via:
SELECT IDENTITY_VAL_LOCAL() FROM sysibm.sysdummy1
But sometimes i need to insert a row with an ID of my choice and there i get into trouble.
Lets say we got a single row in the table with ID 1.Now i insert a new row with a manually assigned id of 2. The next time i try to insert a new row without a preset ID i get an error SQL0803 "DUPLICATE KEY".
I assume the internal "NextId" field for that Auto-Increment Column doesnt update itself if the Id of a row is manually set.
So I tried reseting this field with:
ALTER TABLE SOMESCHEMA.SOMETABLE ALTER COLUMN ID RESTART WITH 3
But this causes a permanent Table lock, which i dont know how to unlock.
How can i get this "Mixed-Mode" ID-Column working? Is it possible to get it to work like MySQL where the DBMS automatically updates the "NextID" upon a manually-Id Insert? If not, how can I release that {insert swear-word here} lock that pops up if i try to reset the NextId?
SQL0913 isn't creating a lock - it is reporting that a lock exists. ALTER TABLE needs an exclusive lock on the table in order to reset the ID number. A table can be locked by another process having it open, or it can be locked by this process if there are uncommitted rows.
There is another reason the table is in use - soft close (or pseudo-close). For performance reasons, DB2 for i keeps cursors in memory so that they can be reused as efficiently as possible. So even if you say CLOSE CURSOR, DB2 keeps it in memory. These soft closed cursors can be closed by the command ALCOBJ OBJ((SOMSCHEMA/SOMETABLE *FILE *EXCL)) WAIT(1) CONFLICT(*RQSRLS) The CONFLICT(*RQSRLS) parameter tells DB2 to close all soft closed cursors.
So the root of the issue is that DB2 wants exclusive access to the table. Which is sort of a design question, because typically one doesn't manipulate the table's structure during the work day. It sounds as though this table is sometimes a parent and sometimes a child when it comes to ID numbers. If that is the case, may I suggest that you ALTER the table again?
I think the implementation might be better if you used a trigger rather than auto-increment. Fire the trigger on INSERT. If ID is supplied, do nothing. If ID is not supplied, SELECT MAX(ID)+1 and use that as the actual ID number you commit to the database.
ALTER TABLE table_name ALTER COLUMN column_name RESTART WITH 99999;
Fixed my issue. "99999" is the next ID to be used for example

get Primary Key from SP

With SQL, when inserting values into a Table from a SP, is it possible to get the value of the Primary Key before the values are added to the Table?
This is certainly possible, leveraging the power of relational databases. Assuming, like Martin Smith said, that you are using an autogenerated key, then you can use a transaction to do what you're looking for.
Here's the general idea:
Start a transaction.
Do the insertion.
Use the primary key to do whatever you need to do, including updated the inserted row to reflect the value.
Commit or rollback
By beginning a transaction before your insert, you can assure that no one else will be able to see the new rows until you commit your transaction. If the key is not to your liking, you can rollback the transaction, and no one else will know. If the key is adequate, you can modify the rows you have just inserted before committing.
Since you have a transaction, no one else can see the intermediate data you have inserted before you commit. Thus, you can update the rows that you have just inserted as if you have the primary key before your actual insert.
If you are using SQL Server the best way to do this is with your MERGE or INSERT command use the OUTPUT clause to get your key back. Even though this is not before the insert you can use the results of the OUTPUT to join back the results of your data to insert subsequent children records.
Also if you are using SQL server you can look at IDENT_CURRENT function which will return the current identity value of a table. If you are writing your SQL in a set based fashion the OUTPUT that I mention above works best for me.

Why 'delete from table' takes a long time when 'truncate table' takes 0 time?

(I've tried this in MySql)
I believe they're semantically equivalent. Why not identify this trivial case and speed it up?
truncate table cannot be rolled back, it is like dropping and recreating the table.
...just to add some detail.
Calling the DELETE statement tells the database engine to generate a transaction log of all the records deleted. In the event the delete was done in error, you can restore your records.
Calling the TRUNCATE statement is a blanket "all or nothing" that removes all the records with no transaction log to restore from. It is definitely faster, but should only be done when you're sure you don't need any of the records you're going to remove.
Delete from table deletes each row from the one at a time and adds a record into the transaction log so that the operation can be rolled back. The time taken to delete is also proportional to the number of indexes on the table, and if there are any foreign key constraints (for innodb).
Truncate effectively drops the table and recreates it and can not be performed within a transaction. It therefore required fewer operations and executes quickly. Truncate also does not make use of any on delete triggers.
Exact details about why this is quicker in MySql can be found in the MySql documentation:
http://dev.mysql.com/doc/refman/5.0/en/truncate-table.html
Your question was about MySQL and I know little to nothing about MySQL as a product but I thought I'd add that in SQL Server a TRUNCATE statement can be rolled back. Try it for yourself
create table test1 (col1 int)
go
insert test1 values(3)
begin tran
truncate table test1
select * from test1
rollback tran
select * from test1
In SQL Server TRUNCATE is logged, it's just not logged in such a verbose way as DELETE is logged. I believe it's referred to as a minimally logged operation. Effectively the data pages still contain the data but their extents have been marked for deletion. As long as the data pages still exist you can roll back the truncate. Hope this is helpful. I'd be interested to know the results if somebody tries it on MySQL.
For MySql 5 using InnoDb as the storage engine, TRUNCATE acts just like DELETE without a WHERE clause: i.e. for large tables it takes ages because it deletes rows one-by-one. This is changing in version 6.x.
see
http://dev.mysql.com/doc/refman/5.1/en/truncate-table.html
for 5.1 info (row-by-row with InnoDB) and
http://blogs.mysql.com/peterg/category/personal-opinion/
for changes in 6.x
Editor's note
This answer is clearly contradicted by the MySQL documentation:
"For an InnoDB table before version 5.0.3, InnoDB processes TRUNCATE TABLE by deleting rows one by one. As of MySQL 5.0.3, row by row deletion is used only if there are any FOREIGN KEY constraints that reference the table. If there are no FOREIGN KEY constraints, InnoDB performs fast truncation by dropping the original table and creating an empty one with the same definition, which is much faster than deleting rows one by one."
Truncate is on a table level, while Delete is on a row level. If you would translate this to sql in an other syntax, truncate would be:
DELETE * FROM table
thus deleting all rows at once, while DELETE statement (in PHPMyAdmin) goes like:
DELETE * FROM table WHERE id = 1
DELETE * FROM table WHERE id = 2
Just until the table is empty. Each query taking a number of (milli)seconds which add up to taking longer than a truncate.

What's the difference between TRUNCATE and DELETE in SQL

What's the difference between TRUNCATE and DELETE in SQL?
If your answer is platform specific, please indicate that.
Here's a list of differences. I've highlighted Oracle-specific features, and hopefully the community can add in other vendors' specific difference also. Differences that are common to most vendors can go directly below the headings, with differences highlighted below.
General Overview
If you want to quickly delete all of the rows from a table, and you're really sure that you want to do it, and you do not have foreign keys against the tables, then a TRUNCATE is probably going to be faster than a DELETE.
Various system-specific issues have to be considered, as detailed below.
Statement type
Delete is DML, Truncate is DDL (What is DDL and DML?)
Commit and Rollback
Variable by vendor
SQL*Server
Truncate can be rolled back.
PostgreSQL
Truncate can be rolled back.
Oracle
Because a TRUNCATE is DDL it involves two commits, one before and one after the statement execution. Truncate can therefore not be rolled back, and a failure in the truncate process will have issued a commit anyway.
However, see Flashback below.
Space reclamation
Delete does not recover space, Truncate recovers space
Oracle
If you use the REUSE STORAGE clause then the data segments are not de-allocated, which can be marginally more efficient if the table is to be reloaded with data. The high water mark is reset.
Row scope
Delete can be used to remove all rows or only a subset of rows. Truncate removes all rows.
Oracle
When a table is partitioned, the individual partitions can be truncated in isolation, thus a partial removal of all the table's data is possible.
Object types
Delete can be applied to tables and tables inside a cluster. Truncate applies only to tables or the entire cluster. (May be Oracle specific)
Data Object Identity
Oracle
Delete does not affect the data object id, but truncate assigns a new data object id unless there has never been an insert against the table since its creation Even a single insert that is rolled back will cause a new data object id to be assigned upon truncation.
Flashback (Oracle)
Flashback works across deletes, but a truncate prevents flashback to states prior to the operation.
However, from 11gR2 the FLASHBACK ARCHIVE feature allows this, except in Express Edition
Use of FLASHBACK in Oracle
http://docs.oracle.com/cd/E11882_01/appdev.112/e41502/adfns_flashback.htm#ADFNS638
Privileges
Variable
Oracle
Delete can be granted on a table to another user or role, but truncate cannot be without using a DROP ANY TABLE grant.
Redo/Undo
Delete generates a small amount of redo and a large amount of undo. Truncate generates a negligible amount of each.
Indexes
Oracle
A truncate operation renders unusable indexes usable again. Delete does not.
Foreign Keys
A truncate cannot be applied when an enabled foreign key references the table. Treatment with delete depends on the configuration of the foreign keys.
Table Locking
Oracle
Truncate requires an exclusive table lock, delete requires a shared table lock. Hence disabling table locks is a way of preventing truncate operations on a table.
Triggers
DML triggers do not fire on a truncate.
Oracle
DDL triggers are available.
Remote Execution
Oracle
Truncate cannot be issued over a database link.
Identity Columns
SQL*Server
Truncate resets the sequence for IDENTITY column types, delete does not.
Result set
In most implementations, a DELETE statement can return to the client the rows that were deleted.
e.g. in an Oracle PL/SQL subprogram you could:
DELETE FROM employees_temp
WHERE employee_id = 299
RETURNING first_name,
last_name
INTO emp_first_name,
emp_last_name;
The difference between truncate and delete is listed below:
+----------------------------------------+----------------------------------------------+
| Truncate | Delete |
+----------------------------------------+----------------------------------------------+
| We can't Rollback after performing | We can Rollback after delete. |
| Truncate. | |
| | |
| Example: | Example: |
| BEGIN TRAN | BEGIN TRAN |
| TRUNCATE TABLE tranTest | DELETE FROM tranTest |
| SELECT * FROM tranTest | SELECT * FROM tranTest |
| ROLLBACK | ROLLBACK |
| SELECT * FROM tranTest | SELECT * FROM tranTest |
+----------------------------------------+----------------------------------------------+
| Truncate reset identity of table. | Delete does not reset identity of table. |
+----------------------------------------+----------------------------------------------+
| It locks the entire table. | It locks the table row. |
+----------------------------------------+----------------------------------------------+
| Its DDL(Data Definition Language) | Its DML(Data Manipulation Language) |
| command. | command. |
+----------------------------------------+----------------------------------------------+
| We can't use WHERE clause with it. | We can use WHERE to filter data to delete. |
+----------------------------------------+----------------------------------------------+
| Trigger is not fired while truncate. | Trigger is fired. |
+----------------------------------------+----------------------------------------------+
| Syntax : | Syntax : |
| 1) TRUNCATE TABLE table_name | 1) DELETE FROM table_name |
| | 2) DELETE FROM table_name WHERE |
| | example_column_id IN (1,2,3) |
+----------------------------------------+----------------------------------------------+
DROP
The DROP command removes a table from the database. All the tables' rows, indexes and privileges will also be removed. No DML triggers will be fired. The operation cannot be rolled back.
TRUNCATE
TRUNCATE removes all rows from a table. The operation cannot be rolled back and no triggers will be fired. As such, TRUNCATE is faster and doesn't use as much undo space as a DELETE. Table level lock will be added when Truncating.
DELETE
The DELETE command is used to remove rows from a table. A WHERE clause can be used to only remove some rows. If no WHERE condition is specified, all rows will be removed. After performing a DELETE operation you need to COMMIT or ROLLBACK the transaction to make the change permanent or to undo it. Note that this operation will cause all DELETE triggers on the table to fire. Row level lock will be added when deleting.
From: http://www.orafaq.com/faq/difference_between_truncate_delete_and_drop_commands
All good answers, to which I must add:
Since TRUNCATE TABLE is a DDL (Data Defination Language), not a DML (Data Manipulation Langauge) command, the Delete Triggers do not run.
Summary of Delete Vs Truncate in SQL server
For Complete Article follow this link : http://codaffection.com/sql-server-article/delete-vs-truncate-in-sql-server/
Taken from dotnet mob article :Delete Vs Truncate in SQL Server
With SQL Server or MySQL, if there is a PK with auto increment, truncate will reset the counter.
"Truncate doesn't log anything" is correct. I'd go further:
Truncate is not executed in the context of a transaction.
The speed advantage of truncate over delete should be obvious. That advantage ranges from trivial to enormous, depending on your situation.
However, I've seen truncate unintentionally break referential integrity, and violate other constraints. The power that you gain by modifying data outside a transaction has to be balanced against the responsibility that you inherit when you walk the tightrope without a net.
TRUNCATE is the DDL statement whereas DELETE is a DML statement. Below are the differences between the two:
As TRUNCATE is a DDL (Data definition language) statement it does not require a commit to make the changes permanent. And this is the reason why rows deleted by truncate could not be rollbacked. On the other hand DELETE is a DML (Data manipulation language) statement hence requires explicit commit to make its effect permanent.
TRUNCATE always removes all the rows from a table, leaving the table empty and the table structure intact whereas DELETE may remove conditionally if the where clause is used.
The rows deleted by TRUNCATE TABLE statement cannot be restored and you can not specify the where clause in the TRUNCATE statement.
TRUNCATE statements does not fire triggers as opposed of on delete trigger on DELETE statement
Here is the very good link relevant to the topic.
Yes, DELETE is slower, TRUNCATE is faster. Why?
DELETE must read the records, check constraints, update the block, update indexes, and generate redo/undo. All of that takes time.
TRUNCATE simply adjusts a pointer in the database for the table (the High Water Mark) and poof! the data is gone.
This is Oracle specific, AFAIK.
If accidentally you removed all the data from table using Delete/Truncate. You can rollback committed transaction. Restore the last backup and run transaction log till the time when Delete/Truncate is about to happen.
The related information below is from a blog post:
While working on database, we are using Delete and Truncate without
knowing the differences between them. In this article we will discuss
the difference between Delete and Truncate in Sql.
Delete:
Delete is a DML command.
Delete statement is executed using a row lock,each row in the table is locked for deletion.
We can specify filters in where clause.
It deletes specified data if where condition exists.
Delete activities a trigger because the operation are logged individually.
Slower than Truncate because it Keeps logs
Truncate
Truncate is a DDL command.
Truncate table always lock the table and page but not each row.As it removes all the data.
Cannot use Where condition.
It Removes all the data.
Truncate table cannot activate a trigger because the operation does not log individual row deletions.
Faster in performance wise, because it doesn't keep any logs.
Note: Delete and Truncate both can be rolled back when used with
Transaction. If Transaction is done, means committed then we can not
rollback Truncate command, but we can still rollback Delete command
from Log files, as delete write records them in Log file in case it is
needed to rollback in future from log files.
If you have a Foreign key constraint referring to the table you are
trying to truncate, this won't work even if the referring table has no
data in it. This is because the foreign key checking is done with DDL
rather than DML. This can be got around by temporarily disabling the
foreign key constraint(s) to the table.
Delete table is a logged operation. So the deletion of each row gets
logged in the transaction log, which makes it slow. Truncate table
also deletes all the rows in a table, but it won't log the deletion of
each row instead it logs the deallocation of the data pages of the
table, which makes it faster.
~ If accidentally you removed all the data from table using
Delete/Truncate. You can rollback committed transaction. Restore the
last backup and run transaction log till the time when Delete/Truncate
is about to happen.
Here is my detailed answer on the difference between DELETE and TRUNCATE in SQL Server
• Remove Data : First thing first, both can be used to remove the rows from table.
But a DELETE can be used to remove the rows not only from a Table but also from a VIEW or the result of an OPENROWSET or OPENQUERY subject to provider capabilities.
• FROM Clause : With DELETE you can also delete rows from one table/view/rowset_function_limited based on rows from another table by using another FROM clause. In that FROM clause you can also write normal JOIN conditions. Actually you can create a DELETE statement from a SELECT statement that doesn’t contain any aggregate functions by replacing SELECT with DELETE and removing column names.
With TRUNCATE you can’t do that.
• WHERE : A TRUNCATE cannot have WHERE Conditions, but a DELETE can. That means with TRUNCATE you can’t delete a specific row or specific group of rows.
TRUNCATE TABLE is similar to the DELETE statement with no WHERE clause.
• Performance : TRUNCATE TABLE is faster and uses fewer system and transaction log resources.
And one of the reason is locks used by either statements. The DELETE statement is executed using a row lock, each row in the table is locked for deletion. TRUNCATE TABLE always locks the table and page but not each row.
• Transaction log : DELETE statement removes rows one at a time and makes individual entries in the transaction log for each row.
TRUNCATE TABLE removes the data by deallocating the data pages used to store the table data and records only the page deallocations in the transaction log.
• Pages : After a DELETE statement is executed, the table can still contain empty pages.
TRUNCATE removes the data by deallocating the data pages used to store the table data.
• Trigger : TRUNCATE does not activate the delete triggers on the table. So you must be very careful while using TRUNCATE. One should never use a TRUNCATE if delete Trigger is defined on the table to do some automatic cleanup or logging action when rows are deleted.
• Identity Column : With TRUNCATE if the table contains an identity column, the counter for that column is reset to the seed value defined for the column. If no seed was defined, the default value 1 is used.
DELETE doesn’t reset the identity counter. So if you want to retain the identity counter, use DELETE instead.
• Replication : DELETE can be used against table used in transactional replication or merge replication.
While TRUNCATE cannot be used against the tables involved in transactional replication or merge replication.
• Rollback : DELETE statement can be rolled back.
TRUNCATE can also be rolled back provided it is enclosed in a TRANSACTION block and session is not closed. Once session is closed you won't be able to Rollback TRUNCATE.
• Restrictions : 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.
And if DELETE is used against View, that View must be an Updatable view.
TRUNCATE cannot be used against the table used in Indexed view.
TRUNCATE cannot be used against the table referenced by a FOREIGN KEY constraint, unless a table that has a foreign key that references itself.
In SQL Server 2005 I believe that you can rollback a truncate
DELETE
The DELETE command is used to remove rows from a table. A WHERE clause can be used to only remove some rows. If no WHERE condition is specified, all rows will be removed. After performing a DELETE operation you need to COMMIT or ROLLBACK the transaction to make the change permanent or to undo it. Note that this operation will cause all DELETE triggers on the table to fire.
TRUNCATE
TRUNCATE removes all rows from a table. The operation cannot be rolled back and no triggers will be fired. As such, TRUCATE is faster and doesn't use as much undo space as a DELETE.
DROP
The DROP command removes a table from the database. All the tables' rows, indexes and privileges will also be removed. No DML triggers will be fired. The operation cannot be rolled back.
DROP and TRUNCATE are DDL commands, whereas DELETE is a DML command. Therefore DELETE operations can be rolled back (undone), while DROP and TRUNCATE operations cannot be rolled back.
From: http://www.orafaq.com/faq/difference_between_truncate_delete_and_drop_commands
TRUNCATE can be rolled back if wrapped in a transaction.
Please see the two references below and test yourself:-
http://blog.sqlauthority.com/2007/12/26/sql-server-truncate-cant-be-rolled-back-using-log-files-after-transaction-session-is-closed/
http://sqlblog.com/blogs/kalen_delaney/archive/2010/10/12/tsql-tuesday-11-rolling-back-truncate-table.aspx
The TRUNCATE vs. DELETE is one of the infamous questions during SQL interviews. Just make sure you explain it properly to the Interviewer or it might cost you the job. The problem is that not many are aware so most likely they will consider the answer as wrong if you tell them that YES Truncate can be rolled back.
One further difference of the two operations is that if the table contains an identity column, the counter for that column is reset 1 (or to the seed value defined for the column) under TRUNCATE. DELETE does not have this affect.
A small correction to the original answer - delete also generates significant amounts of redo (as undo is itself protected by redo). This can be seen from autotrace output:
SQL> delete from t1;
10918 rows deleted.
Elapsed: 00:00:00.58
Execution Plan
----------------------------------------------------------
0 DELETE STATEMENT Optimizer=FIRST_ROWS (Cost=43 Card=1)
1 0 DELETE OF 'T1'
2 1 TABLE ACCESS (FULL) OF 'T1' (TABLE) (Cost=43 Card=1)
Statistics
----------------------------------------------------------
30 recursive calls
12118 db block gets
213 consistent gets
142 physical reads
3975328 redo size
441 bytes sent via SQL*Net to client
537 bytes received via SQL*Net from client
4 SQL*Net roundtrips to/from client
2 sorts (memory)
0 sorts (disk)
10918 rows processed
DELETE
DELETE is a DML command
DELETE you can rollback
Delete = Only Delete- so it can be rolled back
In DELETE you can write conditions using WHERE clause
Syntax – Delete from [Table] where [Condition]
TRUNCATE
TRUNCATE is a DDL command
You can't rollback in TRUNCATE, TRUNCATE removes the record permanently
Truncate = Delete+Commit -so we can't roll back
You can't use conditions(WHERE clause) in TRUNCATE
Syntax – Truncate table [Table]
For more details visit
http://www.zilckh.com/what-is-the-difference-between-truncate-and-delete/
The biggest difference is that truncate is non logged operation while delete is.
Simply it means that in case of a database crash , you cannot recover the data operated upon by truncate but with delete you can.
More details here
DELETE Statement: This command deletes only the rows from the table based on the condition given in the where clause or deletes all the rows from the table if no condition is specified. But it does not free the space containing the table.
The Syntax of a SQL DELETE statement is:
DELETE FROM table_name [WHERE condition];
TRUNCATE statement: This command is used to delete all the rows from the table and free the space containing the table.
Here is a summary of some important differences between these sql commands:
sql truncate command:
1) It is a DDL (Data Definition Language) command, therefore commands such as COMMIT and ROLLBACK do not apply to this command (the exceptions here are PostgreSQL and MSSQL, whose implementation of the TRUNCATE command allows the command to be used in a transaction)
2) You cannot undo the operation of deleting records, it occurs automatically and is irreversible (except for the above exceptions - provided, however, that the operation is included in the TRANSACTION block and the session is not closed). In case of Oracle - Includes two implicit commits, one before and one after the statement is executed. Therefore, the command cannot be withdrawn while a runtime error will result in commit anyway
3) Deletes all records from the table, records cannot be limited to deletion. For Oracle, when the table is split per partition, individual partitions can be truncated (TRUNCATE) in isolation, making it possible to partially remove all data from the table
4) Frees up the space occupied by the data in the table (in the TABLESPACE - on disk). For Oracle - if you use the REUSE STORAGE clause, the data segments will not be rolled back, i.e. you will keep space from the deleted rows allocated to the table, which can be a bit more efficient if the table is to be reloaded with data. The high mark will be reset
5) TRUNCATE works much faster than DELETE
6) Oracle Flashback in the case of TRUNCATE prevents going back to pre-operative states
7) Oracle - TRUNCATE cannot be granted (GRANT) without using DROP ANY TABLE
8) The TRUNCATE operation makes unusable indexes usable again
9) TRUNCATE cannot be used when the enabled foreign key refers to another table, then you can:
execute the command: DROP CONSTRAINT, then TRUNCATE, and then play it through CREATE CONSTRAINT or
execute the command: SET FOREIGN_KEY_CHECKS = 0; then TRUNCATE, then: SET_FOREIGN_KEY_CHECKS = 1;
10) TRUNCATE requires an exclusive table lock, therefore, turning off exclusive table lock is a way to prevent TRUNCATE operation on the table
11) DML triggers do not fire after executing TRUNCATE (so be very careful in this case, you should not use TRUNCATE, if a delete trigger is defined in the table to perform an automatic table cleanup or a logon action after row deletion). On Oracle, DDL triggers are fired
12) Oracle - TRUNCATE cannot be used in the case of: database link
13) TRUNCATE does not return the number of records deleted
14) Transaction log - one log indicating page deallocation (removes data, releasing allocation of data pages used for storing table data and writes only page deallocations to the transaction log) - faster execution than DELETE. TRUNCATE only needs to adjust the pointer in the database to the table (High Water Mark) and the data is immediately deleted, therefore it uses less system resources and transaction logs
15) Performance (acquired lock) - table and page lock - does not degrade performance during execution
16) TRUNCATE cannot be used on tables involved in transactional replication or merge replication
sql delete command:
1) It is a DML (Data Manipulation Language) command, therefore the following commands are used for this command: COMMIT and ROLLBACK
2) You can undo the operation of removing records by using the ROLLBACK command
3) Deletes all or some records from the table, you can limit the records to be deleted by using the WHERE clause
4) Does not free the space occupied by the data in the table (in the TABLESPACE - on the disk)
5) DELETE works much slower than TRUNCATE
6) Oracle Flashback works for DELETE
7) Oracle - For DELETE, you can use the GRANT command
8) The DELETE operation does not make unusable indexes usable again
9) DELETE in case foreign key enabled refers to another table, can (or not) be applied depending on foreign key configuration (if not), please:
execute the command: DROP CONSTRAINT, then TRUNCATE, and then play it through CREATE CONSTRAINT or
execute the command: SET FOREIGN_KEY_CHECKS = 0; then TRUNCATE, then: SET_FOREIGN_KEY_CHECKS = 1;
10) DELETE requires a shared table lock
11) Triggers fire
12) DELETE can be used in the case of: database link
13) DELETE returns the number of records deleted
14) Transaction log - for each deleted record (deletes rows one at a time and records an entry in the transaction log for each deleted row) - slower execution than TRUNCATE. The table may still contain blank pages after executing the DELETE statement. DELETE needs to read records, check constraints, update block, update indexes, and generate redo / undo. All of this takes time, hence it takes time much longer than with TRUNCATE
15) Performance (acquired lock) - record lock - reduces performance during execution - each record in the table is locked for deletion
16) DELETE can be used on a table used in transactional replication or merge replication
In short, truncate doesn't log anything (so is much faster but can't be undone) whereas delete is logged (and can be part of a larger transaction, will rollback etc). If you have data that you don't want in a table in dev it is normally better to truncate as you don't run the risk of filling up the transaction log
A big reason it is handy, is when you need to refresh the data in a multi-million row table, but don't want to rebuild it. "Delete *" would take forever, whereas the perfomance impact of Truncate would be negligible.
Can't do DDL over a dblink.
I'd comment on matthieu's post, but I don't have the rep yet...
In MySQL, the auto increment counter gets reset with truncate, but not with delete.
It is not that truncate does not log anything in SQL Server. truncate does not log any information but it log the deallocation of data page for the table on which you fired TRUNCATE.
and truncated record can be rollback if we define transaction at beginning and we can recover the truncated record after rollback it. But can not recover truncated records from the transaction log backup after committed truncated transaction.
Truncate can also be Rollbacked here the exapmle
begin Tran
delete from Employee
select * from Employee
Rollback
select * from Employee
Truncate and Delete in SQL are two commands which is used to remove or delete data from table. Though quite basic in nature both Sql commands can create lot of trouble until you are familiar with details before using it.
An Incorrect choice of command can result is either very slow process or can even blew up log segment, if too much data needs to be removed and log segment is not enough. That's why it's critical to know when to use truncate and delete command in SQL but before using these you should be aware of the Differences between Truncate and Delete, and based upon them, we should be able to find out when DELETE is better option for removing data or TRUNCATE should be used to purge tables.
Refer check click here
By issuing a TRUNCATE TABLE statement, you are instructing SQL Server to delete every record within a table, without any logging or transaction processing taking place.
DELETE statement can have a WHERE clause to delete specific records whereas TRUNCATE statement does not require any and wipes the entire table.
Importantly, the DELETE statement logs the deleted date whereas the TRUNCATE statement does not.
One more difference specific to microsoft sql server is with delete you can use output statement to track what records have been deleted, e.g.:
delete from [SomeTable]
output deleted.Id, deleted.Name
You cannot do this with truncate.