Sam SQL
Sam SQL
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).
1. NOT NULL
2. UNIQUE
3. PRIMARY KEY
4. FOREIGN KEY
5. CHECK
6. DEFAULT
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))
The UNIQUE and PRIMARY KEY constraints both provide a guarantee for uniqueness for a
column or set of columns.
The PRIMARY KEY constraint uniquely identifies each record in a database 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
Example:
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.
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'),
The default value will be added to all new records, if no other value is specified.
The following SQL creates a DEFAULT constraint on the "City" column when the "student"
table is created:
Example:
To create a DEFAULT constraint on the "City" column when the table is already created, use the
following SQL:
Example:
Example:
SQL aggregate functions return a single value, calculated from values in a column.
SYNTAX:
SELECT AVG(column_name) FROM table_name
EXAMPLE:
select avg(M1) as 'average' from student2
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
The MAX() function returns the largest value of the selected column.
SYNTAX:
SELECT MAX(column_name) FROM table_name
EXAMPLE:
SYNTAX:
SELECT MAX(column_name) FROM table_name
EXAMPLE:
SYNTAX:
EXAMPLE:
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.
Syntax:
Example:
Syntax:
SELECT UPPER(column name) from tablename
Example:
Syntax:
Example:
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:
Example:
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:
Example:
Syntax:
Example:
SUBSTRING function retrieves a portion of the given string starting at the specified
character(startindex) to the number of characters specified(length).
Syntax:
Example:
GetDate() : The GETDATE() function returns the current date and time from the SQL Server
Example:
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:
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 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:
FROM Employee
DateDiff() function: The DATEDIFF() function returns the time between two dates
Syntax:
DATEDIFF(datepart,startdate,enddate)
Example:
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.
EXAMPLE:
select convert(varchar(19),getdate())
select convert(varchar(10),getdate(),110)
select convert(varchar(11),getdate(),106)
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.
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:
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
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:
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
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()
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