0% found this document useful (0 votes)
22 views

Default Constraint in SQL Server - Part 4

The document discusses various data definition language (DDL) commands in SQL Server for defining constraints on columns. It covers adding and dropping default constraints, check constraints, identity columns, and unique keys. It also discusses functions for retrieving identity column values and replacing null values, as well as advanced join types and the UNION and UNION ALL operators.

Uploaded by

Din Alexandru
Copyright
© © All Rights Reserved
Available Formats
Download as RTF, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
22 views

Default Constraint in SQL Server - Part 4

The document discusses various data definition language (DDL) commands in SQL Server for defining constraints on columns. It covers adding and dropping default constraints, check constraints, identity columns, and unique keys. It also discusses functions for retrieving identity column values and replacing null values, as well as advanced join types and the UNION and UNION ALL operators.

Uploaded by

Din Alexandru
Copyright
© © All Rights Reserved
Available Formats
Download as RTF, PDF, TXT or read online on Scribd
You are on page 1/ 7

Default constraint in sql server - Part 4

Altering an existing column to add a default constraint:


ALTER TABLE { TABLE_NAME }
ADD CONSTRAINT { CONSTRAINT_NAME }
DEFAULT { DEFAULT_VALUE } FOR { EXISTING_COLUMN_NAME }

Adding a new column, with default value, to an existing table:


ALTER TABLE { TABLE_NAME } 
ADD { COLUMN_NAME } { DATA_TYPE } { NULL | NOT NULL } 
CONSTRAINT { CONSTRAINT_NAME } DEFAULT { DEFAULT_VALUE }

The following command will add a default constraint, DF_tblPerson_GenderId.


ALTER TABLE tblPerson
ADD CONSTRAINT DF_tblPerson_GenderId
DEFAULT 1 FOR GenderId
OBS: daca specific NULL pentru coloanal cu Default Constraint, acest NULL va fi inserat oricum.
Default Constraint se aplica doar daca nu specific ce valoare sa fie inserata in coloana.

To drop a constraint
ALTER TABLE { TABLE_NAME } 
DROP CONSTRAINT { CONSTRAINT_NAME }

Check constraint in SQL Server - Part 6

Verifica daca o valoare inserata respecta o expresie booleana A/F


The following check constraint, limits the age between ZERO and 150.
ALTER TABLE tblPerson
ADD CONSTRAINT CK_tblPerson_Age CHECK (Age > 0 AND Age < 150)

The general formula for adding check constraint in SQL Server:


ALTER TABLE { TABLE_NAME }
ADD CONSTRAINT { CONSTRAINT_NAME } CHECK ( BOOLEAN_EXPRESSION )

If the BOOLEAN_EXPRESSION returns true, then the CHECK constraint allows the value,
otherwise it doesn't. Since, AGE is a nullable column, it's possible to pass null for this column,
when inserting a row. When you pass NULL for the AGE column, the boolean expression
evaluates to UNKNOWN, and allows the value.
Check Constraint-ul permite NULL-urile daca nu este specificat clar sa nu o faca
To drop the CHECK constraint:
ALTER TABLE tblPerson
DROP CONSTRAINT CK_tblPerson_Age

Identity column in SQL Server - Part 7

If a column is marked as an identity column, then the values for this column are automatically
generated, when you insert a new row into the table. The following, create table statement
marks PersonId as an identity column with seed = 1 and Identity Increment = 1. Seed and
Increment values are optional. If you don't specify the identity and seed they both default to 1. 

Create Table tblPerson
(
PersonId int Identity(1,1) Primary Key,
Name nvarchar(20)
)

How to get the last generated identity column value in SQL Server - Part
8

Example queries for getting the last generated identity value


Select SCOPE_IDENTITY()
Select @@IDENTITY
Select IDENT_CURRENT('tblPerson')

SCOPE_IDENTITY() - returns the last identity value that is created in the same session and in
the same scope. à Returneaza ultimul ID din ultima sesiune creat in ultimul scope.

@@IDENTITY - returns the last identity value that is created in the same session and across
any scope. à Returneaza ultimul ID din ultima sesiune din Orice Scope. (Ex: daca asa avea
un trigger care sa insereze un ID cand afac un alt insert, imi va returna pe cel din Inserul
facut de trigger.)

