Uploaded by sosoiraqgirl

محاضرات-اساسيات-قواعد-البيانات

advertisement
Ministry of Higher Education And
Scientific Research
Southern Technical University
AL Qurna Technical Institute
Computer Systems Department
Subject : SQL DataBase Basics
Assistant Programer : Asmaa Hani Ashoor
AL Qurna Technical Institute
Computer Systems Department
SQL DataBase Basics
-------------------------------------------------------------------------------------------------------------------------------
chapter one
Introduction To SQL DataBase Basics
Databases: It is an organized package of logically interconnected data related to a
particular activity. It is also defined as a large group of related data organized and
arranged in a number of data files interconnected with each other to form an
electronic data repository. This repository is managed through specialized software
called Data Base Management System (DBMS).
DataBaseManagement System (DBMS): It is a set of programs that manage the
process of storing and retrieval of data, as well as providing users with access to the
database and dealing with it, and it is the link between users and the database, as it
receives users' requests and then transfers them to the database and implements the
programs necessary to implement these requirements and from Then provide the
user with the desired results. Such as: VFP, Oracle, SQL-SERVER, Ms-Access.
Application
software
database management
system DBMS
-------------------------------------------------------------------------------------------------------------------------------
2
Asmaa Hani
AL Qurna Technical Institute
Computer Systems Department
SQL DataBase Basics
-------------------------------------------------------------------------------------------------------------------------------
Features of databases
1. Arrange user data in a way that is easy to access and deal with.
2. Determining the types of data that are stored accurately such as texts, numbers,
dates, currencies.
3. Access to information very quickly if it is indexed.
4. No need to repeat information
5. The possibility of creating backup copies of the database with ease.
SQL (Structured Query Language): which is the language used to perform
operations on databases, including adding, updating, or deleting data from the
database, or to modify the database structure itself.
SQL Features
1. Data can be transferred within rules that use SQL language with ease, as this
language supports desktop and laptop computers, tablets, servers and
mainframes.
2. It can be run on local systems that use internal networks or the Internet.
3. SQL is an interactive language that is used to communicate with a database to
help retrieve data for complex queries in seconds.
4. Easy access to data
5. Fast data storage and retrieval
-------------------------------------------------------------------------------------------------------------------------------
3
Asmaa Hani
AL Qurna Technical Institute
Computer Systems Department
SQL DataBase Basics
-------------------------------------------------------------------------------------------------------------------------------
sql language uses
It is used to create a system for managing databases, dealing with information in
them, and implementing commands needed by database users. These commands
include:
1. Organizing and modifying data by adding, deleting, and modifying.
2. Searching databases and accessing information.
3. The SQL programming language is used to protect data.
4. It is used to control permissions and permissions for users who interact with
databases.
-------------------------------------------------------------------------------------------------------------------------------
4
Asmaa Hani
AL Qurna Technical Institute
Computer Systems Department
SQL DataBase Basics
-------------------------------------------------------------------------------------------------------------------------------
SQL command types
1. Data Manipulation Language(DML): This group contains sentences whose
purpose is to give the ability to deal with data without affecting its structure
and general form, so that you can query data, add records, delete or modify
them.
2. Data Definition Language(DDL): The commands that fall under this group
provide the ability to define data, its form, and the way it is linked to each
other through the use of commands to create tables and create a database.
3. Data Control Language (DCL): This set of commands helps in defining the
permissions that can be granted or taken away from users in the database.
-------------------------------------------------------------------------------------------------------------------------------
5
Asmaa Hani
AL Qurna Technical Institute
Computer Systems Department
SQL DataBase Basics
-------------------------------------------------------------------------------------------------------------------------------
chapter Two
Data Normalization
Data Normalization: is the process of a clearance the database of inappropriate
reputation of data by depending on the inference rules and functional dependency.
(Data Anomalies)
We note in the following table that the information of the employee and the department
in which he works are in one table, and as a result, the repetition of some data such as the
name and location of the department in each record will lead to several problems.
1
Asmaa Hani
AL Qurna Technical Institute
Computer Systems Department
SQL DataBase Basics
-------------------------------------------------------------------------------------------------------------------------------
1.Insertion Anomaly: Since we cannot add a new section unless the section contains
an employee; Because the main key of the table is the employee number.
2.Updating Anomaly: Where if we modify the location (loc) of the department, the
modification process must be performed for all employees in this department;
Otherwise, this process will lead to data incompatibility.
3. Deletion Anomaly: Section 3 contains only one employee, and if we delete this
employee, the information of Section 3 will disappear from the table.
-------------------------------------------------------------------------------------------------------------------------------
2
Asmaa Hani
AL Qurna Technical Institute
Computer Systems Department
SQL DataBase Basics
-------------------------------------------------------------------------------------------------------------------------------
Functional Dependency (FD)
Functional Dependency (FD): s the adoption of one attributes on the value of
another attribute(s). symbol
A
B
 It means that B is functionally dependent on A, and we can say here that the value
of A determines the value of B. and that A only returns one value for B.

FD1 : Empno
Ename

