For performing CRUD(Create-Read-Update-Delete) operations we need DML statements; In this article, we will discuss about various behaviors of these commands with bunch of examples. Each example demonstrates a different behavior of each command.
TRUNCATE VS DELETE Statement:
1: INSERT: Inserting values in the table.
Examples:
CREATE TABLE Table1 (Id INT, name VARCHAR(15));
The following are various types of record insertion into the above created table "Table1"-
Inserting a record into table.
Inserting partial record into table - inserting selected column values
Inserting multiple records simultaneously.
INSERT INTO Table1
SELECT 5,'bbb' UNION ALL
SELECT 6,'ccc' UNION ALL
SELECT 7,'ddd'Inserting a record with default values only.
-
Inserting records from existing table.
Inserting records from a Stored Procedure.
-
BULK INSERT: inserting records from .txt file (Note change Id column type int=>char)
-- myrecords.txt file. 101 aabb 102 bbccBULK INSERT Table1
FROM 'c:\myrecords.txt'
WITH ( DATAFILETYPE = 'char',
FIELDTERMINATOR = '\t',
ROWTERMINATOR = '\n')
For BULK INSERT destination table columns must be character type (non-integer and non-real). If table columns are integer type and real type then, you need to add attribute WITH(FORMATFILE=’xml file path’). The format file is an xml file containing structure for mapping columns of source file to destination table.
INSERT INTO Table1 VALUES (1, 'aaa')
INSERT INTO Table1 (Id) VALUES(2)
// OR //
INSERT INTO Table1(Id) SELECT 2
-- Inserts defaults if available otherwise NULL'
INSERT INTO table1 DEFAULT VALUES
INSERT INTO table1 DEFAULT VALUES
INSERT INTO table2(Id2,Name2)
SELECT Id, name FROM table1
SELECT Id, name FROM table1
Syntax:
INSERT [ INTO] table_or_view_name[ ( column_list ) ]
EXEC stored_procedure_name
Example:
-- Create Stored procedure
CREATE PROCEDURE myProc1
AS
SELECT 1, 'mmm' UNION ALL
SELECT 2, 'nnn'
--Insert the values into table by executing SP
INSERT INTO table1
EXEC myProc1 -- 2 rows inserted.
CREATE PROCEDURE myProc1
AS
SELECT 1, 'mmm' UNION ALL
SELECT 2, 'nnn'
--Insert the values into table by executing SP
INSERT INTO table1
EXEC myProc1 -- 2 rows inserted.
2: UPDATE: Updating values in the table.
Syntax:
UPDATE table_name
SET column_name_1 = expression_1 [, column_name_2 = expression_2]...
[FROM table_source [[AS] table_alias]
[WHERE search_condition]
SET column_name_1 = expression_1 [, column_name_2 = expression_2]...
[FROM table_source [[AS] table_alias]
[WHERE search_condition]
Examples:
Simple update to a column
Updating multiple columns
Updating a column with sub-query. (Q: Set name=kkk for maximum id candidate)
Updating a column with two sub-queries.
Updating a column with CASE statement.(Q: Interchange male & female for SEX column)
Setting a column to its default value.
UPDATE with JOINS
--Consider the following tables StdInfo(rno,name,address), StdRes(rno, m1,m2,m3,total)
// Question: CHANGE address to HYD for student whose total marks is 450.
UPDATE table1
SET id=20
WHERE id=2;
SET id=20
WHERE id=2;
UPDATE Table1
SET id=20, name='KKK'
WHERE id=2;
SET id=20, name='KKK'
WHERE id=2;
UPDATE Table1
SET name='KKK'
WHERE id IN (Select Max(id) from Table1);
SET name='KKK'
WHERE id IN (Select Max(id) from Table1);
UPDATE Table1
SET name = (Sub-query1)
WHERE id IN (Sub-query2);
SET name = (Sub-query1)
WHERE id IN (Sub-query2);
UPDATE Table1
SET Sex=CASE WHEN(sex='male') THEN 'female'
WHEN(sex='female') THEN 'male'
ELSE 'UNKNOWN' END;
SET Sex=CASE WHEN(sex='male') THEN 'female'
WHEN(sex='female') THEN 'male'
ELSE 'UNKNOWN' END;
UPDATE Table1
SET name=DEFAULT
WHERE id =101;
SET name=DEFAULT
WHERE id =101;
Syntax:
UPDATE
SET col1 = [,col2 = ]
FROM JOIN
ON ]
WHERE ]
Example:
UPDATE StdInfo
SET address='Hyd'
FROM StdInfo t1
INNER JOIN StdRes t2 ON t1.rno=t2.rno
WHERE total=450;
SET address='Hyd'
FROM StdInfo t1
INNER JOIN StdRes t2 ON t1.rno=t2.rno
WHERE total=450;
3: DELETE: Deleting all or selected rows.
Syntax:
DELETE
[FROM { TableName | [ JOIN
ON ] }
[WHERE ]
Examples:
Deleting all records from the table.
Deleting a particular records
Deleting with JOINS
-- Consider the following tables StdInfo(rno,name,address), StdRes(rno, m1,m2,m3,total)
-- Question1: DELETE a record from StdInfo whose total=450
DELETE Table1 // OR // DELETE FROM Table1
DELETE
FROM Table1
WHERE id=101
DELETE stdInfo
FROM stdInfo t1 INNER JOIN stdrest t2 ON t1.rno=t2.rno
WHERE total=450
FROM stdInfo t1 INNER JOIN stdrest t2 ON t1.rno=t2.rno
WHERE total=450
Question2: DELETE matched records from both tables
DELETE stdInfo, stdRes
FROM stdInfo t1 INNER JOIN stdrest t2 ON t1.rno=t2.rno
FROM stdInfo t1 INNER JOIN stdrest t2 ON t1.rno=t2.rno
You can drop all tables in a database using sp_MSforeachtable stored procedure.
a) EXEC sp_MSforeachtable @command1 = "DROP TABLE ?" – Deletes all tables of current dbase.
b) EXEC sp_MSforeachtable @command1 = "drop table aa" – Deletes single table ‘aa’
4: TRUNCATE command to emptying whole table.
- Removes all rows from a table without logging the individual row deletions.
- TRUNCATE TABLE is functionally the same as the DELETE without WHERE clause;
Syntax:
TRUNCATE TABLE [ {database_name.schema_name..} ]
Table_name
Example
TRUNCATE TABLE employee;
TRUNCATE VS DELETE Statement:
Differences between TRUNCATE and DELETE
- TRUNCATE empties the entire table whereas DELETE removes the rows from the table. So, deleting only particular records is not possible using TRUNCATE but using DELETE with WHERE option it is possible.
- TRUNCATE is the DDL operation that cannot be rolled-back whereas DELETE is the DML operation that can be rolled back.
- TRUNCATE is much faster since it simply de-allocates the table’s memory without logging operations whereas DELETE removes records row-by-row and logs each operation so performance decreases.
- TRUNCATE resets the @@Identity of a table whereas DELETE does not.
- TRUNCATE does not activates the DML Triggers whereas DELETE activates.
No comments:
Post a Comment