Sie sind auf Seite 1von 76

Page 1 of 76

CHAPTER-2

QUERYING DATA

1. Data And Datatypes:-


(a) Data:-
In SQL, data can exist in three forms:-

Structured Data:-
Structured Data has a definite structure.
It follows a defined format and has a predefined length.
Ex- String, Numeric Data etc.
It can be easily stored in a table.
Example:-
Roll number of a student is a numeric value and
can be easily stored in the ROLLNO column of
STUDENT table.
Name of student can be easily stored in NAME
column of STUDENT table.
Geographical data like longitude and latitude.
Geometrical data with coordinates.
Semi-Structured Data:-
Semi-structured data has an indefinite structure.
It cannot be stored easily in a database table.
The attributes of semi-structured data can change.
Semi-structured data is generally stored in the XML
format.
Example:-
The details of customers contain various attributes such
as Customer ID and Customer Name that can change
for every customer.
Page 2 of 76

Unstructured Data:-
Unstructured data does not have a defined structure.
It does not necessarily follow any format or sequence.
It does not follow any rule and it is not predictable.
Example:-
Text file, Image file, Videos, Sound clips etc.

(b) Datatypes:-
Datatypes represents the type of data that a database object can
store. This data can be in the form of characters, numbers or
symbols.
The datatypes are associated with the columns, local variables
or expressions defined in the database.
We must specify the datatype of a column according to the
data to be stored in it.
Types Of Datatypes:-
SQL server supports various datatypes which are categorized
as:-
Numeric Datatypes
Character and String Datatypes
Date and Time Datatypes
Binary Datatypes
Other Datatypes
Example:-
To store name of the employee in EMPLOYEE NAME column,
we must specify a Character And String Datatype for the
column like char, varchar,varchar2 etc.
2. Types Of Datatypes:-
(a) Numeric Datatypes:-
Numeric Datatypes allows user to store numeric values in the
database.
Page 3 of 76

(b) Character And String Datatypes:-


The Character and String Datatypes allows user to store text values in
the database.
Page 4 of 76

(c) Date And Time Datatypes:-


The Date and Time Datatypes allows user to store date and time
values in the database.

(d) Binary Datatypes:-


Binary Datatypes allows user to store Binary data in the database.
Page 5 of 76

(e) Other Datatypes:-


The Other Datatypes allows user to store unique identifiers, cursors,
table, xml and spatial data in the database.
Page 6 of 76

3. Creating Databases and Tables:-


(a) Creating a Query:-
All the statements in the SQL server are written in a Query.
To create a new query in SQL server, follow the given steps:-
1. Open SQL Server Management Studio.
2. Click on New Query option.

3. To save new query , click on Save button, then type a name for
the query and Click on Save .
4. To Execute a Query, select the statements and then click on
Execute option or press F5 on keyboard.
(b) Creating a Database:-
To create a database, we use syntax:-
CREATE DATABASE DATABASE_NAME
Page 7 of 76

Example:-

(c) Creating a Table Within Database:-


To create a table EMPLOYEE within a database SIDDATA :-
Use the Database by using the syntax:-
USE DATABASE_NAME
Create the table using the syntax:-
CREATE TABLE TABLE_NAME

(Attribute1 Datatype1,

Attribute2 Datatype2,

Attribute3 Datatype3,

. Donot Use Comma(,)


after the last statement
.

AttributeN DatatypeN) ;
Page 8 of 76

Here, if the Datatype is Character and String Datatype then


write the Attribute Name along with its size enclosed within
parenthesis.
SQL Server is not case-sensitive, so all the statements written
in Lowercase are same as written in Uppercase.
Example:-

Name of the Attribute


which has a Blank Space
in it should be enclosed
within Double Quotes
or Square Brackets.

Table so formed is as follows:-


Page 9 of 76

Naming Of Attributes:-
The Attribute Name should be a sequence of letters, digits
and underscore. Underscore should be treated as letter.
Attribute Name should start with either a letter.
Symbols can also be included in Attribute Name but it
should not be written at first place of attribute name. Not
all symbols can be included.
Attribute Name should not be a Keyword/Reserved Word.
(d) Inserting Data Into Table:-
We can insert data into table by using the syntax:-
INSERT INTO TABLE_NAME VALUES(VALUE1,VALUE2,................VALUEn) ;

Provided:-
Data should be entered in same order as that of Attributes at
the time of table creation.
By default Date should be written in YYYY-MM-DD format.
If a value is of Character and String Datatype Or Date-Time
Datatype, then it should be written within single quotes.
Ex- John, 1992-12-23 etc.
Example:-