FD2 : Empno
Deptno
Any employee's name can be known from his number as well as the department.
Inference Rules
Inference Rules is a set of rules that are used in the process of identifying the
functional dependency.
1. Reflexive Rule : If y is a part of x , then x defines y.
X
Ↄ Y:X
Y
2. Add Rule: If x defines y then adding z to x means that z can be added to y.
{X
Y}
|= XZ
YZ
Empno
Deptn
Empno,Dname
Deptno,Dname
-------------------------------------------------------------------------------------------------------------------------------
3
Asmaa Hani
AL Qurna Technical Institute
Computer Systems Department
SQL DataBase Basics
-------------------------------------------------------------------------------------------------------------------------------
3. Transitive Rule: If x defines y and y defines z then x defines z.
{X
Z}
Y,Y
|= X
Z
Book
Author
Author
Author_address
Book
Auth_Ad
4. Union Rule: If x defines y and x defines z then x defines yz.
{X
Z} |= X
Y,X
Empno
YZ
Ename
Empno
Gender
Empno
Ename,Gender
5. Decomposition Rule: It is the opposite of the union rule, if x defines yz then x
defines y and defines z.
{X
YZ } |= X
Y,X
Empno
Z
Ename,Gender
Empno
Ename
Empno
Gender
-------------------------------------------------------------------------------------------------------------------------------
4
Asmaa Hani
AL Qurna Technical Institute
Computer Systems Department
SQL DataBase Basics
-------------------------------------------------------------------------------------------------------------------------------
(Unnormalized Form UNF)
It is the relationship that contains a repeated set of data, that is, the presence of more
than one graphic value inside the cell.
-------------------------------------------------------------------------------------------------------------------------------
5
Asmaa Hani
AL Qurna Technical Institute
Computer Systems Department
SQL DataBase Basics
-------------------------------------------------------------------------------------------------------------------------------
) First Normal Form 1NF(
The table will be in the 1NF if all table columns contain simple data (Atomic), that is, any
intersection of column with row gives only one value.
Example: name (divided into first name, second name, last name), address (divided into city,
street, house number) and each one in a separate column.
 That is, in 1NF there are two basic rules:
1- That there should not be a multi-valued adjective: that is, there should be more than one
statement within the column.
2- That there is no compound adjective: meaning that the column is divided into two or
more parts.
-------------------------------------------------------------------------------------------------------------------------------
6
Asmaa Hani
AL Qurna Technical Institute
Computer Systems Department
SQL DataBase Basics
-------------------------------------------------------------------------------------------------------------------------------
Example 1: In the following table the customer information, and we note that the name
contains three graphic values as well as the address, so we cannot store only one value in
the name or address column.
Example 2: The following table represents a record of the hours worked for an employee on a
number of projects and for the department supervising the implementation of the project.
-------------------------------------------------------------------------------------------------------------------------------
7
Asmaa Hani
AL Qurna Technical Institute
Computer Systems Department
SQL DataBase Basics
-------------------------------------------------------------------------------------------------------------------------------
 But there is a problem in this table, which is finding the master key, as the employee's
number is no longer fit to be a PK master key, because one of its conditions is nonrepetition.
 We will now use the functional dependency FD to try to find the master key of the table:
FD1 : Eno
Ename
As the number determines the name, and each employee has one number. We cannot say that
the name determines the number because there are similar names.
FD2 : Proj_code
Deptno
-------------------------------------------------------------------------------------------------------------------------------
8
Asmaa Hani
AL Qurna Technical Institute
Computer Systems Department
SQL DataBase Basics
-------------------------------------------------------------------------------------------------------------------------------
As each project has one department that is supervised by it.
FD3 : Deptno
Dname
In this case, we must make a new attempt to find the PK master key through a compound key of
more than one attribute.
• We associate the employee number with the project code.
FD4 : Eno, Proj_code
Ename
FD5 : Eno, Proj_code
Deptno
FD6 : Eno, Proj_code
Hours
FD7 : Deptno
Dname
FD8 : Eno, Proj_code
Ename
-------------------------------------------------------------------------------------------------------------------------------
9
Asmaa Hani
AL Qurna Technical Institute
Computer Systems Department
SQL DataBase Basics
-------------------------------------------------------------------------------------------------------------------------------
)Second Normal Form 2NF)
• In the second standard form, it is not useful to have an attribute that is partially
functionally dependent on the master key.
• But it must be a full functional accreditation, as in the case of grades, as it depends on
the composite key (student number + subject number).
•
In the case of the student's name, the name of the course is a partial job accreditation.
• The solution in this case is to add a new table for each attribute with the master key fully
functionally dependent on it. The attributes are removed from the base table.
1. We create a new table with the main key + the attribute dependent on it with full
functional dependency.
2. We delete the adjective from the base table.
Sno
St_name
-------------------------------------------------------------------------------------------------------------------------------
10
Asmaa Hani
AL Qurna Technical Institute
Computer Systems Department
SQL DataBase Basics
-------------------------------------------------------------------------------------------------------------------------------
Cno
Course
Now is the following table in the second standard form2NF?
-------------------------------------------------------------------------------------------------------------------------------
11
Asmaa Hani
AL Qurna Technical Institute
Computer Systems Department
SQL DataBase Basics
-------------------------------------------------------------------------------------------------------------------------------
To answer this, we answer the following two questions:
1- Is the table in 1NF?
Yes, because there are no repeating values, each column contains only one value.
2-Is there partial reliability?
To find out, we must define functional reliability.
FD1 : Eno
FD2 : Proj_code
FD3 : Eno, Proj_code
•
Ename
Deptno, Dname
Ename, Deptno, Hours
The main key of the table is Eno, Proj_code but Eno define Ename So there is partial
dependency.
• Proj_code also specifies Deptno, Dname and this is another partial dependency.
• To get rid of this problem, we must divide the table into tables so that each of them
includes the part of the key and the columns that depend on it, and we keep only the
compound key with the columns that depend on it.
1- We move the employee name and number to a new table and keep a copy of the
employee number in the original table (because it is part of the master key).
2- We move the project code, department number and department name to a new table
and keep a copy of the project code in the original table (because it is part of the master
key).
-------------------------------------------------------------------------------------------------------------------------------
12
Asmaa Hani
AL Qurna Technical Institute
Computer Systems Department
SQL DataBase Basics
-------------------------------------------------------------------------------------------------------------------------------
-------------------------------------------------------------------------------------------------------------------------------
13
Asmaa Hani
AL Qurna Technical Institute
Computer Systems Department
SQL DataBase Basics
-------------------------------------------------------------------------------------------------------------------------------
) Third Normal Form 3NF (
The table is in the third standard form if:
1. The table was in the second standard form.
2. The table did not contain transitive dependencies.
transitive dependency: is that some columns (attributes) are functionally dependent on an
attribute other than the master key.
Transitive Functional Dependency (TFD)
In the sense that there is an adjective that depends on another adjective and the other adjective
depends on the main key, in this case the adjective in the middle is an intermediate adjective.
• We note in the following table that the department number depends directly on the
master key (employee number), while the name of the department manager depends on
the department number and not on the master key.
-------------------------------------------------------------------------------------------------------------------------------
14
Asmaa Hani
AL Qurna Technical Institute
Computer Systems Department
SQL DataBase Basics
-------------------------------------------------------------------------------------------------------------------------------
Eno
Deptno
Deptno
Dept-manager
TFD
In this case the solution is:
1- We delete the approved adjective from the main table.
2 - Create a new table with the approved attribute with the intermediate attribute, and assign
the intermediate attribute a brimary key.
-------------------------------------------------------------------------------------------------------------------------------
15
Asmaa Hani
AL Qurna Technical Institute
Computer Systems Department
SQL DataBase Basics
-------------------------------------------------------------------------------------------------------------------------------
Now, are the following tables in the third standard form 3NF?
In order to answer the following questions:
1- Are the tables in the second standard form 2NF?
• Yes, because there is no partial reliability.
2-Is there transitive reliability?
• To know this, the functional dependency of each table must be determined:
• First table:
FD1 : Eno
Ename
There is no transitive reliability.
• Second table:
FD2 : Eno, Proj_code
Hours
There is no transitive reliability.
-------------------------------------------------------------------------------------------------------------------------------
16
Asmaa Hani
AL Qurna Technical Institute
Computer Systems Department
SQL DataBase Basics
-------------------------------------------------------------------------------------------------------------------------------
•Third table:
FD1 : Proj_code
FD2 : Deptno
Deptno, Dname
Dname
• The brimary key Proj_code specifies Deptno, Dname and at the same time Deptno specifies
Dname ie there is a transitive dependency.
To get rid of this problem, we divide the table into tables so that each of them includes columns
that depend on each other, and we keep the key with the columns that depend on it alone,
while keeping the new delimiter Deptno.
That is, we move the section number and name to a new table and keep a copy of the section
number in the table.
-------------------------------------------------------------------------------------------------------------------------------
17
Asmaa Hani
AL Qurna Technical Institute
Computer Systems Department
SQL DataBase Basics
-------------------------------------------------------------------------------------------------------------------------------
chapter Three To Four
SQL Server Data Types
Character string:
Data type
Description
Storage
char(n)
Fixed-length character string. Maximum 8,000 characters
n
varchar(n)
Variable-length character string. Maximum 8,000 characters
varchar(max)
Variable-length character string. Maximum 1,073,741,824
characters
text
Variable-length character string. Maximum 2GB of text data
Unicode strings:
Data type
Description
Storage
nchar(n)
Fixed-length Unicode data. Maximum 4,000 characters
nvarchar(n)
Variable-length Unicode data. Maximum 4,000 characters
nvarchar(max)
Variable-length Unicode data. Maximum 536,870,912 characters
ntext
Variable-length Unicode data. Maximum 2GB of text data
Binary types:
Data type
Description
Storage
bit
Allows 0, 1, or NULL
binary(n)
Fixed-length binary data. Maximum 8,000 bytes
varbinary(n)
Variable-length binary data. Maximum 8,000 bytes
varbinary(max)
Variable-length binary data. Maximum 2GB
image
Variable-length binary data. Maximum 2GB
1
Asmaa Hani Ashoor
AL Qurna Technical Institute
Computer Systems Department
SQL DataBase Basics
------------------------------------------------------------------------------------------------------------------------------Data type
Description
Storag
e
tinyint
Allows whole numbers from 0 to 255
1 byte
smallint
Allows whole numbers between -32,768 and 32,767
2 bytes
int
Allows whole numbers between -2,147,483,648 and
2,147,483,647
4 bytes
bigint
Allows whole numbers between -9,223,372,036,854,775,808 and 8 bytes
9,223,372,036,854,775,807
decimal(p,s)
Fixed precision and scale numbers.
5-17
Allows numbers from -10^38 +1 to 10^38 –1.
bytes
The p parameter indicates the maximum total number of digits
that can be stored (both to the left and to the right of the decimal
point). p must be a value from 1 to 38. Default is 18.
The s parameter indicates the maximum number of digits stored
Number types:
numeric(p,s)
Fixed precision and scale numbers.
5-17
Allows numbers from -10^38 +1 to 10^38 –1.
bytes
The p parameter indicates the maximum total number of digits
that can be stored (both to the left and to the right of the decimal
point). p must be a value from 1 to 38. Default is 18.
The s parameter indicates the maximum number of digits stored
to the right of the decimal point. s must be a value from 0 to p.
Default value is 0
smallmoney
Monetary data from -214,748.3648 to 214,748.3647
4 bytes
money
Monetary data from -922,337,203,685,477.5808 to
922,337,203,685,477.5807
8 bytes
float
Floating precision number data from -1.79E + 308 to 1.79E +
308.
4 bytes
real
Floating precision number data from -3.40E + 38 to 3.40E + 38
4 bytes
----------------------------------------------------------------------------------------------------------------- --------------
2
Asmaa Hani Ashoor
AL Qurna Technical Institute
Computer Systems Department
SQL DataBase Basics
-------------------------------------------------------------------------------------------------------------------------------
Date types:
Data type
Description
Storage
datetime
From January 1, 1753 to December 31, 9999 with an accuracy of
3.33 milliseconds
8 bytes
datetime2
From January 1, 0001 to December 31, 9999 with an accuracy of
100 nanoseconds
6-8
bytes
smalldatetime
From January 1, 1900 to June 6, 2079 with an accuracy of 1
minute
4 bytes
date
Store a date only. From January 1, 0001 to December 31, 9999
3 bytes
time
Store a time only to an accuracy of 100 nanoseconds
3-5
bytes
datetimeoffset
The same as datetime2 with the addition of a time zone offset
8-10
bytes
timestamp
Stores a unique number that gets updated every time a row gets
created or modified. The timestamp value is based upon an
internal clock and does not correspond to real time. Each table
may have only one timestamp variable
Other data types:
Data type
Description
sql_variant
Stores up to 8,000 bytes of data of various data types, except text, ntext,
and timestamp
uniqueidentifier
Stores a globally unique identifier (GUID)
xml
Stores XML formatted data. Maximum 2GB
----------------------------------------------------------------------------------------------------------------- --------------
3
Asmaa Hani Ashoor
AL Qurna Technical Institute
Computer Systems Department
SQL DataBase Basics
-------------------------------------------------------------------------------------------------------------------------------
Create database using wizard
To create the database through the wizard, right-click on the database, a list appears,
from which we choose a new database
----------------------------------------------------------------------------------------------------------------- --------------
4
Asmaa Hani Ashoor
AL Qurna Technical Institute
Computer Systems Department
SQL DataBase Basics
-------------------------------------------------------------------------------------------------------------------------------
Create a table using the wizard
Open the database that you created, right-click on the selection table, a menu appears,
choose a table from it.
----------------------------------------------------------------------------------------------------------------- --------------
5
Asmaa Hani Ashoor
AL Qurna Technical Institute
Computer Systems Department
SQL DataBase Basics
-------------------------------------------------------------------------------------------------------------------------------
After that, the table design interface appears, which contains the column name and the
graph type, Add columns and select the graphic type for each column.
----------------------------------------------------------------------------------------------------------------- --------------
6
Asmaa Hani Ashoor
AL Qurna Technical Institute
Computer Systems Department
SQL DataBase Basics
-------------------------------------------------------------------------------------------------------------------------------
To add data to the table, right-click on the table name, after saving it, a menu appears,
choose from it edit top 200 rows.
To see the result, press (F5) or (Ctrl+ R) or the execution tool (!) in the toolbar.
----------------------------------------------------------------------------------------------------------------- --------------
7
Asmaa Hani Ashoor
AL Qurna Technical Institute
Computer Systems Department
SQL DataBase Basics
-------------------------------------------------------------------------------------------------------------------------------
SQL Create Database Statement
The create database statement is used to create a database.
SQL Create database Syntax
create database database_name
Create Database Example
Now we want to create a database called "my_db". We
use the following create database statement:
create a database my_db
SQL Create Table Statement
The Create Table statement is used to create a table in a database.
SQL Create Table Syntax:
Create table table_name (
column_name1 data_type,
column_name2 data_type,
column_name3 data_type,
....
)
----------------------------------------------------------------------------------------------------------------- --------------
8
Asmaa Hani Ashoor
AL Qurna Technical Institute
Computer Systems Department
SQL DataBase Basics
-------------------------------------------------------------------------------------------------------------------------------
Now we want to create a table called "Persons" that contains five columns: P_Id, LastName,
FirstName, Address, and City.
We use the following CREATE TABLE statement:
Create table Persons (
P_Id int,
LastName varchar(255),
FirstName varchar(255),
Address varchar(255),
City varchar(255)
)
The P_Id column is of type int and will hold a number. The LastName, FirstName, Address,
and City columns are of type varchar with a maximum length of 255 characters.
The empty "Persons" table will now look like this:
P_Id
LastName
FirstName
Address
City
the empty table can be filled with data with the INSERT INTO statement.
----------------------------------------------------------------------------------------------------------------- --------------
9
Asmaa Hani Ashoor
AL Qurna Technical Institute
Computer Systems Department
SQL DataBase Basics
-------------------------------------------------------------------------------------------------------------------------------
SQL NOT NULL Constraint
By default, a table column can hold NULL values.
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.
The following SQL enforces the "P_Id" column and the "LastName" column to not accept NULL
values:
CREATE TABLE Persons (
P_Id int NOT NULL,
LastName varchar(255) NOT NULL,
FirstName varchar(255),
Address varchar(255), City
varchar(255)
)
----------------------------------------------------------------------------------------------------------------- --------------
10
Asmaa Hani Ashoor
AL Qurna Technical Institute
Computer Systems Department
SQL DataBase Basics
-------------------------------------------------------------------------------------------------------------------------------
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 must have only one primary key.
CREATE TABLE Persons (
P_Id int NOT NULL PRIMARY KEY,
LastName varchar(255) NOT NULL,
FirstName varchar(255),
Address varchar(255),
City varchar(255)
)
SQL INSERT INTO Statement
The INSERT INTO statement is used to insert new records in a table.
SQL INSERT INTO Syntax:
It is possible to write the INSERT INTO statement in two forms.
The first form doesn't specify the column names where the data will be inserted, only their values.
INSERT INTO table_name
VALUES (value1, value2, value3,...)
----------------------------------------------------------------------------------------------------------------- --------------
11
Asmaa Hani Ashoor
AL Qurna Technical Institute
Computer Systems Department
SQL DataBase Basics
-------------------------------------------------------------------------------------------------------------------------------
The second form specifies both the column names and the values to be inserted:
INSERT INTO table_name (column1, column2, column3,...) VALUES
(value1, value2, value3,...)
SQL INSERT INTO Example
We have the following "Persons" table:
P_Id
LastName
FirstName
Address
City
1
Hansen
Ola
Timoteivn 10
Sandnes
2
Svendson
Tove
Borgvn 23
Sandnes
3
Pettersen
Kari
Storgt 20
Stavanger
Now we want to insert a new row in the "Persons" table.
We use the following SQL statement:
INSERT INTO Persons
VALUES (4,'Nilsen', 'Johan', 'Bakken 2', 'Stavanger')
The "Persons" table will now look like this:
P_Id
LastName
FirstName
Address
City
1
Hansen
Ola
Timoteivn 10
Sandnes
2
Svendson
Tove
Borgvn 23
Sandnes
3
Pettersen
Kari
Storgt 20
Stavanger
4
Nilsen
Johan
Bakken 2
Stavanger
----------------------------------------------------------------------------------------------------------------- --------------
12
Asmaa Hani Ashoor
AL Qurna Technical Institute
Computer Systems Department
SQL DataBase Basics
-------------------------------------------------------------------------------------------------------------------------------
Insert Data Only in Specified Columns
It is also possible to only add data in specific columns.
The following SQL statement will add a new row, but only add data in the "P_Id", "LastName"
and the "FirstName" columns:
INSERT INTO Persons (P_Id, LastName, FirstName)
VALUES (5, 'Tjessem', 'Jakob')
The "Persons" table will now look like this:
P_Id
LastName
FirstName
Address
City
1
Hansen
Ola
Timoteivn 10
Sandnes
2
Svendson
Tove
Borgvn 23
Sandnes
3
Pettersen
Kari
Storgt 20
Stavanger
4
Nilsen
Johan
Bakken 2
Stavanger
5
Tjessem
Jakob
----------------------------------------------------------------------------------------------------------------- --------------
13
Asmaa Hani Ashoor
AL Qurna Technical Institute
Computer Systems Department
SQL DataBase Basics
-------------------------------------------------------------------------------------------------------------------------------
chapter Five To Six
The SQL SELECT Statement
The SELECT statement is used to select data from a database.
The result is stored in a result table, called the result-set.
SQL SELECT Syntax
SELECT column_name(s)
FROM table_name
and
SELECT * FROM table_name
Note : SQL is not case sensitive. SELECT is the same as select.
An SQL SELECT Example
The "Persons" table:
P_Id
LastName
FirstName
Address
City
1
Hansen
Ola
Timoteivn 10
Sandnes
2
Svendson
Tove
Borgvn 23
Sandnes
3
Pettersen
Kari
Storgt 20
Stavanger
----------------------------------------------------------------------------------------------- --------------------------------
1
Asmaa Hani Ashoor
AL Qurna Technical Institute
Computer Systems Department
SQL DataBase Basics
----------------------------------------------------------------------------------------------- --------------------------------
Now we want to select the content of the columns named "LastName" and "FirstName" from the table
above.We SELECT statement:use the following
SELECT LastName,FirstName FROM Persons
The result-set will look like this:
LastName
FirstName
Hansen
Ola
Svendson
Tove
Pettersen
Kari
SELECT * Example
Now we want to select all the columns from the "Persons" table. We use the following SELECT statement
SELECT * FROM Persons
Tip:The asterisk (*) is a quick way of selecting all columns.
The result-set will look like this:
P_Id
LastName
FirstName
Address
City
1
Hansen
Ola
Timoteivn 10
Sandnes
2
Svendson
Tove
Borgvn 23
Sandnes
3
Pettersen
Kari
Storgt 20
Stavanger
-------------------------------------------------------------------------------------------------------------------------------
2
Asmaa Hani Ashoor
AL Qurna Technical Institute
Computer Systems Department
SQL DataBase Basics
----------------------------------------------------------------------------------------------- --------------------------------
SQL SELECT DISTINCT Statement
In a table, some of the columns may contain duplicate values. This is not a problem, however, sometimes you
will want to list only the different (distinct) values in a table.
The DISTINCT keyword can be used to return only distinct (different) values.
SQL SELECT DISTINCT Syntax
SELECT DISTINCT column_name(s)
FROM table_name
SELECT DISTINCT Example
The "Persons" table:
P_Id
LastName
FirstName
Address
City
1
Hansen
Ola
Timoteivn 10
Sandnes
2
Svendson
Tove
Borgvn 23
Sandnes
3
Pettersen
Kari
Storgt 20
Stavanger
Now we want to select only the distinct values from the column named "City" from the table above.
We use the following SELECT statement:
SELECT DISTINCT City FROM Persons
-------------------------------------------------------------------------------------------------------------------------------
3
Asmaa Hani Ashoor
AL Qurna Technical Institute
Computer Systems Department
SQL DataBase Basics
----------------------------------------------------------------------------------------------- --------------------------------
The result-set will look like this:
City
Sandnes
Stavanger
SQL WHERE Clause
The WHERE clause is used to filter records.
The WHERE clause is used to extract only those records that fulfill a specified criterion.
SQL WHERE Syntax
SELECT column_name(s)
FROM table_name
WHERE column_name operator value
WHERE Clause Example
The "Persons" table:
P_Id
LastName
FirstName
Address
City
1
Hansen
Ola
Timoteivn 10
Sandnes
2
Svendson
Tove
Borgvn 23
Sandnes
3
Pettersen
Kari
Storgt 20
Stavanger
-------------------------------------------------------------------------------------------------------------------------------
4
Asmaa Hani Ashoor
AL Qurna Technical Institute
Computer Systems Department
SQL DataBase Basics
----------------------------------------------------------------------------------------------- --------------------------------
Now we want to select only the persons living in the city "Sandnes" from the table above. We use the
following SELECT statement:
SELECT * FROM Persons
WHERE City='Sandnes'
The result-set will look like this:
P_Id
LastName
FirstName
Address
City
1
Hansen
Ola
Timoteivn 10
Sandnes
2
Svendson
Tove
Borgvn 23
Sandnes
SQL AND & OR Operators
The AND & OR operators are used to filter records based on more than one condition.
The AND operator displays a record if both the first condition and the second condition is true. The OR
operator displays a record if either the first condition or the second condition is true.
AND Operator Example
The "Persons" table:
P_Id
LastName
FirstName
Address
City
1
Hansen
Ola
Timoteivn 10
Sandnes
2
Svendson
Tove
Borgvn 23
Sandnes
3
Pettersen
Kari
Storgt 20
Stavanger
-------------------------------------------------------------------------------------------------------------------------------
5
Asmaa Hani Ashoor
AL Qurna Technical Institute
Computer Systems Department
SQL DataBase Basics
----------------------------------------------------------------------------------------------- --------------------------------
Now we want to select only the persons with the first name equal to "Tove" AND the last name equal to
"Svendson":
We use the following SELECT statement:
SELECT * FROM Persons
WHERE FirstName='Tove'
AND LastName='Svendson'
The result-set will look like this:
P_Id
LastName
FirstName
Address
City
2
Svendson
Tove
Borgvn 23
Sandnes
OR Operator Example
Now we want to select only the persons with the first name equal to "Tove" OR the first name equal to "Ola":
We use the following SELECT statement:
SELECT * FROM Persons
WHERE FirstName='Tove' OR
FirstName='Ola'
The result-set will look like this:
P_Id
LastName
FirstName
Address
City
1
Hansen
Ola
Timoteivn 10
Sandnes
2
Svendson
Tove
Borgvn 23
Sandnes
-------------------------------------------------------------------------------------------------------------------------------
6
Asmaa Hani Ashoor
AL Qurna Technical Institute
Computer Systems Department
SQL DataBase Basics
----------------------------------------------------------------------------------------------- --------------------------------
SQL UPDATE Statement
The UPDATE statement is used to update records in a table.
SQL UPDATE Syntax
UPDATE table_name
SET column1=value, column2=value2,... WHERE
some_column=some_value
Note: Notice the WHERE clause in the UPDATE syntax. The WHERE clause specifies which
record or records that should be updated. If you omit the WHERE clause, all records will be updated.
SQL UPDATE Example
The "Persons" table:
P_Id
LastName
FirstName
Address
City
1
Hansen
Ola
Timoteivn 10
Sandnes
2
Svendson
Tove
Borgvn 23
Sandnes
3
Pettersen
Kari
Storgt 20
Stavanger
4
Nilsen
Johan
Bakken 2
Stavanger
5
Tjessem
Jakob
Now we want to update the person "Tjessem, Jakob" in the "Persons" table. We use the
following SQL statement:
UPDATE Persons
SET Address='Nissestien 67', City='Sandnes' WHERE
LastName='Tjessem' AND FirstName='Jakob'
-------------------------------------------------------------------------------------------------------------------------------
7
Asmaa Hani Ashoor
AL Qurna Technical Institute
Computer Systems Department
SQL DataBase Basics
----------------------------------------------------------------------------------------------- --------------------------------
The "Persons" table will now look like this:
P_Id
LastName
FirstName
Address
City
1
Hansen
Ola
Timoteivn 10
Sandnes
2
Svendson
Tove
Borgvn 23
Sandnes
3
Pettersen
Kari
Storgt 20
Stavanger
4
Nilsen
Johan
Bakken 2
Stavanger
5
Tjessem
Jakob
Nissestien 67
Sandnes
SQL UPDATE Warning
Be careful when updating records. If we had omitted the WHERE clause in the example above, like this:
UPDATE Persons
SET Address='Nissestien 67', City='Sandnes'
The "Persons" table would have looked like this:
P_Id
LastName
FirstName
Address
City
1
Hansen
Ola
Nissestien 67
Sandnes
2
Svendson
Tove
Nissestien 67
Sandnes
3
Pettersen
Kari
Nissestien 67
Sandnes
4
Nilsen
Johan
Nissestien 67
Sandnes
5
Tjessem
Jakob
Nissestien 67
Sandnes
-------------------------------------------------------------------------------------------------------------------------------
8
Asmaa Hani Ashoor
AL Qurna Technical Institute
Computer Systems Department
SQL DataBase Basics
---------------------------------------------------------------------- ---------------------------------------------------------
chapter Seven
SQL LIKE Operator
The LIKE operator is used in a WHERE clause to search for a specified pattern in a column.
SQL LIKE Syntax.
SELECT column_name(s)
FROM table_name
WHERE column_name LIKE pattern
LIKE Operator Example
The "Persons" table:
P_Id
LastName
FirstName
Address
City
1
Hansen
Ola
Timoteivn 10
Sandnes
2
Svendson
Tove
Borgvn 23
Sandnes
3
Pettersen
Kari
Storgt 20
Stavanger
Now we want to select the persons living in a city that starts with "s" from the table above.
We use the following SELECT statement
SELECT * FROM Persons
WHERE City LIKE 's%'
-------------------------------------------------------------------------------------------------------------------------------
1
Asmaa Hani Ashoor
AL Qurna Technical Institute
Computer Systems Department
SQL DataBase Basics
-------------------------------------------------------------------------------------------------------------------------------
The "%" sign can be used to define wildcards (missing letters in the pattern) both before and
after the pattern.
The result-set will look like this:
P_Id
LastName
FirstName
Address
City
1
Hansen
Ola
Timoteivn 10
Sandnes
2
Svendson
Tove
Borgvn 23
Sandnes
3
Pettersen
Kari
Storgt 20
Stavanger
Next, we want to select the persons living in a city that ends with an "s" from the "Persons" table.
We use the following SELECT statement:
SELECT * FROM Persons
WHERE City LIKE '%s'
The result-set will look like this:
P_Id
LastName
FirstName
Address
City
1
Hansen
Ola
Timoteivn 10
Sandnes
2
Svendson
Tove
Borgvn 23
Sandnes
Next, we want to select the persons living in a city that contains the pattern "tav" from the "Persons" table.
We use the following SELECT statement:
SELECT * FROM Persons
WHERE City LIKE '%tav%'
The result-set will look like this:
P_Id
LastName
FirstName
Address
City
3
Pettersen
Kari
Storgt 20
Stavanger
-------------------------------------------------------------------------------------------------------------------------------
2
Asmaa Hani Ashoor
AL Qurna Technical Institute
Computer Systems Department
SQL DataBase Basics
-------------------------------------------------------------------------------------------------------------------------------
It is also possible to select the persons living in a city that NOT contains the pattern "tav" from the "Persons"
table, by using the NOT keyword.
We use the following SELECT statement:
SELECT * FROM Persons
WHERE City NOT LIKE '%tav%'
The result-set will look like this:
P_Id
LastName
FirstName
Address
City
1
Hansen
Ola
Timoteivn 10
Sandnes
2
Svendson
Tove
Borgvn 23
Sandnes
SQL Wildcards
SQL wildcards can substitute for one or more characters when searching for data in adatabase.
SQL wildcards must be used with the SQL LIKE operator. With
SQL, the following wildcards can be used:
Wildcard
Description
%
A substitute for zero or more characters
_
A substitute for exactly one character
[charlist]
Any single character in charlist
[^charlist]
or
[!charlist]
Any single character not in charlist
-------------------------------------------------------------------------------------------------------------------------------
3
Asmaa Hani Ashoor
AL Qurna Technical Institute
Computer Systems Department
SQL DataBase Basics
-------------------------------------------------------------------------------------------------------------------------------
SQL Wildcard Examples
We have the following "Persons" table:
P_Id
LastName
FirstName
Address
City
1
Hansen
Ola
Timoteivn 10
Sandnes
2
Svendson
Tove
Borgvn 23
Sandnes
3
Pettersen
Kari
Storgt 20
Stavanger
Using the % Wildcard
Now we want to select the persons living in a city that starts with "sa" from the "Persons" table.
We use the following SELECT statement:
SELECT * FROM Persons
WHERE City LIKE 'sa%'
The result-set will look like this:
P_Id
LastName
FirstName
Address
City
1
Hansen
Ola
Timoteivn 10
Sandnes
2
Svendson
Tove
Borgvn 23
Sandnes
Next, we want to select the persons living in a city that contains the pattern "nes" from the "Persons" table.
We use the following SELECT statement:
SELECT * FROM Persons
WHERE City LIKE '%nes%'
-------------------------------------------------------------------------------------------------------------------------------
4
Asmaa Hani Ashoor
AL Qurna Technical Institute
Computer Systems Department
SQL DataBase Basics
-------------------------------------------------------------------------------------------------------------------------------
The result-set will look like this:
P_Id
LastName
FirstName
Address
City
1
Hansen
Ola
Timoteivn 10
Sandnes
2
Svendson
Tove
Borgvn 23
Sandnes
Using the _ Wildcard
Now we want to select the persons with a first name that starts with any character, followed by "la"
from the "Persons" table.
We use the following SELECT statement
SELECT * FROM Persons WHERE
FirstName LIKE '_la'
The result-set will look like this:
P_Id
LastName
FirstName
Address
City
1
Hansen
Ola
Timoteivn 10
Sandnes
Next, we want to select the persons with a last name that starts with "S", followed by any character,
followed by "end", followed by any character, followed by "on" from the "Persons" table.
We use the following SELECT statement:
SELECT * FROM Persons
WHERE LastName LIKE 'S_end_on'
-------------------------------------------------------------------------------------------------------------------------------
5
Asmaa Hani Ashoor
AL Qurna Technical Institute
Computer Systems Department
SQL DataBase Basics
-------------------------------------------------------------------------------------------------------------------------------
The result-set will look like this:
P_Id
LastName
FirstName
Address
City
2
Svendson
Tove
Borgvn 23
Sandnes
Using the [charlist] Wildcard
Now we want to select the persons with a last name that starts with "b" or "s" or "p" from the "Persons"
table.
We use the following SELECT statement:
SELECT * FROM Persons
WHERE LastName LIKE '[bsp]%'
The result-set will look like this:
P_Id
LastName
FirstName
Address
City
2
Svendson
Tove
Borgvn 23
Sandnes
3
Pettersen
Kari
Storgt 20
Stavanger
Next, we want to select the persons with a last name that do not start with "b" or "s" or "p" from the
"Persons" table.
We use the following SELECT statement:
SELECT * FROM Persons
WHERE LastName LIKE '[!bsp]%'
The result-set will look like this:
P_Id
LastName
FirstName
Address
City
1
Hansen
Ola
Timoteivn 10
Sandnes
-------------------------------------------------------------------------------------------------------------------------------
6
Asmaa Hani Ashoor
AL Qurna Technical Institute
Computer Systems Department
SQL DataBase Basics
-------------------------------------------------------------------------------------------------------------------------------
SQL IN Operator
The IN operator allows you to specify multiple values in a WHERE clause.
SQL IN Syntax
SELECT column_name(s)
FROM table_name
WHERE column_name IN (value1,value2,...)
IN Operator Example
The "Persons" table:
P_Id
LastName
FirstName
Address
City
1
Hansen
Ola
Timoteivn 10
Sandnes
2
Svendson
Tove
Borgvn 23
Sandnes
3
Pettersen
Kari
Storgt 20
Stavanger
Now we want to select the persons with a last name equal to "Hansen" or "Pettersen" from the table
above.
We use the following SELECT statement:
SELECT * FROM Persons
WHERE LastName IN ('Hansen','Pettersen')
-------------------------------------------------------------------------------------------------------------------------------
7
Asmaa Hani Ashoor
AL Qurna Technical Institute
Computer Systems Department
SQL DataBase Basics
-------------------------------------------------------------------------------------------------------------------------------
The result-set will look like this:
P_Id
LastName
FirstName
Address
City
1
Hansen
Ola
Timoteivn 10
Sandnes
3
Pettersen
Kari
Storgt 20
Stavanger
SQL BETWEEN Operator
The BETWEEN operator is used in a WHERE clause to select a range of data between two values.
The BETWEEN operator selects a range of data between two values. The values can be numbers, text, or
dates.
SQL BETWEEN Syntax
SELECT column_name(s)
FROM table_name
WHERE column_name
BETWEEN value1 AND value2
BETWEEN Operator Example
The "Persons" table:
P_Id
LastName
FirstName
Address
City
1
Hansen
Ola
Timoteivn 10
Sandnes
2
Svendson
Tove
Borgvn 23
Sandnes
3
Pettersen
Kari
Storgt 20
Stavanger
-------------------------------------------------------------------------------------------------------------------------------
8
Asmaa Hani Ashoor
AL Qurna Technical Institute
Computer Systems Department
SQL DataBase Basics
-------------------------------------------------------------------------------------------------------------------------------
Now we want to select the persons with a last name alphabetically between "Hansen" and "Pettersen" from
the table above.
We use the following SELECT statement:
SELECT * FROM Persons
WHERE LastName
BETWEEN 'Hansen' AND 'Pettersen'
The result-set will look like this:
P_Id
LastName
FirstName
Address
City
1
Hansen
Ola
Timoteivn 10
Sandnes
2
Pettersen
Kari
Storgt 20
Stavanger
Example 2
To display the persons outside the range in the previous example, use NOT BETWEEN:
SELECT * FROM Persons
WHERE LastName
NOT BETWEEN 'Hansen' AND 'Pettersen'
The result-set will look like this:
P_Id
LastName
FirstName
Address
City
2
Svendson
Tove
Borgvn 23
Sandnes
-------------------------------------------------------------------------------------------------------------------------------
9
Asmaa Hani Ashoor
AL Qurna Technical Institute
Computer Systems Department
SQL DataBase Basics
-------------------------------------------------------------------------------------------------------------------------------
SQL ALTER TABLE Statement
The ALTER TABLE statement is used to add, delete, or modify columns in an existing table.
SQL ALTER TABLE Syntax
To add a column in a table, use the following syntax:
ALTER TABLE table_name ADD
column_name datatype
To delete a column in a table, use the following syntax (notice that some database systems
don't allow deleting a column):
ALTER TABLE table_name DROP
COLUMN column_name
To change the data type of a column in a table, use the following syntax:
ALTER TABLE table_name
ALTER COLUMN column_name datatype
-------------------------------------------------------------------------------------------------------------------------------
10
Asmaa Hani Ashoor
AL Qurna Technical Institute
Computer Systems Department
SQL DataBase Basics
-------------------------------------------------------------------------------------------------------------------------------
SQL ALTER TABLE Example
Look at the "Persons" table:
P_Id
LastName
FirstName
Address
City
1
Hansen
Ola
Timoteivn 10
Sandnes
2
Svendson
Tove
Borgvn 23
Sandnes
3
Pettersen
Kari
Storgt 20
Stavanger
Now we want to add a column named "DateOfBirth" in the "Persons" table. We use the
following SQL statement:
ALTER TABLE PersonsADD
DateOfBirth date
The "Persons" table will now like this:
P_Id
LastName
FirstName
Address
City
1
Hansen
Ola
Timoteivn 10
Sandnes
2
Svendson
Tove
Borgvn 23
Sandnes
3
Pettersen
Kari
Storgt 20
Stavanger
DateOfBirth
-------------------------------------------------------------------------------------------------------------------------------
11
Asmaa Hani Ashoor
AL Qurna Technical Institute
Computer Systems Department
SQL DataBase Basics
-------------------------------------------------------------------------------------------------------------------------------
Change Data Type Example
Now we want to change the data type of the column named "DateOfBirth" in the "Persons" table.
We use the following SQL statement:
ALTER TABLE Persons
ALTER COLUMN DateOfBirth datetime
DROP COLUMN Example
Next, we want to delete the column named "DateOfBirth" in the "Persons" table. We use
the following SQL statement:
ALTER TABLE Persons DROP
COLUMN DateOfBirth
The "Persons" table will now like this:
P_Id
LastName
FirstName
Address
City
1
Hansen
Ola
Timoteivn 10
Sandnes
2
Svendson
Tove
Borgvn 23
Sandnes
3
Pettersen
Kari
Storgt 20
Stavanger
-------------------------------------------------------------------------------------------------------------------------------
12
Asmaa Hani Ashoor
AL Qurna Technical Institute
Computer Systems Department
SQL DataBase Basics
-------------------------------------------------------------------------------------------------------------------------------
chapter Eight
Data Manipulation Language
 It is a language used for selecting, inserting, deleting and updating data in a database.
 It is used to retrieve and manipulate data in a relational database.
DML commands are as follows:
1. SELECT :to query data in the database.
2. INSERT: to insert data into a table.
3. UPDATE: to update data in a table.
In the SQL DML statement:





Each clause in a statement should begin on a new line.
The beginning of each clause should line up with the beginning of other clauses.
If a clause has several parts, they should appear on separate lines and be indented under the start of the
clause to show the relationship.
Upper case letters are used to represent reserved words.
Lower case letters are used to represent user-defined words.
-------------------------------------------------------------------------------------------------------------------------------
1
Asmaa Hani Ashoor
AL Qurna Technical Institute
Computer Systems Department
SQL DataBase Basics
-------------------------------------------------------------------------------------------------------------------------------
1. SELECT COMMAND
 SELECT command is used to retrieve data from the database.
 This command allows database users to retrieve the specific information they desire from an
operational database.
 It returns a result set of records from one or more tables.
SELECT Command has many optional clauses are as stated below:
Clause
Description
WHERE
It specifies which rows to retrieve.
GROUP BY
It is used to arrange the data into groups.
HAVING
It selects among the groups defined by the GROUP BY clause.
AS
It provides an alias which can be used to temporarily rename tables or columns.
2. INSERT COMMAND: See lecture number 3.
3. UPDATE COMMAND: See lecture number 5.
------------------------------------------------------------------------------------------------------------------------ -------
2
Asmaa Hani Ashoor
AL Qurna Technical Institute
Computer Systems Department
SQL DataBase Basics
-------------------------------------------------------------------------------------------------------------------------------
SELECT statement with GROUP BY clause
The GROUP BY clause is used to create one output row per each group and produces summary values for the
selected columns, as shown below.
SELECT type
FROM Books
GROUP BY type
If the SELECT statement includes a WHERE criterion where price is not null.
SELECT type, price
FROM Books
WHERE price is not null
then a statement with the GROUP BY clause would look like this:
SELECT type,price
FROM Books
WHERE price is not null
GROUP BY type, price
------------------------------------------------------------------------------------------------------------------------ -------
3
Asmaa Hani Ashoor
AL Qurna Technical Institute
Computer Systems Department
SQL DataBase Basics
-------------------------------------------------------------------------------------------------------------------------------
Using COUNT with GROUP BY
We can use COUNT to tally how many items are in a container. However, if we want to count different items
into separate groups, such as marbles of varying colours, then we would use the COUNT function with the
GROUP BY command.
The below SELECT statement illustrates how to count groups of data using the COUNT function with the
GROUP BY clause.
SELECT COUNT(*)
FROM Books
GROUP BY type
Using AVG and SUM with GROUP BY
We can use the AVG function to give us the average of any group, and SUM to give the total.
Example 1 : uses the AVG FUNCTION with the GROUP BY type.
SELECT AVG(qty) AS 'total'
FROM Books
GROUP BY type
------------------------------------------------------------------------------------------------------------------------ -------
4
Asmaa Hani Ashoor
AL Qurna Technical Institute
Computer Systems Department
SQL DataBase Basics
-------------------------------------------------------------------------------------------------------------------------------
Example 2: uses the SUM function with the GROUP BY type.
SELECT SUM(qty) AS 'total'
FROM Books
GROUP BY type
Example 3: uses both the AVG and SUM functions with the GROUP BY type in the SELECT statement.
SELECT ‘Total Sales’ = SUM(qty), ‘Average Sales’ = AVG(qty)
FROM Sales
GROUP BY StorID
------------------------------------------------------------------------------------------------------------------------ -------
5
Asmaa Hani Ashoor
AL Qurna Technical Institute
Computer Systems Department
SQL DataBase Basics
-------------------------------------------------------------------------------------------------------------------------------
Restricting rows with HAVING
The HAVING clause can be used to restrict rows. It is similar to the WHERE condition except HAVING can
include the aggregate function; the WHERE cannot do this.
The HAVING clause behaves like the WHERE clause, but is applicable to groups. In this example, we use the
HAVING clause to exclude the groups with the province ‘BC’.
SELECT fname AS ‘Author' ,country as ' country'
FROM Authors
GROUP BY fname, country
HAVING fname <> ‘BC’
Built-in Functions
There are many built-in functions in SQL Server such as:
1.
2.
3.
4.
5.
6.
7.
Aggregate: returns summary values.
Conversion: transforms one data type to another.
Date: displays information about dates and times.
Mathematical: performs operations on numeric data.
String: performs operations on character strings, binary data or expressions.
System: returns a special piece of information from the database.
Text and image: performs operations on text and image data.
------------------------------------------------------------------------------------------------------------------------ -------
6
Asmaa Hani Ashoor
AL Qurna Technical Institute
Computer Systems Department
SQL DataBase Basics
-------------------------------------------------------------------------------------------------------------------------------
Aggregate functions
Aggregate functions perform a calculation on a set of values and return a single, or summary,
value. Table 1.1 lists these functions.
FUNCTION
DESCRIPTION
AVG
Returns the average of all the values, or only the DISTINCT values, in the expression.
COUNT
COUNT(*)
Returns the number of non-null values in the expression. When DISTINCT is
specified, COUNT finds the number of unique non-null values.
Returns the number of rows. COUNT(*) takes no parameters and cannot be used
with DISTINCT.
MAX
Returns the maximum value in the expression. MAX can be used with numeric,
character and datetime columns, but not with bit columns. With character columns,
MAX finds the highest value in the collating sequence. MAX ignores any null values.
MIN
Returns the minimum value in the expression. MIN can be used with numeric,
character and datetime columns, but not with bit columns. With character columns,
MIN finds the value that is lowest in the sort sequence. MIN ignores any null values.
SUM
Returns the sum of all the values, or only the DISTINCT values, in the expression.
SUM can be used with numeric columns only.
Table 1.1A list of aggregate functions and descriptions
------------------------------------------------------------------------------------------------------------------------ -------
7
Asmaa Hani Ashoor
AL Qurna Technical Institute
Computer Systems Department
SQL DataBase Basics
-------------------------------------------------------------------------------------------------------------------------------
Example 1: AVG
SELECT AVG (price) AS ‘Average Title Price’
FROM Books
Example 2: COUNT
SELECT COUNT(PubID) AS ‘Number of Publishers’
FROM Publishers
Example 3: COUNT (*)
SELECT COUNT(*)
FROM Employees
WHERE job_num = 35
------------------------------------------------------------------------------------------------------------------------ -------
8
Asmaa Hani Ashoor
AL Qurna Technical Institute
Computer Systems Department
SQL DataBase Basics
-------------------------------------------------------------------------------------------------------------------------------
Example 4: MAX
SELECT MAX (age)
FROM Employees
Example 5: MIN
SELECT MIN (price)
FROM Books
Example6: SUM
SELECT SUM(age) AS ‘Total age’
FROM Employees
------------------------------------------------------------------------------------------------------------------------ -------
9
Asmaa Hani Ashoor
AL Qurna Technical Institute
Computer Systems Department
SQL DataBase Basics
-------------------------------------------------------------------------------------------------------------------------------
Chapter Nine To Ten
SQL DELETE Statement
The DELETE statement is used to delete records in a table.
SQL DELETE Syntax
DELETE FROM table_name
WHERE some_column=some_value
Note: Notice the WHERE clause in the DELETE syntax. The WHERE clause specifies which record or
records that should be deleted. If you omit the WHERE clause, all records will be deleted.
SQL DELETE Example
The "Persons" table:
P_Id
LastName
FirstName
Address
City
1
Hansen
Ola
Timoteivn 10
Sandnes
2
Svendson
Tove
Borgvn 23
Sandnes
3
Pettersen
Kari
Storgt 20
Stavanger
4
Nilsen
Johan
Bakken 2
Stavanger
5
Tjessem
Jakob
Nissestien 67
Sandnes
Now we want to delete the person "Tjessem, Jakob" in the "Persons" table. We use the
following SQL statement:
DELETE FROM Persons
WHERE LastName='Tjessem' AND FirstName='Jakob'
-------------------------------------------------------------------------------------------------------------------------------
1
Asmaa Hani Ashoor
AL Qurna Technical Institute
Computer Systems Department
SQL DataBase Basics
-------------------------------------------------------------------------------------------------------------------------------
The "Persons" table will now look like this:
P_Id
LastName
FirstName
Address
City
1
Hansen
Ola
Timoteivn 10
Sandnes
2
Svendson
Tove
Borgvn 23
Sandnes
3
Pettersen
Kari
Storgt 20
Stavanger
4
Nilsen
Johan
Bakken 2
Stavanger
Delete All Rows
It is possible to delete all rows in a table without deleting the table. This means that the table structure,
attributes, and indexes will be intact:
DELETE FROM table_name
or
DELETE * FROM table_name
-------------------------------------------------------------------------------------------------------------------------------
2
Asmaa Hani Ashoor
AL Qurna Technical Institute
Computer Systems Department
SQL DataBase Basics
-------------------------------------------------------------------------------------------------------------------------------
SQL TOP Clause
The TOP clause is used to specify the number of records to return.
The TOP clause can be very useful on large tables with thousands of records. Returning a large number of
records can impact on performance.
Note: Not all database systems support the TOP clause.
SQL Server Syntax
SELECT TOP number|percent column_name(s)
FROM table_name
SQL TOP Example
The "Persons" table:
P_Id
LastName
FirstName
Address
City
1
Hansen
Ola
Timoteivn 10
Sandnes
2
Svendson
Tove
Borgvn 23
Sandnes
3
Pettersen
Kari
Storgt 20
Stavanger
4
Nilsen
Tom
Vingvn 23
Stavanger
Now we want to select only the two first records in the table above. We use
the following SELECT statement:
SELECT TOP 2 * FROM Persons
-------------------------------------------------------------------------------------------------------------------------------
3
Asmaa Hani Ashoor
AL Qurna Technical Institute
Computer Systems Department
SQL DataBase Basics
-------------------------------------------------------------------------------------------------------------------------------
The result-set will look like this:
P_Id
LastName
FirstName
Address
City
1
Hansen
Ola
Timoteivn 10
Sandnes
2
Svendson
Tove
Borgvn 23
Sandnes
SQL TOP PERCENT Example
The "Persons" table:
P_Id
LastName
FirstName
Address
City
1
Hansen
Ola
Timoteivn 10
Sandnes
2
Svendson
Tove
Borgvn 23
Sandnes
3
Pettersen
Kari
Storgt 20
Stavanger
4
Nilsen
Tom
Vingvn 23
Stavanger
Now we want to select only 50% of the records in the table above. We use
the following SELECT statement:
SELECT TOP 50 PERCENT * FROM Persons
The result-set will look like this:
P_Id
LastName
FirstName
Address
City
1
Hansen
Ola
Timoteivn 10
Sandnes
2
Svendson
Tove
Borgvn 23
Sandnes
-------------------------------------------------------------------------------------------------------------------------------
4
Asmaa Hani Ashoor
AL Qurna Technical Institute
Computer Systems Department
SQL DataBase Basics
-------------------------------------------------------------------------------------------------------------------------------
Chapter Eleventh
Determinants
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 acolumn 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 KEYconstraint per table.
SQL UNIQUE Constraint on CREATE TABLE
The following SQL creates a UNIQUE constraint on the "P_Id" column when the "Persons" table is created:
CREATE TABLE Persons (
P_Id int NOT NULL,
LastName varchar(255) NOT NULL,
FirstName varchar(255),
Address varchar(255),
City varchar(255),
UNIQUE (P_Id)
-------------------------------------------------------------------------------------------------------------------------------
1
Asmaa Hani Ashoor
AL Qurna Technical Institute
Computer Systems Department
SQL DataBase Basics
------------------------------------------------------------------------------------------------------------ -------------------
CREATE TABLE Persons(
P_Id int NOT NULL UNIQUE,
LastName varchar(255) NOT NULL,
FirstName varchar(255),
Address varchar(255),
City varchar(255)
SQL UNIQUE Constraint on ALTER TABLE
To create a UNIQUE constraint on the "P_Id" column when the table is already created, use the
following SQL:
ALTER TABLE Persons
ADD UNIQUE (P_Id)
-------------------------------------------------------------------------------------------------------------------------------
2
Asmaa Hani Ashoor
AL Qurna Technical Institute
Computer Systems Department
SQL DataBase Basics
------------------------------------------------------------------------------------------------------------ -------------------
SQL FOREIGN KEY Constraint
A FOREIGN KEY in one table points to a PRIMARY KEY in another table. Let's illustrate the foreign key with an
example. Look at the following two tables: The "Persons" table:
P_Id
LastName
FirstName
Address
City
1
Hansen
Ola
Timoteivn 10
Sandnes
2
Svendson
Tove
Borgvn 23
Sandnes
3
Pettersen
Kari
Storgt 20
Stavanger
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 link between tables.
The FOREIGN KEY constraint also prevents that invalid data is inserted into the foreign key column,
because it has to be one of the values contained in the table it points to.
-------------------------------------------------------------------------------------------------------------------------------
3
Asmaa Hani Ashoor
AL Qurna Technical Institute
Computer Systems Department
SQL DataBase Basics
------------------------------------------------------------------------------------------------------------ -------------------
SQL FOREIGN KEY Constraint on CREATE TABLE
The following SQL creates a FOREIGN KEY on the "P_Id" column when the"Orders" table is created :
CREATE TABLE Orders(
O_Id int NOT NULL,
OrderNo int NOT NULL,P_Id
int PRIMARY KEY (O_Id),
FOREIGN KEY (P_Id) REFERENCES Persons(P_Id)
CREATE TABLE Orders(
O_Id int NOT NULL PRIMARY KEY,
OrderNo int NOT NULL,
P_Id int FOREIGN KEY REFERENCES Persons(P_Id)
-------------------------------------------------------------------------------------------------------------------------------
4
Asmaa Hani Ashoor
AL Qurna Technical Institute
Computer Systems Department
SQL DataBase Basics
------------------------------------------------------------------------------------------------------------ -------------------
SQL FOREIGN KEY Constraint on ALTER TABLE
To create a FOREIGN KEY constraint on the "P_Id" column when the "Orders" table is alreadycreated, use
the following SQL:
ALTER TABLE Orders
ADD FOREIGN KEY (P_Id)
REFERENCES Persons(P_Id)
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.
-------------------------------------------------------------------------------------------------------------------------------
5
Asmaa Hani Ashoor
AL Qurna Technical Institute
Computer Systems Department
SQL DataBase Basics
------------------------------------------------------------------------------------------------------------ -------------------
SQL CHECK Constraint on CREATE TABLE
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_Id int NOT NULL,
LastName varchar(255) NOT NULL,
FirstName varchar(255),
Address varchar(255),City
varchar(255), CHECK
(P_Id>0)
)
CREATE TABLE Persons (
P_Id int NOT NULL CHECK (P_Id>0),
LastName varchar(255) NOT NULL,
FirstName varchar(255),
Address varchar(255), City
varchar(255)
-------------------------------------------------------------------------------------------------------------------------------
6
Asmaa Hani Ashoor
AL Qurna Technical Institute
Computer Systems Department
SQL DataBase Basics
-------------------------------------------------------------------------------------------------------------------------------
Chapter Twelve
Indexing
The index: is a structure in SQL Server either on-disk or in-memory structure associated with a table or
View that is used to faster retrieval of rows.
Indexes are used to:

Improve performance. In most cases, access to data is faster with an index. Although an index cannot
be created for a view, an index created for the table on which a view is based can sometimes improve
the performance of operations on that view.

Indexes are used to retrieve data from the database faster.
Advantages of Indexing



It helps you to reduce the total number of I/O operations needed to retrieve that data, so you don’t
need to access a row in the database from an index structure.
Offers Faster search and retrieval of data to users.
Indexing also helps to reduce table space as you don’t need to link to a row in a table, as there is no
need to store the ROWID in the Index. Thus you will able to reduce the table space.
-------------------------------------------------------------------------------------------------------------------------------
1
Asmaa Hani Ashoor
AL Qurna Technical Institute
Computer Systems Department
SQL DataBase Basics
-------------------------------------------------------------------------------------------------------------------------------
Disadvantages of Indexing




To perform the indexing database management system, you need a primary key on the table with a
unique value.
You can’t perform any other indexes in Database on the Indexed data.
You are not allowed to partition an index-organized table.
SQL Indexing Decrease performance in INSERT, DELETE, and UPDATE query.
Example
Table A in Figure 1 has an index based on the employee numbers in the table. This key value provides a
pointer to the rows in the table. For example, employee number 19 points to employee KMP. An index allows
efficient access to rows in a table by creating a path to the data through pointers.
Unique indexes can be created to ensure uniqueness of the index key. An index key is a column or an ordered
collection of columns on which an index is defined.
Figure 1 shows the relationship between an index and a table.
-------------------------------------------------------------------------------------------------------------------------------
2
Asmaa Hani Ashoor
AL Qurna Technical Institute
Computer Systems Department
SQL DataBase Basics
-------------------------------------------------------------------------------------------------------------------------------
Index Example: At the moment, the Employees table, does not have an index on SALARY column.
Consider, the following query
Select * from Employee where Salary > 5000 and Salary < 7000
To find all the employees, who has salary greater than 5000 and less than 7000, the query engine has to
check each and every row in the table, resulting in a table scan, which can adversely affect the performance,
especially if the table is large. Since there is no index, to help the query, the query engine performs an entire
table scan.
Now Let's Create the Index to help the query:Here, we are creating an index on Salary column in the
employee table.
CREATE Index IX_Employee_Salary
ON Employee (SALARY ASC)
-------------------------------------------------------------------------------------------------------------------------------
3
Asmaa Hani Ashoor
AL Qurna Technical Institute
Computer Systems Department
SQL DataBase Basics
-------------------------------------------------------------------------------------------------------------------------------
The index stores salary of each employee, in the ascending order as shown below. The actual index may
look slightly different.
Now, when the SQL server has to execute the same query, it has an index on the salary column to help this
query. Salaries between the range of 5000 and 7000 are usually present at the bottom, since the salaries
are arranged in an ascending order. SQL server picks up the row addresses from the index and directly fetch
the records from the table, rather than scanning each row in the table. This is called as Index Seek.
The following are the different types of indexes in SQL Server
1. Clustered
2. Nonclustered
3. Unique
4. Filtered
5. XML
6. Full Text
7. Spatial
8. Columnstore
9. Index with included columns
10. Index on computed columns
-------------------------------------------------------------------------------------------------------------------------------
4
Asmaa Hani Ashoor
AL Qurna Technical Institute
Computer Systems Department
SQL DataBase Basics
-------------------------------------------------------------------------------------------------------------------------------
Clustered Index
Clustered indexes sort and store data rows in the table or view depending on their key values. These columns
are included in the index definition. There may be just one clustered index in each table as the data rows can
be stored in a single order.
For an index of type Clustered, it saves information from the basis in an orderly manner. For example, when
you set any column as a primary key in the table, the database automatically adds an index of its type
Clustered. For this reason, we find that the id of the users is returned in the same order that was Add them as
follows.
Create Employees table using the script below.
CREATE TABLE [Employee]
(
[Id] int Primary Key,
[Name] varchar(50),
[Salary] int,
[Gender] varchar(10),
[City] varchar(50)
)
-------------------------------------------------------------------------------------------------------------------------------
5
Asmaa Hani Ashoor
AL Qurna Technical Institute
Computer Systems Department
SQL DataBase Basics
-------------------------------------------------------------------------------------------------------------------------------
Note that Id column is marked as primary key. Primary key, constraint create clustered indexes
automatically if no clustered index already exists on the table and a nonclustered index is not specified when
you create the PRIMARY KEY constraint.
Now execute the following insert queries. Note that, the values for Id column are not in a sequential order.
Insert into Employee Values(3,'John',4500,'Male','New York')
Insert into Employee Values(1,'Sam',2500,'Male','London')
Insert into Employee Values(4,'Sara',5500,'Female','Tokyo')
Insert into Employee Values(5,'Todd',3100,'Male','Toronto')
Insert into Employee Values(2,'Pam',6500,'Female','Sydney')
Execute the following SELECT query
Select * from Employee
Inspite, of inserting the rows in a random order, when we execute the select query we can see that all the
rows in the table are arranged in an ascending order based on the Id column. This is because a clustered index
determines the physical order of data in a table, and we have got a clustered index on the Id column.
Because of the fact that, a clustered index dictates the physical storage order of the data in a table, a table can
contain only one clustered index. If you take the example of Employee table, the data is already arranged by
the Id column, and if we try to create another clustered index on the Name column, the data needs to be
rearranged based on the NAME column, which will affect the ordering of rows that's already done based on
the ID column.
-------------------------------------------------------------------------------------------------------------------------------
6
Asmaa Hani Ashoor
AL Qurna Technical Institute
Computer Systems Department
SQL DataBase Basics
-------------------------------------------------------------------------------------------------------------------------------
For this reason, SQL server doesn't allow us to create more than one clustered index per table. The following
SQL script, raises an error stating 'Cannot create more than one clustered index on table 'tblEmployee'. Drop
the existing clustered index PK__tblEmplo__3214EC0706CD04F7 before creating another.'
Create Clustered Index IX_Employee_Name
ON Employee(Name)
A clustered index is analogous to a telephone directory, where the data is arranged by the last name. We just
learnt that, a table can have only one clustered index. However, the index can contain multiple columns (a
composite index), like the way a telephone directory is organized by last name and first name.
Let's now create a clustered index on 2 columns. To do this we first have to drop the existing clustered
index on the Id column.
Drop index Employee.PK__tblEmplo__3214EC070A9D95DB
When you execute this query, you get an error message stating 'An explicit DROP INDEX is
not allowed on index 'tblEmployee.PK__tblEmplo__3214EC070A9D95DB'. It is being used for
PRIMARY KEY constraint enforcement.'
To successfully delete the clustered index, right click on the
index in the Object explorer window and select DELETE.
-------------------------------------------------------------------------------------------------------------------------------
7
Asmaa Hani Ashoor
AL Qurna Technical Institute
Computer Systems Department
SQL DataBase Basics
-------------------------------------------------------------------------------------------------------------------------------
Now, execute the following CREATE INDEX query, to create a composite clustered Index on the Gender
and Salary columns.
Create Clustered Index IX_Employee_Gender_Salary
ON Employee(Gender DESC, Salary ASC)
Now, if you issue a select query against this table you should see the data physically arranged, FIRST by
Gender in descending order and then by Salary in ascending order. The result is shown below.
-------------------------------------------------------------------------------------------------------------------------------
8
Asmaa Hani Ashoor
AL Qurna Technical Institute
Computer Systems Department
SQL DataBase Basics
-------------------------------------------------------------------------------------------------------------------------------
Chapter Thirteen
NonClustered Index
A nonclustered index :- is analogous to an index in a textbook. The data is stored in one place, the index in
another place. The index will have pointers to the storage location of the data. Since, the nonclustered index is
stored separately from the actual data, a table can have more than one non clustered index.
In the index itself, the data is stored in an ascending or descending order of the index key, which doesn't in
any way influence the storage of data in the table.
The following SQL creates a Nonclustered index on the NAME column on Employee table:
Create NonClustered Index X_Employee_Name
ON Employee(Name)
Difference between Clustered and NonClustered Index:
1. Only one clustered index per table, where as you can have more than one non clustered index
2. Clustered index is faster than a non clustered index, because, the non-clustered index has to refer back to
the table, if the selected column is not present in the index.
3. Clustered index determines the storage order of rows in the table, and hence doesn't require additional disk
space, but where as a Non Clustered index is stored seperately from the table, additional storage space is
required.
-------------------------------------------------------------------------------------------------------------------------------
1
Asmaa Hani Ashoor
AL Qurna Technical Institute
Computer Systems Department
SQL DataBase Basics
-------------------------------------------------------------------------------------------------------------------------------
Unique index
Unique index is:- used to enforce uniqueness of key values in the index.
Create the Employee table using the script below
CREATE TABLE [Employee]
(
[Id] int Primary Key,
[FirstName] varchar(50),
[LastName] varchar(50),
[Salary] int,
[Gender] varchar(10),
[City] varchar(50)
)
Since, we have marked Id column, as the Primary key for this table, a UNIQUE CLUSTERED INDEX gets
created on the Id column, with Id as the index key.
We can verify this by executing the sp_helpindex system stored procedure as shown below:
Execute sp_helpindex Employee
Output:
----------------------------------------------------------------------------------------------------------------------------- --
2
Asmaa Hani Ashoor
AL Qurna Technical Institute
Computer Systems Department
SQL DataBase Basics
-------------------------------------------------------------------------------------------------------------------------------
Since, we now have a UNIQUE CLUSTERED INDEX on the Id column, any attempt to duplicate the
key values, will throw an error stating 'Violation of PRIMARY KEY constraint
'PK__Emplo__3214EC07236943A5'. Cannot insert duplicate key in object dbo.Employee'
Not:To view the Indexes: In the object explorer, expand Indexes folder. Alternatively use sp_helptext system
stored procedure. The following command query returns all the indexes on Employee table.
Example: The following insert queries will fail
Insert into Employee Values(1,'Mike', 'Sandoz',4500,'Male','New York')
Insert into Employee Values(1,'John', 'Menco',2500,'Male','London')
Now let's try to drop the Unique Clustered index on the Id column. This will raise an error stating - 'An
explicit DROP INDEX is not allowed on index Employee.PK__Emplo__3214EC07236943A5. It is being used
for PRIMARY KEY constraint enforcement.'
Drop index Employee.PK__Emplo__3214EC07236943A5
So this error message proves that, SQL server internally, uses the UNIQUE index to enforce the uniqueness
of values and primary key.
----------------------------------------------------------------------------------------------------------------------------- --
3
Asmaa Hani Ashoor
AL Qurna Technical Institute
Computer Systems Department
SQL DataBase Basics
-------------------------------------------------------------------------------------------------------------------------------
Expand keys folder in the object explorer window, and you can see a primary key constraint. Now, expand
the indexes folder and you should see a unique clustered index. In the object explorer it just shows the
'CLUSTERED' word. To, confirm, this is infact an UNIQUE index, right click and select properties. The
properties window, shows the UNIQUE checkbox being selected.
----------------------------------------------------------------------------------------------------------------------------- --
4
Asmaa Hani Ashoor
AL Qurna Technical Institute
Computer Systems Department
SQL DataBase Basics
-------------------------------------------------------------------------------------------------------------------------------
SQL Server allows us to delete this UNIQUE CLUSTERED INDEX from the object explorer. so, Right click
on the index, and select DELETE and finally, click OK. Along with the UNIQUE index, the primary key
constraint is also deleted.
Now, let's try to insert duplicate values for the ID column. The rows should be accepted, without any
primary key violation error.
Insert into Employee Values(1,'Mike', 'Sandoz',4500,'Male','New York')
Insert into Employee Values(1,'John', 'Menco',2500,'Male','London')
So, the UNIQUE index is used to enforce the uniqueness of values and primary key constraint.
Creating a UNIQUE NON CLUSTERED index on the FirstName and LastName columns.
Create Unique NonClustered Index X_Employee_FirstName_LastName
On Employee(FirstName, LastName)
This unique non clustered index, ensures that no 2 entires in the index has the same first and last names.
----------------------------------------------------------------------------------------------------------------------------- --
5
Asmaa Hani Ashoor
AL Qurna Technical Institute
Computer Systems Department
SQL DataBase Basics
-------------------------------------------------------------------------------------------------------------------------------
The benefits of unique indexes include the following:

Data integrity of the defined columns is ensured.

Additional information helpful to the query optimizer is provided.
Note:
1. By default, a PRIMARY KEY constraint, creates a unique clustered index, where as a UNIQUE constraint
creates a unique nonclustered index. These defaults can be changed if you wish to.
2. A UNIQUE constraint or a UNIQUE index cannot be created on an existing table, if the table contains
duplicate values in the key columns. Obviously, to solve this,remove the key columns from the index
definition or delete or update the duplicate values.
3. By default, duplicate values are not allowed on key columns, when you have a unique index or
constraint. For, example, if I try to insert 10 rows, out of which 5 rows contain duplicates, then all the 10 rows
are rejected. However, if I want only the 5 duplicate rows to be rejected and accept the non-duplicate 5 rows,
then I can use IGNORE_DUP_KEY option. An example of using IGNORE_DUP_KEY option is shown below.
CREATE UNIQUE INDEX IX_tblEmployee_City
ON tblEmployee(City)
WITH IGNORE_DUP_KEY
----------------------------------------------------------------------------------------------------------------------------- --
6
Asmaa Hani Ashoor
AL Qurna Technical Institute
Computer Systems Department
SQL DataBase Basics
-------------------------------------------------------------------------------------------------------------------------------
How to add an index
The general form of adding an index
CREATE INDEX index_name
ON table_name (colums);
index_name: We put the name that we want to put in the index.
table_name: We put the name of the table whose columns we will put the index on
columns: We put the name of the column for which the index will be created, and if you want to put more
than one column, you must put a comma between each two columns.
Example1:
CREATE INDEX idx_username
ON users (username);
Example2:
CREATE INDEX idx_full_name
ON users (first_name , last_name);
----------------------------------------------------------------------------------------------------------------------------- --
7
Asmaa Hani Ashoor
AL Qurna Technical Institute
Computer Systems Department
SQL DataBase Basics
-------------------------------------------------------------------------------------------------------------------------------
How to add an index that contains uniform values
The general form of adding an index containing only standardized values.
CREATE UNIQUE INDEX index_name
ON table_name (colums);
Example1:
CREATE UNIQUE INDEX idx_username
ON users (username);
Example2:
CREATE UNIQUE INDEX idx_full_name
ON users (first_name, last_name);
----------------------------------------------------------------------------------------------------------------------------- --
8
Asmaa Hani Ashoor
AL Qurna Technical Institute
Computer Systems Department
SQL DataBase Basics
-------------------------------------------------------------------------------------------------------------------------------
How to delete the index
General form of index deletion.
DROP INDEX table_name.index_name;
Example1:
DROP INDEX users.idx_username;
----------------------------------------------------------------------------------------------------------------------------- --
9
Asmaa Hani Ashoor
AL Qurna Technical Institute
Computer Systems Department
SQL DataBase Basics
-------------------------------------------------------------------------------------------------------------------------------
Chapter Fourteen
Filtered Index
filtered index :- is a non-clustered index that allows us to apply specific conditions to cover a
subset of rows in the table.
Filtered indexes advantages
1.Improved query performance and plan quality.
2. Reduced index maintenance costs.
3. Reduced index storage costs.
4. filtered indexes can help you save spaces especially when the index key columns are sparse. Sparse
columns are the ones that have many NULL values.
The following syntax illustrates how to create a filtered index:
CREATE INDEX index_name
ON table_name(column_list)
WHERE predicate;
Or
CREATE nonclustered INDEX index_name
ON table_name(column_list)
WHERE predicate;
-------------------------------------------------------------------------------------------------------------------------------
1
Asmaa Hani Ashoor
AL Qurna Technical Institute
Computer Systems Department
SQL DataBase Basics
-------------------------------------------------------------------------------------------------------------------------------
In this syntax:



First, specify the name of the filtered index after the CREATE INDEX clause.
Second, list the table name with a list of key columns that will be included in the index.
Third, use a WHERE clause with a predicate to specify which rows of the table should be included in
the index.
SQL Server filtered index example
CREATE INDEX x_phone
ON employees(phone)
WHERE phone IS NOT NULL;
SELECT firstname,lastname,phone
FROM employees
WHERE phone = '(281) 363-3309';
-------------------------------------------------------------------------------------------------------------------------------
2
Asmaa Hani Ashoor
AL Qurna Technical Institute
Computer Systems Department
SQL DataBase Basics
-------------------------------------------------------------------------------------------------------------------------------
XML Index
An XML index is an index type that is specifically built to handle indexing XML type columns. There are two
different types of XML indexes, primary and secondary.
A primary XML:- index stores and indexes all the parts of data in your chosen XML column. A primary XML
index requires that there be a clustered primary key index on your table so the XML index can correlate rows
from the XML index with rows in the table that contain the XML column. Also, note that there can only be
one primary XML index on a table. Since primary XML indexes index the entire column, which makes them
quite large in most cases, you can also add secondary XML indexes which further enhances performance by
creating another index on top of the primary XML index.
Secondary XML:- indexes are dependent on primary XML indexes – you cannot create any secondary
indexes without first having created a primary index.
Secondary XML indexes come in 3 types: PATH, VALUE, and PROPERTY indexes. Secondary indexes are
designed to provide additional optimization for certain types of XML queries.
 PATH secondary indexes often help to optimize queries that make use of a path.
 PROPERTY secondary indexes are designed to be helpful with queries where the primary key field is
used, and where multiple values are retrieved from a single XML instance.
 VALUE secondary indexes are good for queries that use wildcards in a path to find known values – if
the full path is not known, but the value being filtered IS known, a VALUE index will probably
optimize the query execution.
-------------------------------------------------------------------------------------------------------------------------------
3
Asmaa Hani Ashoor
AL Qurna Technical Institute
Computer Systems Department
SQL DataBase Basics
-------------------------------------------------------------------------------------------------------------------------------
Spatial Index
A spatial index:- is another special index type that is built to accommodate adding indexes on columns created
using the spatial datatypes geography and geometry. As was the case with an XML index, spatial indexes also
require that the database table that you are creating the spatial index on also has a clustered primary key index
defined. Spatial indexes cannot be specified on indexed views.
Full Text Index
Creates a full-text index on a table or indexed view in a database in SQL Server. Only one full-text index is
allowed per table or indexed view, . A full-text index can contain up to 1024 columns.
indexes can be created on binary or character-based column types as well. They are different from your
standard index types in that instead of using the entire column as the index key the column data is broken up
into tokens and these tokens are what is used to build the index and used as a predicate when navigating the
index structure. The index structure itself is also stored in its own catalog and not in the data files of the
database
Columnstore Index
A column store index is an index that was designed mainly for improving the query performance for
workloads with very large amounts of data.
This new type of index stores data column-wise instead of row-wise, as indexes currently do. For example,
consider an Employee table containing employee data, as shown in Table 1.
-------------------------------------------------------------------------------------------------------------------------------
4
Asmaa Hani Ashoor
AL Qurna Technical Institute
Computer Systems Department
SQL DataBase Basics
-------------------------------------------------------------------------------------------------------------------------------
Table 1: Sample Employee Table
FirstName
LastName
HireDate
Gender
Adam
Sherri
Brian
Jose
Tim
Tim
Jorgensen
McDonald
McDonald
Chinchilla
Murphy
Moolic
5/9/2008
7/1/2009
09/15/2009
1/10/2010
7/1/2009
6/1/2008
Male
Female
Male
Male
Male
Male
In a row-based index, the data in the Employee table is stored in one or more data pages, as shown in Figure 1.
-------------------------------------------------------------------------------------------------------------------------------
5
Asmaa Hani Ashoor
AL Qurna Technical Institute
Computer Systems Department
SQL DataBase Basics
-------------------------------------------------------------------------------------------------------------------------------
In a column-based index, the data in the Employee table is stored in separate pages for each of the columns,
as shown in Figure 2.
Performance advantages in columnstore indexes are possible by leveraging the VertiPaq compression
technology, which enables large amounts of data to be compressed in-memory. This in-memory compressed
store reduces the number of disk reads and increases buffer cache hit ratios because only the smaller columnbased data pages that need to satisfy a query are moved into memory.
-------------------------------------------------------------------------------------------------------------------------------
6
Asmaa Hani Ashoor
AL Qurna Technical Institute
Computer Systems Department
SQL DataBase Basics
-------------------------------------------------------------------------------------------------------------------------------
Index With Included Columns
Included columns can be used to create a covering indexes without including all the data into the key
columns, so that it is not necessary to use lookup operations or to access the physical table. This means a
reduced number of I/O operations to get the data.
The syntax for creating an index with included columns
The following illustrates the syntax for creating a non-clustered index with included columns:
CREATE [UNIQUE] INDEX index_name
ON table_name(key_column_list)
INCLUDE(included_column_list);
In this syntax:



First, specify the name of the index after CREATE INDEX clause. If the index is unique, you need to
add the UNIQUE keyword.
Second, specify the name of the table and a list of key column list for the index after the ON clause.
Third, list a comma-separated list of included columns in the INCLUDE clause.
CREATE UNIQUE INDEX ix_cust_email_inc
ON sales.customers(email)
INCLUDE(first_name,last_name);
-------------------------------------------------------------------------------------------------------------------------------
7
Asmaa Hani Ashoor
AL Qurna Technical Institute
Computer Systems Department
SQL DataBase Basics
-------------------------------------------------------------------------------------------------------------------------------
Chapter Fiveteen
Sorting
Sorting : is the process of rearranging the table data on the basis of a one or more field, and data
can be arranged in ascending or descending order.
When you use the SELECT statement to query data from a table, the order of rows in the result set is not
guaranteed. It means that SQL Server can return a result set with an unspecified order of rows.
The only way for you to guarantee that the rows in the result set are sorted is to use the ORDER BY clause.
The following illustrates the ORDER BY clause syntax:
SELECT
select_list
FROM table_name
ORDER BY
column_name | expression [ASC | DESC ];
In this syntax:
column_name | expression
First, you specify a column name or an expression on which to sort the result set of the query. If you specify
multiple columns, the result set is sorted by the first column and then that sorted result set is sorted by the
second column, and so on.
The columns that appear in the ORDER BY clause must correspond to either column in the select list or
columns defined in the table specified in the FROM clause.
-------------------------------------------------------------------------------------------------------------------------------
1
Asmaa Hani Ashoor
AL Qurna Technical Institute
Computer Systems Department
SQL DataBase Basics
-------------------------------------------------------------------------------------------------------------------------------
ASC | DESC
Second, use ASC or DESC to specify whether the values in the specified column should be sorted in ascending
or descending order.
The ASC sorts the result from the lowest value to the highest value while the DESC sorts the result set from
the highest value to the lowest one.
If you don’t explicitly specify ASC or DESC, SQL Server uses ASC as the default sort order. Also, SQL Server
treats NULL as the lowest value.
When processing the SELECT statement that has an ORDER BY clause, the ORDER BY clause is the very last
clause to be processed.
SQL Server ORDER BY clause example
We will use the customers table in the sample database from the demonstration.
-------------------------------------------------------------------------------------------------------------------------------
2
Asmaa Hani Ashoor
AL Qurna Technical Institute
Computer Systems Department
SQL DataBase Basics
-------------------------------------------------------------------------------------------------------------------------------
A/ Sort a result set by one column in ascending order
The following statement sorts the customer list by the first name in ascending order:
SELECT
first_name,
last_name
FROM sales.customers
ORDER BY first_name;
In this example, because we did not specify ASC or DESC, the ORDER BY clause used ASC by default.
-------------------------------------------------------------------------------------------------------------------------------
3
Asmaa Hani Ashoor
AL Qurna Technical Institute
Computer Systems Department
SQL DataBase Basics
-------------------------------------------------------------------------------------------------------------------------------
B/ Sort a result set by one column in descending order
The following statement sorts the customer list by the first name in descending order.
SELECT
firstname,
lastname
FROM sales.customers
ORDER BY
first_name DESC;
In this example, because we specified the DESC explicitly, the ORDER BY clause sorted the result set by values
in the first_name column in descending order.
-------------------------------------------------------------------------------------------------------------------------------
4
Asmaa Hani Ashoor
AL Qurna Technical Institute
Computer Systems Department
SQL DataBase Basics
-------------------------------------------------------------------------------------------------------------------------------
C/ Sort a result set by multiple columns
The following statement retrieves the first name, last name, and city of the customers. It sorts the customer list
by the city first and then by the first name.
SELECT
city,
first_name,
last_name
FROM sales.customers
ORDER BY
city, first_name
-------------------------------------------------------------------------------------------------------------------------------
5
Asmaa Hani Ashoor
AL Qurna Technical Institute
Computer Systems Department
SQL DataBase Basics
-------------------------------------------------------------------------------------------------------------------------------
D/Sort a result set by multiple columns and different orders
The following statement sorts the customers by the city in descending order and then sorts the sorted result
set by the first name in ascending order.
SELECT
city,
first_name, last_name
FROM sales.customers
ORDER BY
first_name ASC; , city DESC
-------------------------------------------------------------------------------------------------------------------------------
6
Asmaa Hani Ashoor
AL Qurna Technical Institute
Computer Systems Department
SQL DataBase Basics
-------------------------------------------------------------------------------------------------------------------------------
E/ Sort a result set by a column that is not in the select list
It is possible to sort the result set by a column that does not appear on the select list. For example, the following
statement sorts the customer by the state even though the state column does not appear on the select list.
SELECT
city,
first_name, last_name
FROM sales.customers
ORDER BY state;
Note that the state column is defined in the customers table. If it was not, then you would have an invalid
query.
-------------------------------------------------------------------------------------------------------------------------------
7
Asmaa Hani Ashoor
AL Qurna Technical Institute
Computer Systems Department
SQL DataBase Basics
-------------------------------------------------------------------------------------------------------------------------------
F/ Sort a result set by an expression
The LEN() function returns the number of characters in a string. The following statement uses
the LEN() function in the ORDER BY clause to retrieve a customer list sorted by the length of the first name:
SELECT
first_name, last_name
FROM sales.customers
ORDER BY
LEN(first_name) DESC;
-------------------------------------------------------------------------------------------------------------------------------
8
Asmaa Hani Ashoor
AL Qurna Technical Institute
Computer Systems Department
SQL DataBase Basics
-------------------------------------------------------------------------------------------------------------------------------
G/ Sort by ordinal positions of columns
SQL Server allows you to sort the result set based on the ordinal positions of columns that appear in the select
list.
The following statement sorts the customers by first name and last name. But instead of specifying the column
names explicitly, it uses the ordinal positions of the columns:
SELECT
first_name, last_name
FROM
sales.customers
ORDER BY
1,2
In this example, 1 means the first_name column, and 2 means the last_name column.
Using the ordinal positions of columns in the ORDER BY clause is considered a bad programming practice for
a couple of reasons.


First, the columns in a table don’t have ordinal positions and need to be referenced by name.
Second, when you modify the select list, you may forget to make the corresponding changes in
the ORDER BY clause.
Therefore, it is a good practice to always specify the column names explicitly in the ORDER BY clause.
-------------------------------------------------------------------------------------------------------------------------------
9
Asmaa Hani Ashoor
Download