Delete vs Truncate

There is always a confusion about delete and truncate specially when this question comes suddenly in interview.

Most of the time,  the simple answer is that there are logs created in Delete and no logs in case of truncate. But that is also not fully rue. The correct answer is : In case of delete, as number of log entries are created as number of records being deleted means one log per record deleted. In case of truncate, one log entry is created for the whole truncate.

Some more differences along with above main one can be listed as :

  • One Log entry for the whole transaction and one log per record deleted in case of delete.
  • Truncate deletes all records, but you can put where clause in case of delete.
  • The Identity column counter value resets to 1 in case of Truncate, in case of delete it stays to the last inserted record
  • Delete can be rolled back, truncate cannot. In other words, truncate is committed transaction.

Difference between String and StringBuilder

Strings are Immutable means whenever you change any value of string variable, a new object is created in memory. That’s why where a significant number of strings modifications need to be done, StringBuilder should be used. Its present in System.TextBuilder namespace.

Now questions comes, why strings are Immutable or what are the benefits of immutability :

  • First, All Immutable instances are thread safe. Because on modifying their values, a new instance is created , So no Thread can actually modify it.
  • There will be no side-effect on passing an immutable types as parameter in a function, as if there is x = “abc” in the starting of function,  that doesn’t change in the body of the method, then x == "abc" at the end of the method.
  • Copying is fast and simple, to create a clone just return this. Since the copy can’t be changed anyway, pretending something is its own copy is safe.
  • You can use strings in Hash-table, key-value pairs collection for their key part.