IDENT_CURRENT('TableName') - returns the last identity value that is created for a specific
table across any session and any scope. à Returneaza ultimul ID din Orice sesiune (Querry
page) din Orice Scope. (Ex: daca asa avea un trigger care sa insereze un ID cand fac un
alt insert, imi va returna pe cel din Inserul facut de trigger. Chiar daca scope identity a
fost facut in alta pagina de Querry.)
Unique key constraint - Part 9

To create the unique key using a query:


Alter Table Table_Name
Add Constraint Constraint_Name Unique(Column_Name)

To drop the constraint


1. Right click the constraint and delete.
Or
2. Using a query
Alter Table tblPerson
Drop COnstraint UQ_tblPerson_Email

Advanced Joins - Part 13

Considers Employees (tblEmployee) and Departments (tblDepartment) tables 

Employee Table (tblEmployee)

Departments Table (tblDepartment)


How to retrieve only the non matching rows from the left table. The output should be as
shown below: 

Query:
SELECT       Name, Gender, Salary, DepartmentName
FROM           tblEmployee E
LEFT JOIN   tblDepartment D
ON                 E.DepartmentId = D.Id
WHERE        D.Id IS NULL

How to retrieve only the non matching rows from the right table 

Query:
SELECT         Name, Gender, Salary, DepartmentName
FROM             tblEmployee E
RIGHT JOIN    tblDepartment D
ON                   E.DepartmentId = D.Id
WHERE          E.DepartmentId IS NULL 
 

How to retrieve only the non matching rows from both the left and right table. Matching
rows should be eliminated. 

Query:
SELECT         Name, Gender, Salary, DepartmentName
FROM              tblEmployee E
FULL JOIN      tblDepartment D
ON                   E.DepartmentId = D.Id
WHERE          E.DepartmentId IS NULL
OR                   D.Id IS NULL
Different ways to replace NULL in sql server - Part 15

Replacing NULL value using ISNULL() function: We are passing 2 parameters to IsNULL()
function. If M.Name returns NULL, then 'No Manager' string is used as the replacement value.
SELECT E.Name as Employee, ISNULL(M.Name,'No Manager') as Manager
FROM tblEmployee E
LEFT JOIN tblEmployee M
ON E.ManagerID = M.EmployeeID

Replacing NULL value using CASE Statement:


SELECT E.Name as Employee, CASE WHEN M.Name IS NULL THEN 'No Manager' 
ELSE M.Name END as Manager
FROM tblEmployee E
LEFT JOIN tblEmployee M
ON E.ManagerID = M.EmployeeID

Replacing NULL value using COALESCE() function: COALESCE() function, returns the first
NON NULL value.
SELECT E.Name as Employee, COALESCE(M.Name, 'No Manager') as Manager
FROM tblEmployee E
LEFT JOIN tblEmployee M
ON E.ManagerID = M.EmployeeID

Coalesce() function in sql server - Part 16

According to the MSDN Books online COALESCE() returns the first Non NULL value. Let's
understand this with an example.

Now, let's write a query that returns the Name of the Employee. If an employee, has all the
columns filled - First, Middle and Last Names, then we only want the first name. 

If the FirstName is NULL, and if Middle and Last Names are filled then, we only want
the middle name. For example, Employee row with Id = 1, has the FirstName filled, so we want
to retrieve his FirstName "Sam". Employee row with Id = 2, has Middle and Last names
filled, but the First name is missing. Here, we want to retrieve his middle name "Todd". In short,
The output of the query should be as shown below.

We are passing FirstName, MiddleName and LastName columns as parameters to the


COALESCE() function. The COALESCE() function returns the first non null value from the 3
columns.
SELECT Id, COALESCE(FirstName, MiddleName, LastName) AS Name
FROM tblEmployee

Union and union all in sql server - Part 17

UNION and UNION ALL operators in SQL Server, are used to combine the result-set of two or
more SELECT queries.

If you want to sort, the results of UNION or UNION ALL, the ORDER BY caluse should be
used on the last SELECT statement as shown below.
Select Id, Name, Email from tblIndiaCustomers
UNION ALL
Select Id, Name, Email from tblUKCustomers
UNION ALL
Select Id, Name, Email from tblUSCustomers
Order by Name

You might also like