SQL Structural Query Language
SQL Structural Query Language
SQL Structural Query Language
(Standard
Query
Language)
prpared by Tilahun
Unit One:Fundamental concepts
of relational database
This unit is developed to provide you the
necessary information regarding the
following content coverage and topics:
• Data management approaches
• Relational Database management system
• Structured query language
prpared by Tilahun
Data management approaches
The way in which computers manage
data has come a long way over the last
few decades. Today’s users take for
granted the many benefits found in a
database system. However, it wasn’t that
long ago that computer relied on a much
less elegant and costly approach to data
management called the file-based
system.
prpared by Tilahun
1. File based approach
One way to keep information on a
computer is to store it in permanent files.
A company system has a number of
application programs; each of them is
designed to manipulate data files. These
application programs have been written
at the request of the users in the
organization.
New applications are added to the system
as the need arises. The system just
described is called the file-based system.
Consider a traditional banking system
that uses the file-based system to
prpared by Tilahun
Disadvantages of the file-based approach
Using the file-based system to keep
prpared by Tilahun
Database Properties
prpared by Tilahun
Characteristics and Benefits of a Database
prpared by Tilahun
Objectiv
e
Create the database & relation
structures;
Perform basic data management
tasks, such as:
Insertion
Modification
Deletion of data
Perform both simple and complex
queries prpared by Tilahun
SQL
Transform-oriented language
A language to use relations to
transform input into required
output
Non-procedural language
Specify what you require than how to get
it
Free format
Command consists English word,
such as:
CREATE, INSERT, SELECT,
prpared by Tilahun etc
Function of SQL
Execute queries against a
database
Retrieve data from a database
Insert records into a database
Update records in a database
Delete records from a database
Create new databases
Create new tables in a database
Set permissions
prpared by Tilahun
Categories
of SQL
DDL (Data Definition
Language):
DML (Data Manipulation
Language):
DCL (Data Control
Language):
prpared by Tilahun
DDL
DDL and DCL statements are
commonly used by a database
designer and database
administrator for establishing the
database structures.
The DDL part permits database
tables to be created or deleted.
It also defines indexes (keys),
specify links between tables, and
impose constraints between tables.
prpared by Tilahun
Most important DDL statements :
CREATE DATABASE - creates a new
database
ALTER DATABASE - modifies a database
CREATE TABLE - creates a new table
ALTER TABLE - modifies a table
Adds or removes a column from a table.
Used in connection with ADD, MODIFY and
DROP.
DROP TABLE - deletes a table
Deletes all rows & removes the table from the
database.
CREATE INDEX - creates an index
prpared by Tilahun
DML
SELECT - extracts data from a database
- retrieves rows from a table.
Specifies which columns to include in the
result set.
UPDATE - updates data in a database
Modifies existing rows in a table.
DELETE - deletes data from a database
Removes a specified row or a set of rows from
a table.
INSERT INTO/ insert - inserts new data
into a database
Adds rows to a table.
prpared by Tilahun
DCL
GRANT: to allow specified users to
perform specified tasks
REVOKE: to cancel previously granted
or denied permissions
DENAY: restricts users not to perform
tasks
The operations for which
privileges may be granted to or
revoked from a user or role may
include CONNECT, SELECT, INSERT,
UPDATE, DELETE, EXECUTE, and USAGE
prpared by Tilahun
SQL key words
ADA DEC GRANT NUMERIC
ALL DECIMAL GROUP OF
AND DECLARE HAVING ON
ANY DEFUALT IN OPEN
AS DELETE INDICATOR OPTION
ASC DESC INSERT OPEN
AUTHORIZATION DISTNICT INT OPTION
AVG DOUBLE INTEGER OR
BEGIN END INTO ORDER
BETWEEN ESCAPE IS PRIMARY
BY EXEC KEY REAL
C EXISTS LANGAUGE SELECT
CHAR FETCH LIKE SET
CHARACTER FLOAT MAX SOME
CHECK FOR MIN SUM
CLOSE FOREIGN MODULE TABLE
COBOL FORTRAN NOT TO UNION
COMMIT FOUND NULL UPDATE
CONTINUE FROM USER
COUNT GO VIEW
CREATE GOTO WHERE
CURRENT WITH
CURSOR WORK
prpared by Tilahun
Name
To identify database object
on which the statement
should act
Tablename
Column name
prpared by Tilahun
Data Types
Character strings:
Data type Description
Fixed-length character string. Maximum 8,000 characters
char(n) or
character(n)
prpared by Tilahun
Number types:
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 4 bytes
2,147,483,647
bigint Allows whole numbers between - 8 bytes
9,223,372,036,854,775,808 and
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
numeric(p,s Fixed precision and scale numbers. 5-17
) Allows numbers from -10^38 +1 to 10^38 –1. bytes
smallmone Monetary data from -214,748.3648 to 214,748.3647 4 bytes
y
money Monetary data from -922,337,203,685,477.5808 to 8 bytes
922,337,203,685,477.5807
float(n) Floating precision number data from -1.79E + 308 4 or 8
to 1.79E + 308. bytes
real Floating precisionprpared
number data from -3.40E + 38 to
by Tilahun
4 bytes
Date types:
Data Description Stora
type ge
datetime From January 1, 1753 to December 31, 9999 8 bytes
with an accuracy of 3.33 milliseconds
datetime From January 1, 0001 and December 31, 6-8
2 9999 with an accuracy of 100 nanoseconds bytes
smalldatet From January 1, 1900 to June 6, 2079 with an 4 bytes
ime accuracy of 1 minute
date Store a date only. From January 1, 0001 to 3 bytes
December 31, 9999
time Store a time only to an accuracy of 100 3-5
nanoseconds bytes
datetimeof The same as datetime2 with the addition of a 8-10
fset time zone offset bytes
timestam Stores a unique number that gets updated
p 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 tableprpared
maybyhave
Tilahunonly one
Install SQL server
Identify the hardware &
software requirements
before installation.
prpared by Tilahun
Requirement for Installing MS
SQL Server DBMS Software
The following system
requirements cover SQL
Server 2012 Standard Edition
on 32-bit and x64 platforms,
as well as Itanium-based
systems.
prpared by Tilahun
SQL Server 2012 64-bit
Hardware Requirements:
Component Minimum Requirement Recommended Requirement
Processor x64 Processor with at least 1.4 GHz 2.0 GHz or faster, 4 or more
cores
prpared by Tilahun
SQL Server 2012 32-bit Software Requirements:
• Operating System: SQL Server 2012 32-bit
supports a variety of 32-bit and 64-bit Windows Server
and Windows client operating systems. The specific
editions of SQL Server 2012 (Enterprise, Standard,
etc.) may have different supported operating systems.
Check the official documentation for exact details.
• .NET Framework: SQL Server 2012 requires .NET
Framework 3.5 SP1 for installation. The installer will
typically install this for you. You may also need .NET
Framework 4.0 or later for some features.
• SQL Server 2012 Edition: Make sure you have the
correct edition of SQL Server 2012 (e.g., Enterprise,
Standard, Express) for your needs and licensing.
• SQL Server 2012 Service Pack: It's advisable to
install the latest service pack or cumulative update for
SQL Server 2012 for bug fixes and enhancements.
prpared by Tilahun
Working
with SQL
Commands
prpared by Tilahun
Unit Two:
Data definition language
prpared by Tilahun
Create Database
Statement
Syntax
prpared by Tilahun
CREATE TABLE Statement
Database Tables
prpared by Tilahun
Exercise
Create database by the name
SQLStudent
Create the following table using access
procedures.
IDNo StudentDetail
Fname Lname Age Gender
001 Derartu Gudeta 19 F
002 Kebron Solomon 21 M
003 Alemu Ebisa 20 M
prpared by Tilahun
NOT NULL Constraint
Enforces a column to NOT accept NULL
values.
Enforces a field to always contain a
value. TABLE Employee
CREATE
(Id int NOT NULL,
LastName varchar(25) NOT NULL,
FirstName varchar(25),
Address varchar(10),
City varchar(8))
prpared by Tilahun
PRIMARY KEY Constraint
Primary keys must contain
unique values.
Can’t contain NULL values.
Each table should have a
primary key.
prpared by Tilahun
Primary key on create table
CREATE TABLE Employee
(Id int NOT NULL PRIMARY KEY,
LastName varchar(25) NOT NULL,
FirstName varchar(25),
Address varchar(10),
City varchar(8)) CREATE TABLE Employee
(Id int NOT NULL,
LastName varchar(25) NOT NULL,
FirstName varchar(25),
Address varchar(10),
City varchar(8),
CONSTRAINT pk_ID PRIMARY KEY
(Id,LastName))
prpared by Tilahun
Primary key on Alter table
ALTER TABLE Studentdetail ADD PRIMARY KEY (Id)
prpared by Tilahun
DROP a PRIMARY
KEY Constraint
ALTER TABLE Employee DROP
CONSTRAINT pk_ID
prpared by Tilahun
Books
SerialNo Title Author Publisher
Borrower
prpared by Tilahun
Composite key constraints
CREATE TABLE employee
(
Empno char(5),
fname varchar(15),
lname varchar(15),
salary numeric (8,2),
pno char(2), primary key(Empno, pno)
)
prpared by Tilahun
Foreign key
constraints
A FOREIGN KEY in one table points
to a PRIMARY KEY in another table.
FK is used to prevent actions that
would destroy link between tables.
prpared by Tilahun
Example
"Persons" table:
P_Id LastName FirstName Address City
"Orders" table:
O_Id OrderNo P_Id
1 77895 3
2 44678 3
3 22456 2
4 24562
prpared by Tilahun 1
On CREATE table
CREATE TABLE Orders
(O_Id int PRIMARY KEY, OrderNo int NOT NULL,
P_Id int FOREIGN KEY REFERENCES Persons(P_Id))
On ALTER table
ALTER TABLE Orders
ADD FOREIGN KEY (P_Id) REFERENCES Persons (P_Id)
on ALTER TABLE
ALTER TABLE Persons
ALTER COLUMN City SET DEFAULT 'SANDNES'
prpared by Tilahun
Example
ID FName Gender
Edu01 Weinshet F
Edu02 Tadesse M
Edu03 Beti F
Edu04 Truwork F
On alter
table
ALTER TABLE employee3
between 200 and 5000)
ADD CONSTRAINT sal_chk CHECK (salary
prpared by Tilahun
Insert Data Only in Specified
Columns
prpared by Tilahun
Drop SQL constraints
Alter table customer Alter column Gender
drop default
prpared by Tilahun
SQL SELECT Statement
Used to select data from a
database
Syntax
SELECT column_name(s)FROM
table_name
SELECT * FROM table_name
prpared by Tilahun
SQL SELECT DISTINCT
Statement
SELECT DISTINCT column_name(s)FROM
table_name
prpared by Tilahun
WHERE Clause
Used to filter records or to
extract only those records that
fulfill a specified criterion.
Syntax
SELECT column_name(s)
FROM table_name
WHERE column_name
operator value
prpared by Tilahun
Examples
Select * FROM StudInfo WHERE
Gender=‘F’
SELECT * FROM StudInfo
WHERE Fname ‘T%’
SELECT EmpID, EmpName
WHERE Salary > 4000
prpared by Tilahun
Operators in WHERE
Clause
Operator Description
= Equal
<> Not equal
> Greater than
< Less than
>= Greater than or equal
<= Less than or equal
BETWEE
Between an inclusive range
N
LIKE Search for a pattern
IN If you know the exact value you want to
return for at least one of the columns
prpared by Tilahun
AND Operator
SELECT * FROM Persons WHERE
FirstName='Tove‘ AND
LastName='Svendson‘
Example
SELECT *
FROM StudInfo
WHERE ID ‘E%’
AND Gender=‘F’
prpared by Tilahun
OR Operator
Example
SELECT * FROM Persons
WHERE FirstName='Tove'OR
FirstName='Ola‘
SELECT * FROM StudInfo
WHERE Fname=‘B%’
OR Gender=‘M
prpared by Tilahun
AND & OR Operators
SELECT * FROM StudInfo
WHERE Gender=‘F’
AND (Fname=‘T%’ OR Fname=‘W%’
prpared by Tilahun
SQL ORDER BY Keyword
Used to sort the result-set by
a specified column
Sort the records in ascending
order by default.
If you want to sort the
records in a descending
order, you can use the DESC
keyword. prpared by Tilahun
Syntax
SELECTcolumn_name(s)
FROM table_name
ORDER BY column_name(s) ASC|
DESC
Example
SELECTFname, Gender
FROM StudInfo
ORDER BY Fname ASC/DESC
prpared by Tilahun
SQL UPDATE Statement
Used to update existing records in a
table
Syntax
UPDATE table_name
prpared by Tilahun
Example
UPDATEStudInfo
SET Fname=‘Asnake’,
Gender=‘M’
WHERE ID= ‘Edu04’
prpared by Tilahun
SQL DELETE Statement
Used to delete records/ rows in a table.
Syntax
DELETE FROM table_name
WHERE some_column=some_value
Example
DELETE FROM Project
WHERE PjtNo=N08
prpared by Tilahun
Delete All Rows
DELETE FROM
table_name or
DELETE * FROM
table_name
prpared by Tilahun
SQL ALTER TABLE Statement
The ALTER TABLE statement is used to
add, delete, or modify columns in an
existing table.
prpared by Tilahun
SQL ALTER TABLE Syntax
To add a column in a table, use the following syntax:
prpared by Tilahun
To change the data type of a column in a table,
use the following syntax:
Example
Alter table student alter column age int
prpared by Tilahun
To delete a column in a table, use the following syntax
(notice that some database systems don't allow deleting a column):
Example:
ALTER TABLE student drop COLUMN Gender
prpared by Tilahun
AUTO INCREMENT Field
Auto-increment allows a unique number
to be generated when a new record is
inserted into a table.
prpared by Tilahun
Unit Three:
Data manipulation
language
prpared by Tilahun
SELECT - extracts data from a database
- retrieves rows from a table.
Specifies which columns to include in the
result set.
UPDATE - updates data in a database
Modifies existing rows in a table.
DELETE - deletes data from a database
Removes a specified row or a set of rows
from a table.
INSERT INTO/ insert - inserts new data into
a database
Adds rows to a table.
prpared by Tilahun
SELECT QUERY
Assume we have a table called Employees with the
following columns:
• EmployeeID (Primary Key)
• FirstName
• LastName
• Department
• Salary
This query selects all columns from the
Employees table
SELECT EmployeeID, FirstName,
LastName, Department, Salary FROM
Employees;
Or
SELECT * FROM Employees;prpared by Tilahun
Filter rows using a condition
(WHERE clause):
SELECT FirstName, LastName, Department
FROM Employees
WHERE Department = 'IT';
Display Employees with Salary
Greater than 50000
SELECT EmployeeID, FirstName,
LastName, Department, Salary
FROM Employees
WHERE Salary > 50000;
prpared by Tilahun
UPDATE Query Example
Let's assume you want to update the salary of
a specific employee, say John Doe, by
increasing it to 65000.
##Update the salary of an employee with EmployeeID =
1
UPDATE Employees
SET Salary = 65000
WHERE EmployeeID = 1;
You can update multiple columns at once, like so:
UPDATE Employees SET Salary = 65000,
Department = 'Engineering'
WHERE EmployeeID = 1;
prpared by Tilahun
DELETE Query Example
##Delete the employee with EmployeeID =
1 DELETE FROM Employees
WHERE EmployeeID = 1;
## Deletes all rows from the Employees
table (use with caution)
prpared by Tilahun
INSERT INTO Query
Example
INSERT INTO Employees (FirstName,
LastName, Department, Salary)
VALUES (‘john', ‘doe', ‘IT', 55000);
prpared by Tilahun
Unit Four:
Data query language
This unit is developed to provide you the
necessary information regarding the following
content
coverage and topics:
• Selection of data from a single table
• Selection of data from multiple tables
• Retrieval of data selectively
• Working with functions
• Working with sub-queries
prpared by Tilahun
Tables name Student, Course, and
Department.
example:
Student: Contains information about
students (e.g., StudentID, FirstName,
LastName, DepartmentID).
Course: Contains information about courses
(e.g., CourseID, CourseName,
DepartmentID).
Department: Contains information about
departments (e.g., DepartmentID,
DepartmentName).
prpared by Tilahun
1. Selection of Data from a
Single Table
To select all student data from the
Student table:
SELECT * FROM Student;
To select specific columns (e.g.,
FirstName and LastName) from
the Student table:
SELECT FirstName, LastName
FROM Student;
prpared by Tilahun
2. Selection of Data from Multiple Tables
prpared by Tilahun
3. Retrieval of Data Selectively
To retrieve students from the Student table where the
DepartmentID is 1 (for example, students in the IT
department):
SELECT StudentID, FirstName, LastName
FROM Student
WHERE DepartmentID = 1;
You can also use comparison operators:
SELECT FirstName, LastName
FROM Student
WHERE StudentID > 10;
Or combine conditions using AND, OR:
SELECT FirstName, LastName
FROM Student
WHERE DepartmentID =prpared
1 AND StudentID > 5;
by Tilahun
4. Working with Functions
SQL Server supports various
functions, such as aggregate
functions (COUNT, SUM, AVG, MAX,
MIN) and string manipulation
functions.
For example, to count how many
prpared by Tilahun
End
prpared by Tilahun