The EMPLOYEE Table


Page 10 of 76

The EMPLOYEE Table

(Horizontal View)
Page 11 of 76

4. The SELECT Statement:-


We can retrieve the required data from the database tables in many
ways out of which on e is the Select Statement.
SELECT statement is basically used to access and retrieve data
from a database.
The syntax for using SELECT statement is:-
SELECT [ALL | DISTINCT] Select_Column_List

INTO New_Table_Name

FROM [Table_Name|View_Name]

WHERE Search_Condition
Provided:-

ALL is represented by Asterisk Symbol(*), which means to


display all the columns of table.
DISTINCT specifies that only the unique rows should
appear in the resultant set if there are any repeated rows.
Select_Column_List is the list of columns which are going
to be displayed in the result set.
INTO creates a new table and inserts the resulting rows
from query into it.
New_Table_Name is the name of new table to be created.
FROM Table_Name retrieves data from the table having
name Table_Name.
View_Name is the name of the view according to which
data will be displayed.
WHERE specifies the search condition for the rows
returned by the query.
Search_Condition specifies the condition to be satisfied to
return the selected rows.
The components of Select Statement are used as per the
requirements of user to display and retrieve the data.
Page 12 of 76

Select Statement can be used in many different ways are as follows:-

(a) To Display all Columns & Data:-


Syntax:-
SELECT *FROM Table_Name
Example:-

(b) To Display Selected Columns:-


Syntax:-
SELECT Column1,Column2,........,ColumnN

FROM Table_Name

Example:-
Page 13 of 76

(c) To Display all Columns with Distinct Rows:-


Syntax:-
SELECT DISTINCT *FROM Table_Name

Example:-
SELECT DISTINCT *FROM EMPLOYEE
After executing this statement, only unique rows will be displayed
and all repeated entries will be hidden.
(d) To Display Selected Columns with Distinct Rows:-
Syntax:-
SELECT DISTINCT Column_List FROM Table_Name

Example:-
SELECT DISTINCT EMPID,EMP_NAME,[EMP DESIG]
FROM EMPLOYEE
After executing this statement, only unique rows of these selected
columns will be displayed.
5. Customizing The Display:-
In SQL Server, display of the tables can be customized by using user
defined headings and literals. This does not changes the name of the
column in the table, instead it is just a customized display of the table.
(a) Creating User Defined Headings:-
User-Defined Headings should be enclosed within single quotes if
they contain blank spaces, otherwise written without single quotes.
The User-Defined Headings can be created in three ways:-
Using Equal to Sign:-
Syntax:-
SELECT Heading1=ColumnName1, Heading2=ColumnName2

FROM Table_Name

Heading written aside Column Name:-


Syntax:-
SELECT ColumnName1 Heading1, ColumnName2 Heading2

FROM Table_Name
Page 14 of 76

Using the Keyword AS:-


Syntax:-
SELECT ColumnName1 AS Heading1,ColumnName2 AS Heading2

FROM Table_Name

Common Example representing all the three ways is as follows:-


Page 15 of 76

(b) Display Customization Using Literals:-


Literals are string values that are enclosed in single quotes and added
to the Select Statement. The Literal values are printed in a separate
column when they are written in the Select_Column_List.
Syntax:-
SELECT ColumnName1, Literal ,ColumnName2

FROM Table_Name

Example:-

(c) Concatenating the Text Values with Columns:-


Concatenation is the operation where two strings are joined to make
one string. It can be applied only to Attributes having Character and
String Datatypes.
Sometimes, we require to display the value of multiple
columns in a single column alongwith the description of values.
Concatenation Operator(+):-
It is used to concatenate string expressions and also to add
additional description.
Syntax For Concatenation:-
SELECT ColumnName1 + Text1+ ColumnName2 + Text2

AS NewColumnName FROM Table_Name


Page 16 of 76

Example:-

6. Calculations With Column Values:-


Sometimes ,we need to show calculated values for the columns and for
this we use Arithmetic Operators.
(a) Arithmetic Operators:-
Arithmetic operators are used to perform mathematical
operations on numeric columns and numeric constants.
SQL server supports the following arithmetic operators:-
OPERATOR SYMBOL OPERATOR NAME
+ Addition
- Subtraction
/ Division
* Multiplication
% Modulo (to obtain remainder)
All arithmetic operators can be used in the SELECT statement
with column names and numeric constants in any combination.
Page 17 of 76

(b) Precedence of Arithmetic Operators:-


Expression within parenthesis ( ) is executed first.
Order of execution is from Left to Right
The following precedence is followed thereafter:-

