DBS Chapter Five
DBS Chapter Five
Introduction
to
SQL(Standard Query Language)
SQL is a nonprocedural language , it only require a user to specify what data to retrieve or modify
without specifying how to get those data
SQL is a widely used database language, providing means of data manipulation (store, retrieve,
update, delete) and database creation
T-SQL stands for Transact Structure Query Language which is a Microsoft product and is an
extension of SQL Language used in SQL Server .
Each statement requests a specific action from the DBMS, such as creating a new table,
retrieving data, or inserting new data into the database.
Categories of SQL
• DCL (Data Control Language): which defines the privileges granted to database users.
DDL and DCL statements are commonly used by a database designer and database
administrator for establishing the database structures.
10
The acronym CRUD refers to all of the major functions that need to be implemented in a
relational database application to consider it complete.
Each letter in the acronym can be mapped to a standard SQL statement: database
• A clause may specify the data to be acted upon by the statement, or provide
more detail about what the statement is supposed to do.
• Every clause also begins with a keyword, such as WHERE, FROM, INTO,
and HAVING. Some clauses are optional; others are required.
Syntax
CREATE DATABASE database_name
CREATE TABLE Statement
Syntax
CREATE TABLE table_name
(
column_name1 data_type,
column_name2 data_type,
column_name3 data_type,
....
)
IDENTITY) can be specified when a table is created with the CREATE TABLE statement or
after the table is created with the ALTER TABLE statement.
Example
CREATE TABLE CUSTOMER
(
CustomerId int PRIMARY KEY,
CustomerNumber int NOT NULL UNIQUE CHECK(CustomerNumber>0) ,
CustName varchar(25) NOT NULL,
CustFName varchar(25) NOT NULL,
CustGFName varchar(25) NOT NULL,
Country varchar(20) DEFAULT ‘Ethiopia‘,
Syntax
ALTER TABLE table_name
DROP COLUMN column_name;
Example
ALTER TABLE Customer
DROP COLUMN Email;
ALTER TABLE - ALTER/MODIFY COLUMN
Example For a table name sample1( sid , sname), When the table is created with sid a s a primary Key ,
primary key constraint and Clustered index are created with name PK_sample1.
To create a Clustered Index other than the primary key follow the following steps
1. Drop the primary key constraint and the index
IF (EXISTS(select * from sys.key_constraints where name = 'PK_sample1'))
ALTER table sample1 DROP PK_sample1
IF (EXISTS(select * from sys.indexes where name = 'PK_sample1'))
DROP INDEX PK_sample1 on sample1
2. Create the clustered index on the column that you want.
CREATE CLUSTERED INDEX IX_sname ON dbo.sample1 (sname);
3. Re-create the primary key
ALTER TABLE sample1
ADD CONSTRAINT PK_sample1 PRIMARY KEY (sid)
WHERE Syntax
SELECT column1, column2, ...
FROM table_name
WHERE condition;
Note: The WHERE clause is not only used in SELECT statements, it is also used in
INSERT, UPDATE and DELETE
Checks if the values of two operands are equal or not, if yes then condition becomes true.
=
Checks if the values of two operands are equal or not, if values are not equal then condition becomes true.
!=
Checks if the values of two operands are equal or not, if values are not equal then condition becomes true.
<>
Checks if the value of left operand is greater than the value of right operand, if yes then condition becomes
>
true.
Checks if the value of left operand is less than the value of right operand, if yes then condition becomes true.
<
Checks if the value of left operand is greater than or equal to the value of right operand, if yes then condition
>=
becomes true.
Checks if the value of left operand is less than or equal to the value of right operand, if yes then condition
<=
becomes true.
Checks if the value of left operand is not less than the value of right operand, if yes then condition becomes
!<
true.
Checks if the value of left operand is not greater than the value of right operand, if yes then condition
!>
becomes true.
25 Database Management Systems
Arithmetic Operators
Operator Description
AND
2 The AND operator allows the existence of multiple conditions in an SQL statement's WHERE clause.
ANY
3 The ANY operator is used to compare a value to any applicable value in the list as per the condition.
BETWEEN
4 The BETWEEN operator is used to search for values that are within a set of values, given the minimum value and the maximum value.
EXISTS
5 The EXISTS operator is used to search for the presence of a row in a specified table that meets a certain criterion.
IN
6 The IN operator is used to compare a value to a list of literal values that have been specified.
LIKE
7 The LIKE operator is used to compare a value to similar values using wildcard operators.
NOT
8 The NOT operator reverses the meaning of the logical operator with which it is used. Eg: NOT EXISTS, NOT BETWEEN, NOT IN, etc.
This is a negate operator.
OR
9 The OR operator is used to combine multiple conditions in an SQL statement's WHERE clause.
IS NULL
10 The NULL operator is used to compare a value with a NULL value.
UNIQUE
11 The UNIQUE operator searches every row of a specified table for uniqueness (no duplicates).
SELECT column_name(s)
FROM table_name
WHERE column_name IN (SELECT STATEMENT);
Syntax
SELECT column1, column2, ...
FROM table_name
WHERE columnN LIKE pattern;
Note: MS Access uses an asterisk (*) instead of the percent sign (%), and a question mark (?)
instead of the underscore (_).
The percent sign and the underscore can also be used in combinations!
WHERE CustomerName LIKE 'a%' Finds any values that start with "a"
WHERE CustomerName LIKE '%a' Finds any values that end with "a"
WHERE CustomerName LIKE '%or%' Finds any values that have "or" in any position
WHERE CustomerName LIKE '_r%' Finds any values that have "r" in the second position
WHERE CustomerName LIKE 'a_%' Finds any values that start with "a" and are at least 2 characters in
length
WHERE CustomerName LIKE 'a__%' Finds any values that start with "a" and are at least 3 characters in
length
WHERE ContactName LIKE 'a%o' Finds any values that start with "a" and ends with "o"
SELECT column_names
FROM table_name
WHERE column_name IS NOT NULL;
Use an ORDER BY clause in the main SELECT statement (outer query) not in subqueries
If a subquery (inner query) returns a null value to the outer query, the outer query will not return
any rows when using certain comparison operators in a WHERE clause.
A sub query can returns zero or one row(Single row subquery ), returns one or more
rows(Multiple row subquery), returns one or more columns (Multiple column subqueries), be
placed within another subquery (Nested subqueries), can reference one or more columns in the
outer SQL statement(Correlated subqueries)
The ORDER BY keyword is used to sort the result-set in ascending or descending order.
The ORDER BY keyword sorts the records in ascending order by default. To sort the records in
descending order, use the DESC keyword.
ORDER BY Syntax
UPDATE Syntax
UPDATE table_name
SET column1 = value1, column2 = value2, ...
WHERE condition;
The WHERE clause specifies which record(s) that should be updated.
Note: If the WHERE clause is omitted, all records in the table will be updated!
DELETE Syntax
To get the number of customers in each region ,zone and woreda we can use the
following SQL statements with group by clause
Example 2
SELECT dbo.REGION.RegionName,dbo.ZONE.ZoneName ,count(CustomerId)
FROM dbo.CUSTOMER INNER JOIN dbo.WOREDA
ON dbo.CUSTOMER.CustWoredaId = dbo.WOREDA.WoredaId INNER JOIN
dbo.ZONE ON dbo.WOREDA.WZoneId = dbo.ZONE.ZoneId INNER JOIN
dbo.REGION ON dbo.REGION.RegionId = dbo.ZONE.ZRegionID
GROUP BY REGION.RegionName,zone.ZoneName
ORDER BY REGION.RegionName, Zone.ZoneName ASC
true.
•For any given row, if that conditional statement is true, the value 0 will be assigned to Tax
•In any row for which the conditional statement is false, move on to the next WHEN/THEN ,the condition
checked EmpSalary > 600 and EmpSalary < 1650 will be checked if that condition is true 0.1* EmpSalary
– 60 will be assigned toTax
•And if it is not true .15 * EmpSalary - 142.5 will be assigned to Tax
•At the same time all this is happening, SQL is retrieving and displaying all the values in Employee table
Note:
CASE must include the following components: WHEN, THEN, and END. ELSE is an optional
component.
The query that defines the view can be from one or more tables or from other views in the current or
other databases.
Syntax
CREATE VIEW view_name AS
SELECT column1, column2, ...
FROM table_name
WHERE condition;
tblCOURSE(CourseId,CourseTitle,CourseCode,CrdtHrs)
tblENROLLMENT(EnrollId,CourseId,StudentID,DateofEnrollment,MidExResult,ProjectResult,FinalExResult)
CREATE VIEW VStudentEnroll AS
SELECT tS.StudentID,tS.StuName,tS.StuFname,tS.StuGFName,tS.StuGender,
tC.CourseTitle, tC. CrdtHrs,tE.MidExResult, tE.ProjectResult, tE.FinalExResult,
tE.MidExResult + tE.ProjectResult + tE.FinalExResult as TotalResult
FROM tblENROLLMENT tE
INNER JOIN tblSTUDENT tS ON tE.StudentID = tS.StudentID
INNER JOIN tblCOURSE tC ON tE.CourseId = tC.CourseId
User defined functions are objects that are stored in the database and avoid writing the same code over
and over again.
Once functions are created and stored in the database, they can be called any number of times
UDF allow to control what is the input and define the structure/type of output and also allow to decide
permissions to DB users.
SQL Server UDF are routines that accept parameters, perform an action, such as a complex calculation,
and return the result of that action as a value.
SQL Server scalar function takes one or more parameters and returns a single value.
Select dbo.getitemquantSum(1)