Archive

Archive for the ‘T SQL’ Category

SQL Basics – ADD or DROP (remove) Columns in a Table in SQL Server

June 25, 2009 2 comments

In my [previous post] we saw how to create a new Database and a new Table.
 

Today we will see how to ADD a new column to a table and DROP an existing column from a table.

To ADD or DROP columns you have to use the ALTER TABLE statement, that is also used to change the datatype of existing columns. Please check the video and the Scripts below to check and learn about both of these actions.

Please note: while adding a new column by using ALTER TABLE ADD statement the columns are always added at the end of the table. But if you want to add the column at a specific position use the Table Designer in SSSMS. Adding column in between is not recommended as it may do data movement by introducing an intermediate temporary table. Thus it is advised to add the columns at the end only and while Querying it you can use the specific column in the middle of the SELECT statement.
 

Check video on how to ADD and DROP columns in a Table:

–> SQL Script used in the above demo:

USE [Demo]
GO

-- create a sample table:

CREATE TABLE [dbo].[Employee](
	[EmployeeID]	int				NOT NULL,
	[EmployeeName]	nvarchar(100)	NOT NULL,
	[Gender]		nchar(1)		NULL,
	[DOB]			datetime		NULL,
	[DOJ]			datetime		NULL,
	[DeptID]		int				NULL
)

-- insert some sample/test records:
INSERT INTO [dbo].[Employee]
VALUES (1, 'MANOJ PANDEY', 'M', '1990-01-01', '2010-01-01', 101)

INSERT INTO [dbo].[Employee]
VALUES (2, 'JHON K', 'M', NULL, '2010-01-01', NULL)

INSERT INTO [dbo].[Employee] ([EmployeeID], [EmployeeName])
VALUES (3, 'Brock H')
GO

SELECT * FROM [dbo].[Employee]
GO


-- Add a new COLUMN:

ALTER TABLE [dbo].[Employee]
ADD MgrID INT
GO

SELECT * FROM [dbo].[Employee]
GO


-- Add column at specific location:
BEGIN TRANSACTION
GO

CREATE TABLE dbo.Tmp_Employee
	(
	EmployeeID int NOT NULL,
	EmployeeName nvarchar(100) NOT NULL,
	Gender nchar(1) NULL,
	FathersName nvarchar(100) NULL,
	DOB datetime NULL,
	DOJ datetime NULL,
	DeptID int NULL,
	MgrID int NULL
	)  ON [PRIMARY]
GO

ALTER TABLE dbo.Tmp_Employee SET (LOCK_ESCALATION = TABLE)
GO

