CONSTRAINTS
SQL Constraints
Constraints are used to limit the type of data that can go into a table.
Constraints can be specified when a table is created (with the CREATE TABLE statement) or
after the table is created (with the ALTER TABLE statement).
We will focus on the following constraints:
1. NOT NULL
2. UNIQUE
3. PRIMARY KEY
4. FOREIGN KEY
5. CHECK
6. DEFAULT
1.SQL NOT NULL Constraint
The NOT NULL constraint enforces a column to NOT accept NULL values.
The NOT NULL constraint enforces a field to always contain a value. This means that you
cannot insert a new record, or update a record without adding a value to this field
Example:
create table CitizenCard
(
CID int primary key,
CName varchar(35) not null,
CardIssueDate Datetime
CardExpiryDate Datetime
CardNum number,
TravelledFrom varchar(20) not null,
TravelledTo varchar(20) not null,
TravellingFair numeric(5,2))
SQL UNIQUE Constraint
The UNIQUE constraint uniquely identifies each record in a database table.
The UNIQUE and PRIMARY KEY constraints both provide a guarantee for uniqueness for a
column or set of columns.
A PRIMARY KEY constraint automatically has a UNIQUE constraint defined on it.
Note that you can have many UNIQUE constraints per table, but only one PRIMARY KEY
constraint per table.
SQL UNIQUE Constraint on CREATE TABLE
Example:
create table CitizenCard
(
CID int primary key,
CName varchar(35) not null unique,
CardIssueDate Datetime
CardExpiryDate Datetime
CardNum number,
TravelledFrom varchar(20) not null,
TravelledTo varchar(20) not null,
TravellingFair numeric(5,2)
)
SQL UNIQUE Constraint on ALTER TABLE
alter table CitizenCard
add constraint uc_CID unique(CID,CardNum)
2.SQL PRIMARY KEY Constraint
The PRIMARY KEY constraint uniquely identifies each record in a database table.
Primary keys must contain unique values.
A primary key column cannot contain NULL values.
Each table should have a primary key, and each table can have only ONE primary key.
SQL PRIMARY KEY Constraint on CREATE TABLE
Example:
create table CitizenCard
(
CID int primary key,
CName varchar(35) not null,
CardIssueDate Datetime
CardExpiryDate Datetime
CardNum number,
TravelledFrom varchar(20) not null,
TravelledTo varchar(20) not null,
TravellingFair numeric(5,2)
)
SQL PRIMARY KEY Constraint on ALTER TABLE
Example:
alter table CitizenCard
add constraint uc_CID primary key(CID)
To DROP a PRIMARY KEY Constraint
To drop a PRIMARY KEY constraint, use the following SQL:
alter table CitizenCard
drop constraint uc_CID
3.SQL FOREIGN KEY Constraint
A FOREIGN KEY in one table points to a PRIMARY KEY in another table.
The FOREIGN KEY constraint is used to prevent actions that would destroy links between
tables.
The FOREIGN KEY constraint also prevents that invalid data form being inserted into the
foreign key column, because it has to be one of the values contained in the table it points to.
SQL FOREIGN KEY Constraint on CREATE TABLE
create table CitizenInfo
(
CitizenId int,
custid int foreign key references CitizenCard(CID),
PANCardId int,
CCity varchar(20),
CAddress varchar(20),
)
SQL FOREIGN KEY Constraint on ALTER TABLE
Example:
ALTER TABLE CitizenInfo
ADD CONSTRAINT fk_CitizenInfo
FOREIGN KEY (CitizenId)
REFERENCES CitizenCard(CID)
To DROP a FOREIGN KEY Constraint
To drop a FOREIGN KEY constraint, use the following SQL:
Example:
ALTER TABLE CitizenInfo
DROP CONSTRAINT fk_CitizenInfo
4.SQL CHECK Constraint
The CHECK constraint is used to limit the value range that can be placed in a column.
If you define a CHECK constraint on a single column it allows only certain values for this
column.
If you define a CHECK constraint on a table it can limit the values in certain columns based on
values in other columns in the row.
SQL CHECK Constraint on CREATE TABLE
The following SQL creates a CHECK constraint on the "m1" column when the "student" table is
created. The CHECK constraint specifies that the column "m1" must include between 60 and
100.
Example:
create table CitizenCard
(
CID int primary key,
CName varchar(35) not null,
CardIssueDate Datetime
CardExpiryDate Datetime
CardNum number,
TravelledFrom varchar(20) check(TravelledFrom='Hyderabad' or
TravelledFrom='Bangalore'orTravelledFrom='Delhi'or TravelledFrom='Chennai'),
TravelledTo varchar(20) not null,
TravellingFair numeric(5,2)
)
SQL CHECK Constraint on ALTER TABLE
Example:
ALTER TABLE CitizenCard
ADD CONSTRAINT chk_TravellingFrom CHECK (TravelledFrom='Hyderabad' or
TravelledFrom='Bangalore'orTravelledFrom='Delhi'or TravelledFrom='Chennai'),
5.SQL DEFAULT Constraint
The DEFAULT constraint is used to insert a default value into a column.
The default value will be added to all new records, if no other value is specified.
SQL DEFAULT Constraint on CREATE TABLE
The following SQL creates a DEFAULT constraint on the "City" column when the "student"
table is created:
Example:
create table CitizenCard
(
CID int primary key,
CName varchar(35) not null,
CardIssueDate Datetime
CardExpiryDate Datetime
CardNum number,
TravelledFrom varchar(20) check(TravelledFrom='Hyderabad' or
TravelledFrom='Bangalore'orTravelledFrom='Delhi'or TravelledFrom='Chennai'),
TravelledTo varchar(20) default 'banglore',
TravellingFair numeric(5,2)
)
SQL DEFAULT Constraint on ALTER TABLE
To create a DEFAULT constraint on the "City" column when the table is already created, use the
following SQL:
Example:
ALTER TABLE CitizenCard
ALTER COLUMN TravelledTo set DEFAULT 'banglore'
To DROP a DEFAULT Constraint
To drop a DEFAULT constraint, use the following SQL:
Example:
ALTER TABLE CitizenCard
ALTER COLUMN TravelledTo DROP DEFAULT
B.SQL Aggregate Functions
SQL aggregate functions return a single value, calculated from values in a column.
Useful aggregate functions:
1. AVG() - Returns the average value
2. COUNT() - Returns the number of rows
3. MAX() - Returns the largest value
4. MIN() - Returns the smallest value
5. SUM() - Returns the sum
1.The AVG() Function
The AVG() function returns the average value of a numeric column.
SYNTAX:
SELECT AVG(column_name) FROM table_name
EXAMPLE:
select avg(M1) as 'average' from student2
2.The COUNT() Function
The COUNT() function returns the number of rows that matches a specified criteria.
SYNTAX:
SELECT COUNT(column_name) FROM table_name
SELECT COUNT(*) FROM table_name
SELECT COUNT(DISTINCT column_name) FROM table_name
EXAMPLE:
select count(studentname) from student2
select count(*) from student2
select count(distinct studentname) from student2
3.The MAX() Function
The MAX() function returns the largest value of the selected column.
SYNTAX:
SELECT MAX(column_name) FROM table_name
EXAMPLE:
select max(M1) as 'highest' from student2
4.The MIN() Function
The MIN() function returns the smallest value of the selected column.
SYNTAX:
SELECT MAX(column_name) FROM table_name
EXAMPLE:
select min(M1) as 'lowest' from student1
5.The SUM() Function
The SUM() function returns the total sum of a numeric column.
SYNTAX:
SELECT SUM(column_name) FROM table_name
EXAMPLE:
select sum(M1) as 'sum' from student1
SQL STRING Functions
String functions are mainly used to change the case of strings,concatenate strings,reverse
strings,extract various part of strings and perform many other types of string manipulation.
LOWER : Convert character strings data into lowercase.
Syntax:
SELECT LOWER(column name) from tablename
Example:
Select lower(studentID) from student1
UPPER : Convert character strings data into Uppercase.
Syntax:
SELECT UPPER(column name) from tablename
Example:
select upper(studentcity) from student1
LEN : Returns the length of the character string.
Syntax:
SELECT LEN(colunmn name) from table name
Example:
select len(studentcity) from student1
LEFT : Returns left part of a string with the specified number of characters counting from
left.LEFT function is used to retrieve portions of the string.
Syntax:
SELECT LEFT(column name, 6) from table name
Example:
select left (sub, 2 ) from student1
RIGHT : Returns right part of a string with the specified number of characters counting from
right.RIGHT function is used to retrieve portions of the string.
Syntax:
SELECT RIGHT(column name, 6) from table name
Example:
select right(sub, 2 ) from student1
REVERSE : Returns reverse of a input string.
Syntax:
SELECT REVERSE(column name) from table name
Example:
select reverse(sub) from student1
SUBSTRING : Returns part of a given string.
SUBSTRING function retrieves a portion of the given string starting at the specified
character(startindex) to the number of characters specified(length).
Syntax:
SELECT SUBSTRING(column name, start index,length)->STRING
Example:
select substring(sub,1,2) from student1
SQL Date-Time Functions
GetDate() : The GETDATE() function returns the current date and time from the SQL Server
Example:
select getdate() as CurrentDateTime
Datepart() function: The DATEPART() function is used to return a single part of a date/time,
such as year, month, day, hour, minute, etc.
Where date is a valid date expression and datepart can be one of the following:
datepart Abbreviation
year yy, yyyy
quarter qq, q
month mm, m
dayofyear dy, y
day dd, d
week wk, ww
weekday dw, w
hour hh
minute mi, n
second ss, s
millisecond ms
microsecond mcs
nanosecond ns
Example:
Select datepart (yyyy,dateofjoining) as OrderYear,
datepart(mm,dateofjoining) as OrderMonth,
datepart(dd,dateofjoining) as OrderDay from Employee
DateAdd() function: The DATEADD() function is adds or subtracts a specified time interval from
a date.
Syntax:
DATEADD(datepart,number,date)
Where date is a valid date expression and number is the number of interval you want to add. The
number can either be positive, for dates in the future, or negative, for dates in the past.
datepart can be one of the following:
datepart Abbreviation
year yy, yyyy
quarter qq, q
month mm, m
dayofyear dy, y
day dd, d
week wk, ww
weekday dw, w
hour hh
minute mi, n
second ss, s
millisecond ms
microsecond mcs
nanosecond ns
Example:
SELECT DATEADD(day,45,dateofjoining) AS OrderPayDate
FROM Employee
DateDiff() function: The DATEDIFF() function returns the time between two dates
Syntax:
DATEDIFF(datepart,startdate,enddate)
Example:
SELECT DATEDIFF(day,'2008-06-05','2008-08-05') AS DiffDate
Convert() function:
The CONVERT() function is a general function for converting data into a new data type.
The CONVERT() function can be used to display date/time data in different formats.
Syntax:
CONVERT(data_type(length),data_to_be_converted,style)
Where data_type(length) specifies the target data type (with an optional length),
data_to_be_converted contains the value to be converted, and style specifies the output format for
the date/time.
The styles that can be used are:
Style ID Style Format
100 or 0 mon dd yyyy hh:miAM (or PM)
101 mm/dd/yy
102 yy.mm.dd
103 dd/mm/yy
104 dd.mm.yy
105 dd-mm-yy
106 dd mon yy
107 Mon dd, yy
108 hh:mm:ss
109 or 9 mon dd yyyy hh:mi:ss:mmmAM (or PM)
110 mm-dd-yy
111 yy/mm/dd
112 yymmdd
113 or 13 dd mon yyyy hh:mm:ss:mmm(24h)
114 hh:mi:ss:mmm(24h)
120 or 20 yyyy-mm-dd hh:mi:ss(24h)
121 or 21 yyyy-mm-dd hh:mi:ss.mmm(24h)
126 yyyy-mm-ddThh:mm:ss.mmm(no spaces)
130 dd mon yyyy hh:mi:ss:mmmAM
131 dd/mm/yy hh:mi:ss:mmmAM
EXAMPLE:
select convert(varchar(19),getdate())
select convert(varchar(10),getdate(),110)
select convert(varchar(11),getdate(),106)
Sql Math Function:
Some of the mathematical functions are:
1. ABS Function
2. Trig Functions
3. Rounding Functions
4. Rounding
5. Converting Radians to Degrees
6. Converting Degrees to Radians
7. Exponents
8. PI
9. Random Number
1.ABS Function:
The absolute value. The absolute value can be thought of as the distance from 0 on a
number line to whatever number you have. So say your number is -5. The distance from 0 to -5 is
5. The distance from 0 to 5 is also 5. This is why the absolute value is simply the argument
without any negative sign.
Example: SELECT ABS(-1) AS absolute
2.Trig Functions:
The available trig functions are:
ACOS
ASIN
ATAN
TAN
COS
SIN
The first three are the inverse functions. So given a tangent value the resulting value is the angle
with that tangent. The return value will be an angle in radians.
Example:
SELECT COS(5.5) AS cosine;
SELECT SIN(3.55) AS sine;
Tangent
This function TAN also takes a parameter being the angle in radians. The output is the tangent of
that angle.
Example:
SELECT TAN(3.5553) AS tangent
3.RoundingFunctions
The functions is CEILING. These take a floating point parameter. These functions return the
smallest integer value that is not less than the parameter.
Example:
SELECT CEILING(5.35) AS roundedUp;
FloorFunctions
The floor function allows you to round a number to the largest integer value that is less than the
parameter. You can think of this function as "rounding down".
Example:
SELECT FLOOR(5.35) AS roundedDown
4.Rounding
The function is ROUND.
This function allows you to specify how many digits you want to.
Example:
SELECT ROUND(5.334333,2);
5.ConvertingRadiansToDegrees
For one reason or another all programming languages seem to use radians to represent angles.
However, from a young age we are brought up with the concept of degrees. So degrees naturally
make more sense to us. To convert from radians to degrees we use the function DEGREES.
Let's say that we have a value in radians of 0.4567 and we want to convert it to degrees.
Example:
SELECT DEGREES(0.4567) AS deg;
6.Converting Degrees to Radians
The function to convert to back to radians is RADIANS.
Example:
select radians(26.1669825036247) as rad;
Exponents
An exponent is simply multiplying a number by itself x times. So x^n means to multiply x by itself
n times. So 5^3 = 5*5*5. This is what the POW function does for us.
Example:
Select power(5,3) as pow;
PI
This function simply returns the value of PI.
Example: SELECT PI();
Random Number
This function chooses a random floating point number between 0 and 1. We can then manipulate
this number with multiplication and addition to get a seemingly random number in a range.
Example:
SELECT RAND()
SQL RANK FUNCTION:
ROW_NUMBER ()
Returns the sequential number of a row within a partition of a result set, starting at 1 for the first
row in each partition.
Syntax:
ROW_NUMBER () OVER ([<partition_by_clause>] <order_by_clause>)
EXAMPLE:
select stdname, row_number()
over(order by m2 desc)as rank from student
RANK ()
Returns the rank of each row within the partition of a result set.
Syntax:
RANK () OVER ([<partition_by_clause>] <order_by_clause>)
EXAMPLE:
SELECT stdname,m1, RANK() OVER
(ORDER BY m1 DESC) AS rank from student
DENSE_RANK ()
Returns the rank of rows within the partition of a result set, without any gaps in the ranking.
Syntax:
DENSE_RANK () OVER ([<partition_by_clause>] <order_by_clause>)
EXAMPLE:
select stdname,m1,DENSE_RANK() over
(order by m1 desc) as rank from student1