(c) Retrieve data using Arithmetic Operators:-


Syntax:-
SELECT ColumnName1, NewColumnName = Expression

FROM Table_Name

Here, Expression is an algebraic expression which is a


combination of Constants, Operators and ColumnNames.
Example:-
Page 18 of 76

7. The WHERE Clause:-


To retrieve selected rows based on a specific condition, we use WHERE
clause along with the SELECT statement.
Syntax:-
SELECT Column_List

FROM Table_Name

WHERE Expression1 Comparison_Operator Expression2

Conditional Expression

(a) Comparison Operators with WHERE Clause:-


Page 19 of 76

Example representing Use of Comparison Operators is as follows:-

(b) Logical Operators with WHERE Clause:-


Logical operators are used in SELECT statement along with WHERE
clause to retrieve records that Match One Or More Condition.
The syntax for using logical operator in SELECT statement is:-
SELECT Column_List

FROM Table_Name

WHERE ConditionalExpression1 Logical_Operator ConditionalExpression2


Page 20 of 76

Conditional Expressions are those expression which are a


combination of two expressions and one comparison operator.
Types Of Logical Operators:-
OR:- Returns a true value if at least one condition is
satisfied.
AND:- It is used to join two conditions and returns a true
value only if both the conditions are satisfied.
NOT:-It reverses the result of search condition. In case of
NOT, the query retrieves all the rows except those that
match the specified condition.
Example (Use Of Logical Operators):-
Page 21 of 76

(c) Range Operators with WHERE Clause:-


Range operators retrieve data based on range.
The syntax for using range operators in the SELECT statement
is:-
SELECT Column_List

FROM Table_Name

WHERE Expression1 Range_Operator Expression2 AND Expression3

Types Of Range Operators:-


BETWEEN:- Specifies an inclusive range to search.
NOT BETWEEN:- Excludes the specified range from the
result set.
Example (Use Of Range Operators):-

(d) List Operators with WHERE Clause:-


List operators are used in SELECT statement along with WHERE
clause to retrieve data after specifying a set of values to check
whether the specified value matches the data of table or not.
Page 22 of 76

The syntax for using list operator is:-


SELECT Column_List

FROM Table_Name

WHERE Expression List_Operator (Value_List)

Here, Expression is any valid combination of constants,


Attributes, functions etc.
List_Operator is a valid list operator.
Value_List is a list of values or instances to be included or
excluded within single quotes & separated by commas.
Types Of List Operators:-
IN:- The IN keyword selects the values that match
anyone of the values given in the Value_List.
NOT IN:- The NOT IN keyword restricts the selection of
values that match anyone of the values in Value_List.
Example (Use Of List Operators):-
Page 23 of 76

8. The LIKE Keyword and Wildcards:-


LIKE keyword is used to search a string and match the given character
string with the specified pattern by using wildcards.
The Specified Pattern must be a combination of wildcard characters and
string characters.
(a) Wildcards:-
Wildcards are special characters that are used to match patterns.

(b) Using Wildcards with LIKE:-


The wildcards can be combined into single expression with LIKE
keyword. LIKE is always used with WHERE clause.
Possible Different Patterns:-
Page 24 of 76

Syntax for using LIKE :-


SELECT Column_List

FROM Table_Name

WHERE Search_ColumnName LIKE Expression

Here, Expression is a specified pattern which is a combination


of string characters and wildcard characters. This pattern is
searched in the column having name Search_ColumnName.
Example (Use Of LIKE):-
Page 25 of 76

9. NULL Values & Unknown Value Operators:-


(a) NULL Value:-
A NULL value in a column implies the data value for the column is not
available.
(b) Unknown Value Operator:-
Whenever we find the records by including or excluding NULL valued
instances , we require to use unknown value operators.
Syntax for using Unknown Value Operator:-
SELECT Column_List

FROM Table_Name

WHERE Search_ColumnName UnknownValue_Operator

Types Of Unknown Value Operator:-


IS NULL:- Returns true if the instance is NULL.
IS NOT NULL:- Returns true if the instance is NOT NULL.
No two NULL values are equal and hence two NULL values
cannot be compared.
NULL values are always the first item to be displayed in the
output when sorted in Ascending Order.
Example (Use Of Unknown Value Operator):-
Page 26 of 76

(c) The ISNULL( ) Function:-


The ISNULL( ) function replaces the null values with the specified
replacement value. The syntax for using ISNULL( ) function is:-
ISNULL (Check_Column, Replacement_Value)