IF EXISTS(SELECT * FROM dbo.Employee)
	 EXEC('INSERT INTO dbo.Tmp_Employee (EmployeeID, EmployeeName, Gender, DOB, DOJ, DeptID, MgrID)
		SELECT EmployeeID, EmployeeName, Gender, DOB, DOJ, DeptID, MgrID FROM dbo.Employee WITH (HOLDLOCK TABLOCKX)')
GO

DROP TABLE dbo.Employee
GO

EXECUTE sp_rename N'dbo.Tmp_Employee', N'Employee', 'OBJECT' 
GO

COMMIT


SELECT EmployeeID, EmployeeName, Gender, MgrID, FathersName, DOB, DOJ, DeptID 
FROM [dbo].[Employee]
GO


-- Drop an existing Column:

ALTER TABLE [dbo].[Employee]
DROP Column FathersName
GO


-- Adding Column with NOT NULL values

ALTER TABLE [dbo].[Employee]
ADD Address VARCHAR(100) NOT NULL
GO
-- error
/*
Msg 4901, Level 16, State 1, Line 38
ALTER TABLE only allows columns to be added that can contain nulls, or have a DEFAULT definition specified, or the column being added is an identity or timestamp column, or alternatively if none of the previous conditions are satisfied the table must be empty to allow addition of this column. Column 'Address' cannot be added to non-empty table 'Employee' because it does not satisfy these conditions.
*/

ALTER TABLE [dbo].[Employee]
ADD Address VARCHAR(100) NOT NULL DEFAULT ('N/A')
GO

SELECT * FROM [dbo].[Employee]
GO

ALTER TABLE [dbo].[Employee]
DROP COLUMN Address
GO
-- error
/*
Msg 5074, Level 16, State 1, Line 55
The object 'DF__Employee__Addres__xxxxxxxx' is dependent on column 'Address'.
Msg 4922, Level 16, State 9, Line 55
ALTER TABLE DROP COLUMN Address failed because one or more objects access this column.
*/

ALTER TABLE [dbo].[Employee] 
DROP CONSTRAINT [DF__Employee__Addres__3C69FB99]
GO

ALTER TABLE [dbo].[Employee]
DROP COLUMN Address
GO


-- Final Cleanup
DROP TABLE [dbo].[Employee]
GO

 

Check my [next post] on how to Rename & change datatype of columns in a table.


SQL Basics – Create Database and Tables in SQL Server

May 25, 2009 5 comments

A Database, it is a collection of data/information organized in a particular fashion so that it can be easily managed and accessed back in same fashion. The data stored and retrieved should in same format and should be consistent.

A Relational Database stores data in Tables, and there can be multiple tables in a database, which may be related to each other by referential integrity.

A Table is a collection of related data stored in a structured format within a database, in form or rows (tuple) and columns (fields).
 

–> Database:

Check video on how to create a new Database by using both, SSMS GUI and T-SQL Script:

–> T-SQL script to Create a new Database:

USE master
GO

CREATE DATABASE [Demo] ON  PRIMARY ( 
	NAME = N'Demo', 
	FILENAME = N'C:\Program Files\Microsoft SQL Server\MSSQL13.MSSQLSERVER2016\MSSQL\DATA\Demo.mdf' , 
	SIZE = 4096KB , 
	FILEGROWTH = 1024KB 
)
LOG ON ( 
	NAME = N'Demo_log', 
	FILENAME = N'C:\Program Files\Microsoft SQL Server\MSSQL13.MSSQLSERVER2016\MSSQL\DATA\Demo_log.ldf' , 
	SIZE = 1024KB , 
	FILEGROWTH = 10%
)
GO

 

–> Table:

Check video on how to create a new Table by using both, SSMS GUI and T-SQL Script:

–> T-SQL script to Create a new Table:

USE [Demo]
GO

CREATE TABLE [dbo].[Employee](
	[EmployeeID]	[int]			NOT NULL,
	[EmployeeName]	[nvarchar](100) NOT NULL,
	[Gender]		[nchar](1)		NULL,
	[DOB]			[datetime]		NULL,
	[DOJ]			[datetime]		NULL,
	[DeptID]		[int]			NULL
)


SELECT * FROM [dbo].[Employee]

INSERT INTO [dbo].[Employee]
VALUES (1, 'MANOJ PANDEY', 'M', '1990-01-01', '2010-01-01', 101)

sp_help 'Employee' -- ALT + F1

INSERT INTO [dbo].[Employee]
VALUES (2, 'JHON K', 'M', NULL, '2010-01-01', NULL)

INSERT INTO [dbo].[Employee] ([EmployeeID], [EmployeeName])
VALUES (3, 'Brock H')

sp_rename 'Employees', 'Employee'

DELETE FROM [dbo].[Employee] WHERE EmployeeID = 2

TRUNCATE TABLE [dbo].[Employee]

DROP TABLE [dbo].[Employee]

 

Check my [next post] on how to ADD/DROP columns in a table.


SQL Basics – Difference between TRUNCATE, DELETE and DROP?

February 22, 2009 23 comments

DELETE and TRUNCATE are two SQL commands used to remove records from a particular table. But they differ in how they execute and operate.
 

–> DELETE: (MSDN)

1. Removes Some or All rows from a table.

2. A WHERE clause can be used to remove some rows. If no WHERE condition is specified, all rows will be removed.

3. Causes all DELETE triggers on the table to fire.

4. It removes rows row-by-row one at a time and records an entry in the Transaction logs, thus is slower than TRUNCATE.

5. Every deleted row in locked, thus it requires more number of locks and database resources.

6. According to MS BOL, if a table is a Heap or no Clustered index is defined than the row-pages emptied are not de-allocated instantly and remain allocated in the heap. Thus, no other object can reuse this associated space. Thus to de-allocate the space a Clustered index is required or TABLOCK hint should be applied in the DELETE statement.

7. This is a DML command as it is just used to manipulate/modify the table data. It does not change any property of a table.


 

–> TRUNCATE: (MSDN)

1. Removes All rows from a table.

2. Does not require a WHERE clause, so you can not filter rows while Truncating.

3. With SQL Server 2016 you can Truncate a Table Partition, for more details check [here].

4. IDENTITY columns are re-seeded on this operation, if no seed was defined then the default value 1 is used.

5. No Triggers are fired on this operation because it does not operate on individual rows.

6. It de-allocates Data Pages instead of Rows and records Data Pages instead of Rows in Transaction logs, thus is faster than DELETE.

7. While de-allocating Pages it locks Pages and not Rows, thus it requires less number of locks and few resources.

8. TRUNCATE is not possible when a table:
a. is reference by a Foreign Key or tables used in replication or with Indexed views.
b. participates in an Indexed/Materialized View.
c. published by using Transactional/Merge replication.

9. This is a DDL command as it resets IDENTITY columns, de-allocates Data Pages and empty them for use of other objects in the database.

Note: It is a misconception among some people that TRUNCATE cannot be roll-backed. But in reality both DELETE and TRUNCATE operations can be COMMITTED AND ROLL-BACKED if provided inside a Transaction. The only method to Rollback a committed transaction after DELETE/TRUNCATE is to restore the last backup and run transactions logs till the time when DELETE/TRUNCATE is about to happen.


 

–> DROP: (MSDN)

1. The DROP TABLE command removes one or more table(s) from the database.

2. All related Data, Indexes, Triggers, Constraints, and Permission specifications for the Table are dropped by this operation.

3. Some objects like Views, Stored Procedures that references the dropped table are not dropped and must be explicitly dropped.

4. Cannot drop a table that is referenced by any Foreign Key constraint.

5. According to MS BOL, Large tables and indexes that use more than 128 extents are dropped in two separate phases: Logical and Physical. In the Logical phase, the existing allocation units used by the table are marked for de-allocation and locked until the transaction commits. In the physical phase, the IAM pages marked for de-allocation are physically dropped in batches.
 


 


DB Basics – What are DDL, DML, DCL and TCL commands & difference b/w them?

February 10, 2009 4 comments

DDL – Data Definition Language:

Statements used to Create, Alter, Drop Database Objects.

Some examples:

– CREATE: used to define new objects

– ALTER: used to modify the definition of existing objects

– DROP: used to remove existing entities.

– TRUNCATE TABLE: used to remove all rows from a table without logging the individual row deletions.

– UPDATE STATISTICS: used to update query optimization statistics on a table or indexed view.
 

DML – Data Manipulation Language:

Statements used to Retrieve, Insert, Update, Remove and Manage data within DB objects.

Some examples:

– SELECT: retrieves one or more rows from a Table or View.

– INSERT: insert one or more rows from a Table or View.

– UPDATE: changes existing data in a Table or View.

– DELETE: removes one or more rows from a Table or View.

– BULK INSERT: imports a data file into a database Table or View in a user-specified format.

– MERGE: performs Insert, Update and/or Delete operations on a Target table based on the results of a JOIN with a source table in one Transaction.

– READTEXT: reads text, ntext, or image values from a text, ntext, or image column

– UPDATETEXT: updates an existing text, ntext, or image field.

– WRITETEXT: permits minimally logged, interactive updating of an existing text, ntext, or image column.
 

DCL – Data Control Language:

Statements used to control the access of data stored in database and provide data security.

Some examples:

– GRANT: grants permissions on a securable to a principal.

– REVOKE: removes a previously granted or denied permission.

– SETUSER: allows a member of the sysadmin fixed server role or db_owner fixed database role to impersonate another user.

– EXECUTE AS, statement: sets the execution context of a session.

– EXECUTE AS, clause: define the execution context of the following user-defined modules: functions (except inline table-valued functions), procedures, queues, and triggers.

– REVERT: switches the execution context back to the caller of the last EXECUTE AS statement.

– OPEN MASTER KEY: opens the Database Master Key of the current database.

– CLOSE MASTER KEY: closes the master key of the current database.

– OPEN SYMMETRIC KEY: Decrypts a symmetric key and makes it available for use.

– CLOSE SYMMETRIC KEY: closes a symmetric key, or closes all symmetric keys open in the current session.
permission through its group or role memberships.
 

TCL – Transaction Control Language:

statements used to manage the changes made by DML statements. It allows statements to be grouped together into logical transactions.

Some Examples:

– BEGIN DISTRIBUTED TRANSACTION: specifies the start of a Transact-SQL distributed transaction managed by Microsoft Distributed Transaction Coordinator (MS DTC).

– BEGIN TRANSACTION: marks the starting point of an explicit, local transaction. BEGIN TRANSACTION increments @@TRANCOUNT by 1.

– COMMIT TRANSACTION: marks the end of a successful implicit or explicit transaction.

– COMMIT WORK: marks the end of a transaction.

– ROLLBACK TRANSACTION: rolls back an explicit or implicit transaction to the beginning of the transaction, or to a savepoint inside the transaction.

– ROLLBACK WORK: rolls back a user-specified transaction to the beginning of the transaction.

– SAVE TRANSACTION: sets a savepoint within a transaction.
 

Check the video:

DDL DML DCL TCL