PROGRAM NO.
11
AIM: Types of SQL Constraints
SQL constraints are used to specify rules for the data in a table.
Constraints are used to limit the type of data that can go into a table. This
ensures the accuracy and reliability of the data in the table. If there is any
violation between the constraint and the data action, the action is aborted.
Constraints can be column level or table level. Column level constraints apply to
a column, and table level constraints apply to the whole table.
The following constraints are commonly used in SQL:
NOT NULL - Ensures that a column cannot have a NULL value
UNIQUE - Ensures that all values in a column are different
PRIMARY KEY - A combination of a NOT NULL and UNIQUE. Uniquely identifies each
row in a table
FOREIGN KEY - Uniquely identifies a row/record in another table
CHECK - Ensures that all values in a column satisfies a specific condition
DEFAULT - Sets a default value for a column when no value is specified
INDEX - Used to create and retrieve data from the database very quickly
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:
The following SQL enforces the "P_Id" column and the "LastName" column to not
accept NULL values:
CREATE TABLE PersonsNotNull
P_Idint NOT NULL,
LastNamevarchar(255) NOT NULL,
FirstNamevarchar(255),
Address varchar(255),
City varchar(255)
ii. 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.
Example:
The following SQL creates a UNIQUE constraint on the "P_Id" column when the
"Persons" table is created:
CREATE TABLE Persons
P_Idint NOT NULL UNIQUE,
LastNamevarchar(255) NOT NULL,
FirstNamevarchar(255),
Address varchar(255),
City varchar(255)
)
iii. 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.
Most tables should have a primary key, and each table can have only ONE
primary key.
Example:
The following SQL creates a PRIMARY KEY on the "P_Id" column when the
"Persons" table is created:
CREATE TABLE Persons
P_Idint NOT NULL,
LastNamevarchar(255) NOT NULL,
FirstNamevarchar(255),
Address varchar(255),
City varchar(255),
PRIMARY KEY (P_Id)
iv. FOREIGN KEY Constraint:
A FOREIGN KEY in one table points to a PRIMARY KEY in another table.
Look at the following two tables:
o The "Persons" table:
P_Id LastName FirstName Address
1 Hansen Ola Timoteivn
2 Svendson Tove Borgvn23
3 Pettersen Kari Storgt20
The “Orders” table:
O_Id OrderNo P_Id
1 77895 3
2 44678 3
3 22456 2
4 24562 1
Note that the "P_Id" column in the "Orders" table points to the "P_Id" column in
the "Persons" table.
The "P_Id" column in the "Persons" table is the PRIMARY KEY in the "Persons"
table.
The "P_Id" column in the "Orders" table is a FOREIGN KEY in the "Orders" table.
The FOREIGN KEY constraint is used to prevent actions that would destroy links
between tables.
The FOREIGN KEY constraint also prevents invalid data from being inserted into
the foreign key column, because it has to be one of the values contained in the
table it points to.
Example:
The following SQL creates a FOREIGN KEY on the "P_Id" column when the
"Orders" table is created:
CREATE TABLE Orders
O_Idint NOT NULL,
OrderNoint NOT NULL,
P_Idint,
PRIMARY KEY (O_Id),
FOREIGN KEY (P_Id) REFERENCES Persons(P_Id)
o CHECK Constraint:
o The CHECK constraint is used to limit the value range that can be placed
in a column.
o If you define a CHECK constraint on a single column it allows only certain
values for this column.
o 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.
o Example:
The following SQL creates a CHECK constraint on the "P_Id" column
when the "Persons" table is created. The CHECK constraint specifies that
the column "P_Id" must only include integers greater than 0.
CREATE TABLE Persons
P_Idint NOT NULL,
LastNamevarchar(255) NOT NULL,
FirstNamevarchar(255),
Address varchar(255),
City varchar(255),
CHECK (P_Id>0)
o DEFAULT Constraint:
o The DEFAULT constraint is used to insert a default value into a column.
o The default value will be added to all new records, if no other value is
specified.
o Example:
The following SQL creates a DEFAULT constraint on the "City" column
when the "Persons" table is created:
CREATE TABLE Persons
P_Idint NOT NULL,
LastNamevarchar(255) NOT NULL,
FirstNamevarchar(255),
Address varchar(255),
City varchar(255) DEFAULT 'Sandnes'
)
PROGRAM NO.12
AIM: Types of SQL functions.
SQL Server has many built-in functions.
This reference contains string, numeric, date, conversion, and some advanced functions in SQL
Server.
SQL Server String Functions
Function Description
ASCII Returns the ASCII value for the specific character
CHAR Returns the character based on the ASCII code
CHARINDEX Returns the position of a substring in a string
CONCAT Adds two or more strings together
Concat with + Adds two or more strings together
CONCAT_WS Adds two or more strings together with a separator
DATALENGTH Returns the number of bytes used to represent an expression
DIFFERENCE Compares two SOUNDEX values, and returns an integer value
FORMAT Formats a value with the specified format
LEFT Extracts a number of characters from a string (starting from left)
LEN Returns the length of a string
LOWER Converts a string to lower-case
LTRIM Removes leading spaces from a string
NCHAR Returns the Unicode character based on the number code
PATINDEX Returns the position of a pattern in a string
QUOTENAME Returns a Unicode string with delimiters added to make the string a valid SQL
identifier
REPLACE Replaces all occurrences of a substring within a string, with a new substring
REPLICATE Repeats a string a specified number of times
REVERSE Reverses a string and returns the result
RIGHT Extracts a number of characters from a string (starting from right)
RTRIM Removes trailing spaces from a string
SOUNDEX Returns a four-character code to evaluate the similarity of two strings
SPACE Returns a string of the specified number of space characters
STR Returns a number as string
STUFF Deletes a part of a string and then inserts another part into the string, starting a
SUBSTRING Extracts some characters from a string
TRANSLATE Returns the string from the first argument after the characters specified in the s
translated into the characters specified in the third argument.
TRIM Removes leading and trailing spaces (or other specified characters) from a strin
UNICODE Returns the Unicode value for the first character of the input expression
UPPER Converts a string to upper-case
SQL NUMERIC FUNCTIONS
Function Description
ABS Returns the absolute value of a number
ACOS Returns the arc cosine of a number
ASIN Returns the arc sine of a number
ATAN Returns the arc tangent of a number
ATN2 Returns the arc tangent of two numbers
AVG Returns the average value of an expression
CEILING Returns the smallest integer value that is >= a number
COUNT Returns the number of records returned by a select query
COS Returns the cosine of a number
COT Returns the cotangent of a number
DEGREES Converts a value in radians to degrees
EXP Returns e raised to the power of a specified number
FLOOR Returns the largest integer value that is <= to a number
LOG Returns the natural logarithm of a number, or the logarithm of a
specified base
LOG10 Returns the natural logarithm of a number to base 10
MAX Returns the maximum value in a set of values
MIN Returns the minimum value in a set of values
PI Returns the value of PI
POWER Returns the value of a number raised to the power of another nu
RADIANS Converts a degree value into radians
RAND Returns a random number
ROUND Rounds a number to a specified number of decimal places
SIGN Returns the sign of a number
SIN Returns the sine of a number
SQRT Returns the square of a number
SQUARE Returns the square of a number
SUM Calculates the sum of a set of values
TAN Returns the tangent of a number
SQL DATE FUNCTIONS
Function Description
CURRENT_TIMESTAMP Returns the current date and time
DATEADD Adds a time/date interval to a date and then returns the date
DATEDIFF Returns the difference between two dates
DATEFROMPARTS Returns a date from the specified parts (year, month, and day va
DATENAME Returns a specified part of a date (as string)
DATEPART Returns a specified part of a date (as integer)
DAY Returns the day of the month for a specified date
GETDATE Returns the current database system date and time
GETUTCDATE Returns the current database system UTC date and time
ISDATE Checks an expression and returns 1 if it is a valid date, otherwise
MONTH Returns the month part for a specified date (a number from 1 to
SYSDATETIME Returns the date and time of the SQL Server
YEAR Returns the year part for a specified date
SQL SERVER ADVANCED FUNCTIONS
Function Description
CAST Converts a value (of any type) into a specified datatype
COALESCE Returns the first non-null value in a list
CONVERT Converts a value (of any type) into a specified datatype
CURRENT_USER Returns the name of the current user in the SQL Server database
ISNULL Return a specified value if the expression is NULL, otherwise retu
ISNUMERIC Tests whether an expression is numeric
NULLIF Returns NULL if two expressions are equal
SESSION_USER Returns the name of the current user in the SQL Server database
SESSIONPROPERTY Returns the session settings for a specified option
SYSTEM_USER Returns the login name for the current user
USER_NAME Returns the database user name based on the specified id