Where:-
Check_Column is the name of column to be checked for NULL
Replacement_Value is the value that replaces the null values in result
set.
Syntax for using ISNULL( ) with SELECT :-
SELECT Column_List , ISNULL(Check_Column,Replacement_Value)

AS Check_Column FROM Table_Name

Points To Remember:-
While using ISNULL( ), Column_List should not include
Check_Column.
Replacement_Value must be of Numeric Type i.e it should
be a number.
ISNULL( ) only displays the Replacement_Value in place of
NULL, but it does not change the values in the Table.
Example:-
Page 27 of 76

(d) COALESCE( ) Function:-


The COALESCE( ) function checks the instances of each column whose
name is given inside its parenthesis and then returns the first non-
null value detected among all the columns.
If all the instances of all the columns written inside COALESCE()
are NULL, then NULL value is returned.
The first non-null value returned by COALESCE() is displayed in
the new specified column.
Syntax Of COALESCE( ):-

COALESCE( Check_Column_List)

Where, Check_Column_List is the list of columns to be checked


for Non-NULL value.
Syntax for using COALESCE( ) with SELECT:-
SELECT Column_List, COALESCE(Check_Column_List)

AS New_Column_Name FROM Table_Name

Where, New_Column_Name is the name of new specified


column in which the value returned by COALESCE() is displayed
Example:-
Page 28 of 76

Working Of COALESCE( ):-


Step1:- It takes first instances of each column listed in
Check_Column_List.
Instances are taken in same sequence as given in
Check_Column_List .
Example:-
Here, In this case it firstly take instances :
516,NULL and 991011
Step2:- Now it takes first instance of first Column in
Check_Column_List and checks whether it is Non-Null
Or NULL.
If it is Non-Null, then this value is displayed as first
Instance of New Column.
Otherwise
If it is NULL, then it takes first instance of Second
Column given in Check_Column_List and the same
checking procedure is repeated until we get a non-null
value.
Example:-
Here, in this case it takes first instance of
[RESIDENCE NUMBER] column i.e 516 and since it is
Non-Null, 516 is first instance of RETURNED_VALUE.
Step3:- Once we get first non-null instance for our New Column
then STEP-1 and STEP-2 are repeated for set of Second
Instances in columns given in Check_Column_List.
Further, this process is repeated for each set of
Instances of all columns in Check_Column_List.

10. The ORDER BY Clause:-


The ORDER BY clause of SELECT statement is used to display the
records in a specific or sequential order.
Using ORDER BY, data can be displayed in the Ascending or
Descending Order of values in a given column.
It only displays the data in a specific order, it does not sort
or change the table physically.
Page 29 of 76

In Alphabetical Ordering, if ORDER BY is assigned ASC then


data is ordered from A to Z ,while in case of DESC it is
ordered from Z to A.
Syntax for using ORDER BY:-
SELECT Column_List

FROM Table_Name

ORDER BY Column_Name [ASC|DESC]


Where,
Column_Name is the name of column on which sorting is
performed.
Out of ASC and DESC, only one format is used at a time.
ASC specifies that column value should be displayed in
Ascending order.
DESC specifies that column value should be displayed in
Descending order.
If ASC or DESC is not specified, then by default records are
displayed in Ascending Order.
Example:-
Page 30 of 76

11. The TOP Keyword:-


The TOP keyword is used with SELECT in three forms:-
(a) To Retrieve n records:-
The TOP keyword is used to retrieve only the first n records/
rows from the top of the table.
Syntax:-
SELECT TOP n Column_List FROM Table_ Name

Where, n is the number of records to be displayed from


the top of the table.
Example:-

(b) To Retrieve n % records:-


TOP keyword along with PERCENT is used to display the n % of
total number of records of the table.
Syntax:-
SELECT TOP n PERCENT Column_List FROM Table_Name

Where, n is the percentage of rows to be displayed


If n is fractional, then greater integer is considered.
Ex:- If n% of total rows is 5.4, then 6 rows are retrieved.
Page 31 of 76

Example:-

(c) TOP keyword along with WITH TIES:-


By using WITH TIES with TOP keyword, the result set includes
all the additional rows that match the last row returned by the
TOP keyword in terms of column according to which table is
ordered in ORDER BY clause.
WITH TIES is always used along with ORDER BY clause.
Syntax:-
SELECT TOP n WITH TIES Column_List FROM Table_Name

ORDER BY Column_Name [ASC|DESC]

Example:- (See the new EMPLOYEE table on next page)


Page 32 of 76

To show the use of WITH TIES, we have added 2 more records in the
EMPLOYEE table. The new EMPLOYEE table is as follows:-
Page 33 of 76

