Archive

Archive for the ‘DB Concepts’ Category

SQL Basics – Persisted and Non-Persisted Computed columns in SQL Server

October 2, 2009 Leave a comment

In SQL Server you have an option to create Calculated Columns in a table other than normal columns. By saying Normal columns I meant that their values are stored physically with the table. But with Calculated Columns their values are not stored physically, instead they are re-calculated every time whenever they are referenced.

A Computed Column is nothing but an expression, which can be a:

1. Non Computed column

2. Constant

3. Function

4. or any combination of above of these by using operators.

These type of Computed Columns are Non-Persisted in nature.
 

Persisted Computed Columns: You can also make Computed columns values stored physically by using the PERSISTED keyword. This will calculate the column values initially while inserting a row, or later if there is any change made to the column that is part of its expression.
 

Finally a Computed Column:

– is computed from an expression that can use other columns in the same table.

– can be a noncomputed column name, constant, function with one or more operators.

– cannot be a subquery.

– cannot be used as a DEFAULT or FOREIGN KEY constraint definition or with a NOT NULL constraint definition.

– used as CHECK, FOREIGN KEY, or NOT NULL constraints must be marked PERSISTED.

– can be used in SELECT list, WHERE clause, ORDER BY clause, etc.

– cannot be the target of an INSERT or UPDATE statement.
 

Check video on how to create Calculated Columns in a Table:

Computed Columns
 

–> SQL Script used in the above demo:

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

INSERT INTO [dbo].[Employee] (EmployeeName, Gender, DOB, DOJ, DeptID)
VALUES ('MANOJ PANDEY', 'M', '1990-01-01', '2010-01-01', 101)

INSERT INTO [dbo].[Employee] (EmployeeName, Gender, DOB, DOJ, DeptID)
VALUES ('JHON K', 'M', '1970-03-03', NULL, NULL)

INSERT INTO [dbo].[Employee] (EmployeeName, DOB)
VALUES ('Brock H', '1980-02-02')
GO

SELECT * FROM [dbo].[Employee]
GO

ALTER TABLE [dbo].[Employee]
ADD AGE AS (DATEDIFF(YY, DOB, GETDATE()))
GO

ALTER TABLE [dbo].[Employee]
ADD XYZ AS 'nothing'
GO

SELECT * FROM [dbo].[Employee]
GO


CREATE TABLE dbo.Products (
    ProductID	int IDENTITY (1,1),
	Qty			smallint,
	Price		money,
	TotalValue AS (Qty * Price)
)

INSERT INTO dbo.Products (Qty, Price)
VALUES (5, 200)

INSERT INTO dbo.Products (Qty, Price)
VALUES (3, 150)

select * from dbo.Products
GO


ALTER TABLE dbo.Products
DROP COLUMN TotalValue

ALTER TABLE dbo.Products
ADD TotalValue AS (Qty * Price) PERSISTED
GO

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

SQL Basics – Rename or Change DataType of a Column in SQL Server

July 1, 2009 1 comment

In my [previous post] we saw how to create a new Database and a new Table. We also saw how to [ADD/DROP] columns in a table.
 

Today we will see how to Rename a Column and Change its datatype.
 

–> To Rename an existing column in a table you can use the system Stored Procedure sp_rename, and the syntax is:

EXECUTE sp_rename 'schema.Table.ColumnName', 'NewColumnName', 'COLUMN'
 

–> And to change column datatype use simple ALTER TABLE statement, like:

ALTER TABLE table_name
ALTER COLUMN ColumnName new_Datatype

 

Check video on how to Rename and Change column datatype 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 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

-- Rename a column:
EXECUTE sp_rename N'dbo.Employee.MgrID', N'ManagerID', 'COLUMN'
GO

-- Change datatype of column:
ALTER TABLE [dbo].[Employee]
ALTER column ManagerID BIGINT
GO

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.


DB Basics – Database Normalization | 1NF, 2NF, 3NF

March 25, 2009 5 comments

In the field of Relational Database design, normalization is a systematic way of ensuring that a database structure is suitable for general-purpose querying and free of certain undesirable characteristics—insertion, update, and deletion anomalies—that could lead to a loss of data integrity.
 

According to E. F. Codd the objectives of normalization were stated as follows:

1. To free the collection of relations from undesirable insertion, update and deletion dependencies.

2. To reduce the need for restructuring the collection of relations as new types of data are introduced, and thus increase the life span of application programs.

3. To make the relational model more informative to users.

4. To make the collection of relations neutral to the query statistics, where these statistics are liable to change as time goes by.
 

E. F. Code the inventor of Relational Model, introduced the concept of normalization (1NF at 1970, 2-3NF at 1971, then with R. F. Boyce defined the BCFN in 1974).

C. Date, H. Darwin, R. Fagin, N. Lorentzos defined other higher forms upto 6NF by 2002.

As of now there are total 8 normal forms, as follows:
1. First normal form (1NF)
2. Second normal form (2NF)
3. Third normal form (3NF)
4. Boyce-Codd normal form (BCNF)
5. Fourth normal form (4NF)
6. Fifth normal form (5NF)
7. Domain/key normal form (DKNF)
8. Sixth normal form (6NF)

But to keep our data consistent & non-redundant the first 3 Normal Forms are sufficient.
 

1. The 1st Normal Form:

– There are no duplicate rows and each row should have a unique identifier (or Primary key). A table should be free from repeating groups.

– The values in each column of a table are atomic. Meaning a field value cannot be decomposed into smaller pieces or should not be divided into parts with more than one kind of data in it.
Like: A Person’s Name column could be further divided into First, Middle, Last Name columns.
 

2. The 2nd Normal Form:

– A table should be in 1st Normal Form.

– Any Candidate key (K) and any Attribute (A) that is not a constituent of a candidate key, A depends upon whole of K rather than just part of it.

Means all its non-prime attributes are functionally dependent on the whole of a candidate key.

In Simple terms, any non-key columns must be dependent on the entire primary key. In the case of a composite primary key, this means that a non-key column cannot depend on only part of the composite key.
 

3. The 3rd Normal Form:

– A table should be in 2nd Normal Form.

– Every non-prime attribute of R is non-transitively dependent (i.e. directly dependent) on every candidate/primary key of R.

– All columns should depend directly on the primary key. Tables violate the Third Normal Form when one column depends on another column, which in turn depends on the primary key (a transitive dependency).
 

>> Check & Subscribe my [YouTube videos] on SQL Server.
 


Categories: DB Concepts Tags: , , , ,