Archive

Archive for the ‘SQL Basics’ Category

SQL Basics – Working with Foreign Key (FK) constraints

December 27, 2009 3 comments

A foreign key (FK) is a column or combination of columns that is used to establish and enforce a link between the data in two tables, as per MSDN BoL.
 

–> Foreign Key (FK) Constraint

1. We can create a FK by defining a FOREIGN KEY constraint while Creating or modifying (Altering) a table.

2. We can define a FK in a table that points to a PK or UK in another table.
   – Like Employee & Department, shown in video-demo below.

3. A FK constraint can reference columns within the same table, these are called self-referencing tables. For example: Employee & Manager Relationship.
 

–> Referential Integrity:

1. The FK constraint enforces Referential Integrity by not allowing values in the Child table outside form the domain of the Parent table.

2. This also disallows any changes to the Parent table, like deleting any row or modifying PK value in the Parent table.
 

–> Check the video on Foreign Key:

FK Constraint
 

–> Department and Employee table FK relationship:

FK Constraint
 

–> SQL Code used in above video:


-- 1. Parent table:

CREATE TABLE [dbo].[Department](
	 [DeptID]	int IDENTITY (101, 1) PRIMARY KEY
	,[DeptName]	nvarchar(100)
	,[isActive]	bit DEFAULT(1)
)
GO

INSERT INTO [dbo].[Department] ([DeptName])
SELECT 'HR'
UNION ALL
SELECT 'Finance'
UNION ALL
SELECT 'Admin'
UNION ALL
SELECT 'IT'

select * from [dbo].[Department]
GO


-- 2. Child Table:

-- Method #1.a : with Column inline
CREATE TABLE [dbo].[Employee](
	 [EmployeeID]	int IDENTITY (100, 1) PRIMARY KEY
	,[EmployeeName]	nvarchar(100)
	,[Gender]		nchar(1)
	,[DeptID]		int NOT NULL FOREIGN KEY REFERENCES Department(DeptID)
	,[isActive]		bit DEFAULT(1)
)
GO

-- Method #1.b : with Column inline & Named FK
DROP TABLE [dbo].[Employee]
GO
CREATE TABLE [dbo].[Employee](
	 [EmployeeID]	int IDENTITY (100, 1) PRIMARY KEY
	,[EmployeeName]	nvarchar(100)
	,[Gender]		nchar(1)
	,[DeptID]		int NOT NULL CONSTRAINT FK_EmployeeID_DeptID FOREIGN KEY REFERENCES Department(DeptID)
	,[isActive]		bit DEFAULT(1)
)
GO

-- Method #2.a : with Explicit
DROP TABLE [dbo].[Employee]
GO
CREATE TABLE [dbo].[Employee](
	 [EmployeeID]	int IDENTITY (100, 1) PRIMARY KEY
	,[EmployeeName]	nvarchar(100)
	,[Gender]		nchar(1)
	,[DeptID]		int NOT NULL
	,[isActive]		bit DEFAULT(1)
		FOREIGN KEY ([DeptID]) REFERENCES Department(DeptID)
)
GO

-- Method #2.b : with Explicit & Named FK
DROP TABLE [dbo].[Employee]
GO
CREATE TABLE [dbo].[Employee](
	 [EmployeeID]	int IDENTITY (100, 1) PRIMARY KEY
	,[EmployeeName]	nvarchar(100)
	,[Gender]		nchar(1)
	,[DeptID]		int NOT NULL
	,[isActive]		bit DEFAULT(1)
		CONSTRAINT FK_EmployeeID_DeptID FOREIGN KEY ([DeptID]) REFERENCES Department(DeptID)
)
GO

-- Method #3 : with ALTER Table Named FK
DROP TABLE [dbo].[Employee]
GO
CREATE TABLE [dbo].[Employee](
	 [EmployeeID]	int IDENTITY (100, 1) PRIMARY KEY
	,[EmployeeName]	nvarchar(100)
	,[Gender]		nchar(1)
	,[DeptID]		int NOT NULL
	,[isActive]		bit DEFAULT(1)
)
GO

-- SSMS or ALTER Table stmt:

-- Generated by SSMS - Table Designer:
ALTER TABLE dbo.Employee ADD CONSTRAINT
	FK_Employee_Department FOREIGN KEY
	(
	DeptID
	) REFERENCES dbo.Department
	(
	DeptID
	)

-- OR --

ALTER TABLE [dbo].[Employee]
ADD CONSTRAINT FK_EmployeeID_DeptID FOREIGN KEY ([DeptID]) REFERENCES Department(DeptID)
GO


INSERT INTO Employee ([EmployeeName], [Gender], [DeptID])
VALUES ('Manoj Pandey', 'M', 101)

INSERT INTO Employee ([EmployeeName], [Gender], [DeptID])
VALUES ('Deepak B', 'M', 102)

INSERT INTO Employee ([EmployeeName], [Gender], [DeptID])
VALUES ('Jhon B', 'M', 103)

INSERT INTO Employee ([EmployeeName], [Gender], [DeptID])
VALUES ('Mariya Y', 'F', 104)

select * from [dbo].[Employee]
GO


-- REFERENTIAL INTEGRITY:

INSERT INTO Employee ([EmployeeName], [Gender], [DeptID])
VALUES ('Mary J', 'F', 105)
--Msg 547, Level 16, State 0, Line 115
--The INSERT statement conflicted with the FOREIGN KEY constraint "FK_EmployeeID_DeptID". The conflict occurred in database "TestManDB", table "dbo.Department", column 'DeptID'.
--The statement has been terminated.

DELETE FROM [dbo].[Department]
WHERE DeptID = 102
--Msg 547, Level 16, State 0, Line 118
--The DELETE statement conflicted with the REFERENCE constraint "FK_EmployeeID_DeptID". The conflict occurred in database "TestManDB", table "dbo.Employee", column 'DeptID'.
--The statement has been terminated.

DROP TABLE [dbo].[Department]
--Msg 3726, Level 16, State 1, Line 121
--Could not drop object 'dbo.Department' because it is referenced by a FOREIGN KEY constraint.

GO


-- Allowed updates:

select * from [dbo].[Department]

UPDATE [dbo].[Department]
SET DeptName = 'Human Resource'
WHERE DeptID = 101

select * from [dbo].[Department]

GO


-- Final Cleanup:

DROP TABLE [dbo].[Employee]
GO
DROP TABLE [dbo].[Department]
GO

Check Primary Key & Unique Key constraints

To know about more on Constraints and their types check this blog post.


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.