12. OFFSET and FETCH Clause:-


The OFFSET and FETCH clause are used to retrieve a
specific number of records starting from a particular
position in the table.
The result should be sorted on a particular column,
hence:-
OFFSET and FETCH are always used with
ORDER BY clause.
FETCH can only be used with OFFSET.
Syntax:-
SELECT Column_List

FROM Table_Name

ORDER BY Column_Name

OFFSET Offset_Row_Expression [ROW | ROWS]

FETCH [FIRST | NEXT] Fetch_Row_Expression [ROW | ROWS]

ONLY

Where:-

Offset_Row_Expression is either Integer or Expression

Fetch_Row_Expression is either Integer or Expression

OFFSET specifies the number of rows to be excluded before query execution.

FETCH specifies the number of rows to be returned after excluding rows in


OFFSET .

FIRST or NEXT are used to FETCH upcoming rows after OFFSET.

Out of FIRST and NEXT, only one is used at a time because both have same
meaning.
Page 34 of 76

Example:-

13. RANKING Functions:-


Ranking functions are used to generate sequential numbers for
each row or to give rank based on specific criteria. They return a
ranking value for each row.
There are four ranking functions in SQL server:-
row_number( )
rank( )
dense_rank( )
ntile( )
All these functions are used with OVER clause along with
ORDER BY clause, which determines the Ascending or
Descending sequence in which rows are assigned a rank.
We can also use PARTITION BY clause with OVER clause to
partition the rows on which the ranking is performed. It
divides the result set returned into partitions based on
specified condition and then the ranking function is applied
in each partition.
(a) The row_number( ) Function:-
The row_number( ) function returns the sequential numbers
(starting from 1) for the rows in a result set based on a column.
Page 35 of 76

Syntax :-
SELECT Column_List,

row_number( ) OVER (ORDER BY Column_Name [ASC|DESC])

AS New_Column_Name FROM Table_Name

Example:-

(b) The rank( ) Function:-


The rank( ) function returns the rank of each row in a result set
based on specific criteria.
It does not provides consecutive ranks i.e, similar
records are given same ranks and after that when a
different record occurs then the rank given to this record
is n+1,where n is the number of records already
allotted a rank.
The record with maximum value will get rank as 1, if
ORDER BY clause states DESC.
Page 36 of 76

The record with minimum value will get rank as 1, if


ORDER BY clause states ASC.
Syntax:-
SELECT Column_List,

rank( ) OVER (ORDER BY Column_Name [ASC|DESC])

AS New_Column_Name FROM Table_Name

Example:-

(c) The dense_rank( ) Function:-


The dense_rank( ) function is used where consecutive ranking
values are needed to be given based on specified criteria.
It provides consecutive ranks i.e, one set of similar
records is given 1st rank, then another set of similar
records is given 2nd rank and so on.
Syntax:-
SELECT Column_List,

dense_rank( ) OVER (ORDER BY Column_Name [ASC|DESC])

AS New_Column_Name FROM Table_Name


Page 37 of 76

Example:-

(d) The ntile( ) Function:-


The ntile( ) function is used to divide the result set into a
specific number of groups.
Points To Remember:-
This function accepts a positive integer to
distribute the rows into the number of groups.
Number of groups formed using ntile( ) is equal to
the Positive Integer accepted by ntile( ).
Distributed groups are numbered, starting from 1
to the Positive Integer of ntile( ).
All rows included in one group are given same
rank.
Page 38 of 76

No.of Rows in a Group:-


The no. Of rows in a group depends on total no. of rows in a table.
If the total no. of rows in the table is divisible by Positive Integer of
ntile(), then each group contain equal number of rows.
If the total no. of rows in the table is not divisible by Positive Integer of
ntile( ), then the groups are distributed in such a way that all the groups
contain different number of rows. Some contain Larger no. of rows and
others contain Smaller no. of rows while the rest contain equal no. of
rows.
In the display, the groups with Larger no. of rows comes first, then the
groups with Smaller no. of rows and at last the groups with Equal no. of
rows.
Basically, the groups are distributed in such a way that each group
should get maximum no. of possible rows.
Syntax:-
SELECT Column_List,

ntile(n ) OVER (ORDER BY Column_Name [ASC|DESC])

AS New_Column_Name FROM Table_Name

Where, n is the Positive Integer accepted by ntile().


Also, n = No. of Groups Formed
Example:-
Page 39 of 76

14. ANALYTICAL Functions:-


When the rows have some common instances (not all instances as
common) with other rows then Analytical Functions are used to
retrieve the data in such a form, so we get the data of common
instances in single or multiple rows.
There are four Analytical Functions in SQL server:-
lead( )
lag( )
first_value( )
last_value( )

All these functions return the values from the Partially Similar
Rows (having at least one instance as common) in the same result
set.

We have created SALESDATA table to represent the use of


Analytical Functions, as shown below:-
Page 40 of 76

(a) The lead( ) Function:-


This analytical function is used to compare values in the
current row with the values in subsequent or upcoming rows.
Syntax:-
SELECT Column_List,

lead (scalar_expression,[offset],[default] )

OVER ([PartitionBy_clause] OrderBy_clause )

AS New_Column_Name

FROM Table_Name

Where:-
scalar_expression is the value to be returned
based on specified offset. It can be any expression
or function.

Here, if scalar_expression contains an Aggregate


Function then we must use GROUP BY clause
after the FROM Table_Name statement.

offset is the interval by which the number of rows


to be forwarded. It is always a positive integer.

default denotes the default value(i.e NULL) which


is to be returned if scalar_expression is not
present.

OVER( ) specifies the order of data before the


function is applied.
Page 41 of 76

Example(Use Of lead( ) Function):-


Page 42 of 76

(b) The lag( ) Function:-


This function returns the values from the preceding rows in the
same result set. It is used to compare the values in the current
row with the values in the previous rows.
Syntax:-
SELECT Column_List,

lag (scalar_expression,[offset],[default] )

OVER ([PartitionBy_clause] OrderBy_clause )

AS New_Column_Name

FROM Table_Name

Where:-
scalar_expression is the value to be returned
based on specified offset. It can be any expression
or function.
Here, if scalar_expression contains an Aggregate
Function then we must use GROUP BY clause
after the FROM Table_Name statement.
offset is the interval by which the number of rows
to be sorted backward. It is always a positive
integer.
default denotes the default value(i.e NULL) which
is to be returned if scalar_expression is not
present.
OVER( ) specifies the order of data before the
function is applied.
lag() works similar to lead() , the only difference is
that:-
lead() retrieves data from upcoming rows and
display it corresponding to current row.
BUT
lag() retrieves data from previous rows and
display it corresponding to current row.
Page 43 of 76

Example:-
Page 44 of 76

(c) The first_value( ) Function:-


It returns the first value in an ordered set of records.
Syntax:-
SELECT Column_List,

first_value (scalar_expression)

OVER ([PartitionBy_clause] OrderBy_clause [rows_range_clause] )

AS New_Column_New

FROM Table_Name

Where:-
scalar_expression is the value to be returned
based on specified offset. It can be any expression
or function.
row_range_clause:-
It limits the number of rows within the partition
by specifying start & end points. It is used inside
OVER( ). (will be discussed in brief later)
PartitionBy Clause:-
It is used to partition the rows according to the
specified distinct instance. [Used inside OVER()]
Syntax:-
PARTITION BY Column_Name
Example:-
Page 45 of 76

(d) The last_value( ) Function:-


This function returns the last value in an ordered set of
records.
Syntax:-
SELECT Column_List,

last_value (scalar_expression)

OVER ([PartitionBy_clause] OrderBy_clause [rows_range_clause] )

AS New_Column_New

FROM Table_Name

Example:-
Page 46 of 76

15. Aggregate Functions:-


The aggregate function summarizes the values of a column or a
group of columns and produces a single value.
Syntax for using Aggregate Function:-
SELECT aggregate_function([ALL|DISTINCT] expression)

FROM Table_Name

Where:-
ALL specifies that the aggregate function is
applied to all the values in the specified column.
DISTINCT specifies that the aggregate function is
applied to only unique values in the specified
column.
expression may be a column or an expression
with operators.
Different Aggregate Functions in SQL:-
We can summarize data using the following aggregate
functions:-
SUM( ) :- Returns the sum total of values in a
numeric expression, either all or distinct.

AVG( ):- Returns the average of values in a


numeric expression, either all or distinct.

COUNT( ):- Returns the number of values in an


expression, either all or distinct.

MIN( ):- Returns the lowest value in the


expression.

MAX( ):- Returns the highest value in the


expression.
Page 47 of 76

Example (Use of Aggregate Functions):-

Functions :- There are different kinds of functions in SQL server which are used to perform specific tasks.
Ex- String Functions, Conversion Functions, Date Functions, Mathematical Functions, Logical Functions,
System Functions, Aggregate Functions, Analytical Functions, etc. Syntax for using a function is:-

SELECT function_name(parameters)

Where, parameters can be column_name or any other required parameters according to function type.
Page 48 of 76

16. String Functions:-


String functions are used to manipulate the string values in the
result set.
Page 49 of 76
Page 50 of 76
Page 51 of 76
Page 52 of 76

17. Conversion Functions:-


Conversion functions are used to convert data from one datatype
to another.

Style Values used in conversion functions are given below along with their
formats:-
Page 53 of 76

18. Date Functions:-


Date functions are used to manipulate the date and time values.
We can perform arithmetic operations on date values or parse the
date values.
Date Parsing includes extracting components like day, month and
year from date value.
Example:-
Use of datepart( ) function for parsing date values.
Use of datediff( ) function to find difference between two dates.
Etc.

Some abbreviations used to extract different parts of date are given below:-
Page 54 of 76

Some Date Functions used in SQL server are as follows:-


Page 55 of 76
Page 56 of 76
Page 57 of 76

19. Mathematical Functions:-


Mathematical functions are used to manipulate numeric values in
a result set. We can perform various numeric and arithmetic
operations on numeric values.
Page 58 of 76

Given below is the table showing the usage of round( ) function:-


Page 59 of 76

20. Logical Functions:-


Logical functions are used to perform logical operations on result
set. They return Boolean value as Output.
Page 60 of 76

21. System Functions:-


The System Functions are used to query the system tables. System
Tables are a set of tables that are used by SQL server to store
information about users, databases, tables and security. The
system functions are used to access SQL server databases.
Page 61 of 76
Page 62 of 76

22. The GROUP BY and HAVING Clauses:-


The GROUP BY clause summarises the result set into groups.
HAVING clause further restricts the result set to produce the data
based on a condition.
Syntax for using GROUP BY:-
SELECT Column_List

FROM Table_Name

WHERE Search_Condition

GROUP BY [ALL] Expression

HAVING Search_Condition

Where:-
Search_Condition is the conditional expression on which
the result set is to be produced.

Expression can be column_name or expression on which


the result set is to be grouped.

ALL is used to include those groups that do not meet


Search_Condition of WHERE as well as HAVING.

Working of GROUP BY & HAVING:-


GROUP BY clause collects the data that matches
the condition and summarises it into expression
to produce a single value for each group.

The HAVING clause eliminates all those groups


that do not match the specified condition.
Page 63 of 76

Example of GROUP BY & HAVING:-

We have created SALESHISTORY table for representing the use of GROUP BY &
HAVING clauses:-
Page 64 of 76

GROUP BY on multiple fields:-


The GROUP BY clause can be applied on multiple fields.
Syntax:-
SELECT Column_List

FROM Table_Name

WHERE Search_Condition

GROUP BY [ALL] Expression1,Expression2,.......ExpressionN

HAVING Search_Condition

Example:-

We have created FRIENDS table to demonstrate the use of GROUP BY on


multiple fields and also to demonstrate the use of GROUP BY SETS.
Page 65 of 76

GROUP BY SETS clause:-


It is used to combine the result generated by multiple
GROUP BY clauses into a single result.
SELECT Column_List

FROM Table_Name

WHERE Search_Condition

GROUP BY

GROUPING SETS ( (Column_Name1,Column_Name2),

(Column_Name1),

(Column_Name2) )
Page 66 of 76

Example of GROUP BY SETS clause:-

23. ROLL UP & CUBE Operators:-


ROLL UP and CUBE are used to apply multiple levels of
aggregation on result sets and generate the required report.
(a) ROLL UP :-
It is the extension of GROUP BY clause. It generates the result
set that contains:-
1. Subtotal for each group.
2. Grand total of all groups.
Page 67 of 76

Example of ROLL UP:-

(b) CUBE :-
It extends the functionality of ROLL UP. It generates the result
that contains:-
1. Subtotal for each group.
2. Grand total of all groups.
3. All other possibilities involved within groups.
Page 68 of 76

Example of CUBE:-

(c) Difference between ROLLUP and CUBE:-


ROLLUP CUBE
1. It does not report all It reports all the possible
possible combinations from combinations from the
the columns on left side. columns on left side.
2. The number of groupings The number of groupings
returned by ROLL UP equals returned by CUBE equals
the number of columns the double of the number of
specified in GROUP BY clause columns specified in GROUP
plus one. BY clause.
Page 69 of 76

24. PIVOT Operator:-


PIVOT is used to transform a set of columns into values or records.
It rotates a table valued expression by turning the unique values
from one column in the expression into multiple columns in the
Output.
Syntax of PIVOT:-
SELECT Column_List, Instance_List

FROM

(SELECT Column_Name,Pivot_Column,Value_Column FROM Table_Name)


AS Table_Alias

PIVOT ( AggregateFunction(Value_Column)

FOR Pivot_Column IN(Instance_List)

AS PivotedTable_Alias
Where:-

Column_List must include the Column_Name according to which the table is


arranged.

Instance_List includes those instances which are included in Pivot_Column and


each instance must have an Alias (written using AS keyword) which will be
used as column name in Pivoted Table. Each instance must be enclosed in
Square Brackets as they are going to a column in pivoted table.

Column_Name is the name of column according to which table is arranged.

Pivot_Column is the name of column whose entries or instances will be used


as column name in the Pivoted Table.

Value_Column is the name of column whose entries combine using aggregate


function and work as instance in Pivoted Table.

Table_Name is the name of table which is going to be pivoted.

Table_Alias is the name of table generated after execution of sub-query in


parenthesis.

PivotedTable_Alias is the name of table generated finally after pivoting.


Page 70 of 76

Example Of PIVOT:-
The DAILY TRANSACTION Table:-
We have created the DAILY TRANSACTION table to demonstrate the use
of PIVOT & UNPIVOT:-
Page 71 of 76

Process Of Pivoting:-

Example Of PIVOT:-

25. UNPIVOT Operator:-


The UNPIVOT operator allows database users to normalize the
data that has earlier been pivoted. This operator transforms the
multiple column values of a record into multiple records with the
same values in a single column.
Page 72 of 76

Syntax of UNPIVOT:-
SELECT Column_Name,Pivot_Column,Value_Column

FROM (SELECT PivotedTable_ColumnList FROM PivotedTable_Alias)

AS PivotedTable_NewAlias

UNPIVOT

( Value_Column

FOR Pivot_Column IN( PivotedTable_Columns )

) AS UnpivotedTable_Alias

Where:-

Column_Name is the name of column according to which table is arranged.

Pivot_Column is the name of column whose entries or instances are used as


column name in the Pivoted Table.

Value_Column is the name of column whose entries combine using aggregate


function and work as instance in Pivoted Table.

PivotedTable_ColumnList is the list of columns in the already pivoted table.

PivotedTable_Alias is the name of the already pivoted table.

PivotedTable_NewAlias is the name of table generated from Pivoted Table


using the given sub-query.

PivotedTable_Columns is the list of columns of Pivoted Table which were


instances of Pivot_Column in the base table of Pivoted Table.

UnpivotedTable_Alias is the name of the table generated finally after


unpivoting.
Page 73 of 76

Process of Unpivoting:-

Example of UNPIVOT:-

For demonstrating UNPIVOT, first of all we create a table PIVOTEDTABLE which


has already been pivoted and then we unpivot this table.(as shown below)
Page 74 of 76

26. Difference b/w Char & Varchar:-


CHAR VARCHAR
1. It is used to store fixed length It is used to store variable length
character data. character data.
2. Example:- Example:-
If you declare a variable of Char If you declare a variable of Char
with 50 character size, but insert with 50 character size, but insert
only 10 characters in the only 10 characters in the variable
variable then the remaining 40 then the remaining 40 character
character memory remain memory will not get occupied
occupied and will not be freed and will be available for usage in
for usage. other variables.
3. It boosts wastage of memory. It prevents wastage of memory.
4. nchar works like char. nvarchar works like varchar.

27. Schema :-
A Schema is a collection of database objects (like tables), that
comes under the same database and are logically related to each
other. Basically, it is a group of tables that are referenced by same
group name in SQL server. This group name is called Schema.

By default, all the tables created in SQL server database are


created under dbo Schema, where dbo stands for Database
Objects.

(a) Creating a Schema:-


A Schema can be created inside a database using the syntax:-
CREATE SCHEMA Schema_Name

Where, Schema_Name is the name of schema to be created.


Example:-
Page 75 of 76

(b) Adding already created tables into Schema:-


The tables which are created without allotting any schema are
created under default schema dbo. These tables can be
allotted a Schema by using the syntax:-
ALTER SCHEMA Schema_Name

TRANSFER OldSchemaName.TableName

Example:-
In the following table, we are adding all the tables we have
created in this chapter under the schema CH2 :-
Page 76 of 76

(c) Adding Schema to Tables at the time of Table Creation:-


A Schema can be added to new table while creating that table:-

CREATE TABLE SchemaName.TableName

(Attribute1 Datatype1,

Attribute2 Datatype2,

Attribute3 Datatype3,

AttributeN DatatypeN) ;

Example:-

Prepared By: SIDDHARTH

Email id:- siddhhaarrth@gmail.com

Das könnte Ihnen auch gefallen