You are on page 1of 59

Chapter 3

SQL
Introduction
• Structured Query Language (SQL) is a query language
that is standardized for RDBMS.
• SQL Statements (commonly referred to as 'queries') are
run to retrieve or modify the requested information from
the database
• SQL supports:
• Data Definition Language (DDL), and
• Data Manipulation Language (DML)

Standard Query Language 2


SQL Data Definition Language (DDL)
Part of the SQL language that permits
database tables and constraints to be created,
modified or deleted.
◦ CREATE TABLE - creates a new database table.
◦ ALTER TABLE - alters (changes) a database table.
◦ DROP TABLE - deletes a database table.
◦ CREATE INDEX - creates an index (search key).
◦ DROP INDEX - deletes an index.
DDL statements are used for schema
definition of a relational database.

Standard Query Language 3


SQL Data Manipulation Language (DML)
It is part of the SQL syntax for executing
queries to insert, retrieve, update, or delete
records.
◦ INSERT INTO - inserts new data into a database table.
◦ SELECT - extracts data from a database table.
◦ UPDATE - updates data in a database table.
◦ DELETE - deletes data from a database table.
The four most common commands are also
known as SQL CRUD statements.

Standard Query Language 4


Schema Creation and Modification
• SQL statement that is used to create a new database and the
corresponding files for storing the database:
CREATE DATABASE <database_name>
• Schema is a concept that is used to group database objects
such as tables, constraints, views and permissions in the
same application.
• The syntax for the command is:
CREATE SCHEMA <schema_name> AUTHORIZATION <owner>

Standard Query Language 5


Table Creation and Modification
• The SQL statement that is used to specify a new relation
in a database:
CREATE TABLE <table_name> (
<column_name> <data_type> {column_constraint},
:
<column_name> <data_type> {column_constraint}
)

Standard Query Language 6


Create table syntax
• Creating the database
CREATE DATABASE <databaseName>
• Creating the tables
CREATE TABLE <tablename> (
<colName> <type> <null or not null> <other options>,
<colName> <type> <null or not null> <other options>,
<colName> <type> <null or not null> <other options>,
.
.
.
PRIMARY KEY(colName),
FOREIGN KEY (colName) REFERENCES <tableName>(<colname>)
ON DELETE
ON UPDATE
)

Standard Query Language 7


… Table Creation and Modification
• The primary key constraint in a relation is enforced by using
the key word PRIMARY KEY.
• The referential integrity constraint in a relational database is
implemented by the use of FOREIGN KEY.
• Referential trigged actions:
• ON DELETE {CASCADE | NO ACTION | SET DEFAULT | SET NULL}
• ON UPDATE {CASCADE | NO ACTION | SET DEFAULT | SET NULL }

Standard Query Language 8


Example
1. Create a database named employeeManagement
2. Create table named employee. The table has the following columns
empId: Which is integer auto increment and primary key
name: varchar of length 100 and not null
sex: has only two values Male and Female and not null,
bDate: has dateime type and not null ,
address varchar of length 50 and not null,
position varchar of length 20 and not null,
salary double and not null.
3. Create table overtime, The table has the following columns
employeeId: integer foreign key that references empId of employee table. When a
record is updated or deleted from employee it should be cascaded to overtime
table
hours: of type double and not null
overtimeId: Which is integer auto increment and primary key

Standard Query Language 9


… Table Creation and Modification
• The ALTER TABLE command allows modification (adding,
changing, or dropping) of a column or constraint in a
table.
ALTER TABLE <table_name>
[ALTER COLUMN <column_name> <new_data_type>] |
[ADD <column_definition> | <constraint>] |
[DROP <column_name> | < constraint>]

Standard Query Language 10


… Example
• Adding constraints
• Key Constraint
ALTER TABLE [Emplyees] WITH NOCHECK ADD
CONSTRAINT [PK_Emplyees] PRIMARY KEY CLUSTERED
(
[empId]
)
• Foreign Key Constraint (Relationship)
ALTER TABLE [Receipts] ADD
CONSTRAINT [FK_Receipts_Employees] FOREIGN KEY
(
[empId]
) REFERENCES [Employees] (
[empId]
)

Standard Query Language 11


… Example
• Adding constraints
• Default Constraint
ALTER TABLE Emplyees] ADD
CONSTRAINT [DF_Emplyees_salary] DEFAULT
(
0
) FOR [salary]
• Unique Constraint
ALTER TABLE [Resources] ADD
CONSTRAINT [UQ_Resources_stockNo] UNIQUE NONCLUSTERED
(
[stockNo], [regDate]
)

Standard Query Language 12


INSERT, UPDATE and DELETE
• The INSERT statement
• Syntax
INSERT INTO <table_name>| <view_name> [(column_list)] data_values
• There are two ways to specify the data values:
VALUES (<value_or_expression> [,..n])
SELECT <subquery>

Standard Query Language 13


INSERT, UPDATE and DELETE
• The UPDATE statement
• Syntax
UPDATE <table_name>
SET <column_name> = <value> [,..n]
WHERE <condtion>

• The DELETE statement


• Syntax
DELETE FROM <table_name>| <view_name>
WHERE <condtion>

Standard Query Language 14


… Example
• Insert
INSERT INTO [HHOffFurn].[dbo].[Emplyees]([name], [sex], [bDate], [address],
[salary])
VALUES(‘AAA’, ‘M’, ‘02-02-1978’, ‘ ’, 750)

• Update
UPDATE [Emplyees] SET [name]=‘BBB', [empDate]='1-1-2001'
WHERE [empID] = 1

• Delete
DELETE FROM [Emplyees]
WHERE [empID] = 1

Standard Query Language 15


Example
1. Insert the following rows in employee table
Name Sex bDate Address Position salary
Alen Male ‘1993-01-23’ A.A Manager 25000
Alice Female ‘1995-05-27’ Adama Manager 25000
Brian Stive Male ‘1985-07-23’ A.A Engineer 50000

2. Insert the following rows in overtime table


employeeId hours
1 10.6
2 6
3 7

Database systems (Biruk.A) 16


Example…
1. Change ‘Alen’ in the employee table to ‘Alen Harper’,
change the birth day of ‘alice’ to ‘1998-07-03’
2. Delete the row of ‘alen’

Database systems (Biruk.A) 17


SQL data retrieval query
SELECT-FROM-WHERE Statement
The SELECT-FROM-WHERE Statement is data
reading query
Simplest Syntax
SELECT <column_list>
FROM <table_list>
WHERE <condition>

The DISTINCT key word on the SELECT clause:


SELECT DISTINCT <column_list>

The LIKE key word for test of string pattern:


S LIKE P
S NOT LIKE P

Standard Query Language 19


… Example
• Select
• All Data
SELECT [empId], [name], [sex], [bDate], [address], [empDate], [position],
[salary]
FROM [Emplyees]
• Single Data
SELECT [empId], [name], [sex], [bDate], [address], [empDate], [position],
[salary]
FROM [Emplyees]
WHERE [empId] = 1

Standard Query Language 20


WHERE CLAUSE COMPARISION OEPRATORS
• =,<,>, !=,<=,>=
• AND, OR, NOT,
• LIKE..
EXAMPLE:
SELECT * FROM products
WHERE products.buyPrice >=50 AND
products.quantityInStock > 10

Database systems (Biruk.A) 21


SQL LIKE operator
• Allows to search for string of text based on specified pattern
• Patterns are expressed using wildcard characters (% and _)
• % matches a sequence of any character including space
• _ matches any single character
• Example:
SELECT lastname, firstname
FROM employees
WHERE lastname LIKE ‘D%’
• D% matches any string that starts with D
• %d mathes any string that ends with d
• %da% matches any string that contains da in between
Database systems (Biruk.A) 22
Examples
1. Select all from customers
2. Select all from customers where customerNumber=103
3. Select productCode, productName, productVendor
from product where the buyPrice is greater than
50.00 and quantityInStock less than 5000
4. Select firstName, lastName of all employees whose first
name starts with b

Database systems (Biruk.A) 23


Nested Subqueries and Complex
Queries
Subqueries
• Subqueries can be used in different ways:
• In the WHERE clause to form nested queries,
• In set operations such as UNION, EXCEPT, …, and
• In the FROM clause as constant table
• Constant tables: has at most one row value

Standard Query Language 25


Nested Queries
 SQL SELECT statements can be contained in the WHERE
clause of another SQL statement to form Nested queries.
 The SELECT statement that contains the nested query is said
to be the outer query.
 Subqueries in a nested SQL statement can produce scalar
value (constant) or table.
 TEST Operators in subquery:
◦ IN: operator allows you to specify multiple values in where clause,
similar to multiple OR conditions
◦ ALL: returns true if all of the sub-query values fulfill the condition
◦ ANY: returns true if any one of the sub query values fulfill the condition
◦ EXISTS: returns true when the subquery returns at least one row

Standard Query Language 26


Nested Queries
• Example
1. SELECT customers.customerNumber, customers.customerName
FROM customers
WHERE
EXISTS(SELECT orders.orderNumber FROM orders WHERE
orders.customerNumber=customers.customerNumber)
2. SELECT * FROM customers
WHERE customers.country IN ('Germany','France','UK')

Standard Query Language 27


SET Operation of Queries
 The set operations union, intersection and difference
(UNION, INTERSECT and EXCEPT) can be used in SQL
statements that will consist of two subqueries as the
operations are binary.
 Syntax
(Subquery 1)
UNION | INTERSECT | EXCEPT |
(Subquery 2)
 The set operators do not include duplicate in the resulting
table. If all the resulting rows are to be retrieved the ALL
operator is used with the set operators to prevent duplicate
elimination.

Standard Query Language 28


Joined Tables
• Reading data from more than one table with the use of
joined tables in the FROM clause.
• Cross Product
<left_table> CROSS JOIN <right_table>
• Natural Join
<left_table> NATURAL JOIN <right_table>
• Theta Join
<left_table> JOIN <right_table> ON<condition>
• Outer Join
<left_table> [RIGHT | LEFT | FULL] OUTER {NATURAL} JOIN <right_table>
{ON<condition>}

Standard Query Language 29


Join operations from w3schools website

Database systems (Biruk.A) 30


Examples
1. SELECT * FROM customers CROSS JOIN employees
Cartesian product
SELECT * FROM customers JOIN employees
2. SELECT * FROM customers NATURAL JOIN employees
join two tables on columns with the same name and
data type
3. SELECT * FROM customers INNER JOIN payments
ON customers.customerNumber= payments.customerNumber

Database systems (Biruk.A) 31


Ordering Query Results
• To specify the order in which the resulting table is
organized, the ORDER BY clause is used in the
statement.
• Syntax:
SELECT <column_list>
FROM <table_list>
WHERE <condition>
ORDER BY {<order_column> [ASC | DESC]}[,..n]

Standard Query Language 32


Aggregate Function in SQL
 SQL allows grouping of resulting rows in a query so that
aggregate functions can be applied to make analysis and
summary.
 The aggregate functions supported by the SQL statement are:
◦ Summation
SUM (<column_name>)
◦ Average
AVG (<column_name>)
◦ Minimum
MIN (<column_name>)
◦ Maximum
MAX (<column_name>)
◦ Count
COUNT (<column_name> | *)

Standard Query Language 33


Grouping in SQL Statement
• The GROUP BY clause is used after the WHERE clause to
group the result of the SQL statement.
• Syntax:
GROUP BY <group_column>[,..n]
HAVING <condition>
• The columns that can be included in the HAVING clause
are:
• Aggregated column from the FROM clause tables, or
• Unaggregated columns from the GROUP BY list

Standard Query Language 34


Grouping in SQL Statement
• A query that counts the number of teams a given Project
is having
SELECT p.Name, COUNT(t.Name) AS NoOfTeams
FROM Projects p JOIN Teams t ON p.PrjId=t.PrjId
GROUP BY p.Name

Standard Query Language 35


Grouping in SQL Statement
• To add on a condition for grouping such as only projects
that are having teams more than 2.
SELECT p.Name, COUNT(t.Name) AS NoOfTeams
FROM Projects p JOIN Teams t ON p.PrjId=t.PrjId
GROUP BY p.Name
HAVING COUNT(t.Name)>2

Standard Query Language 36


Grouping in SQL Statement
• For only the projects that are having a name starting with
‘A’, the query can be written as:
SELECT p.Name, COUNT(t.Name) AS NoOfTeams
FROM Projects p JOIN Teams t ON p.PrjId=t.PrjId
GROUP BY p.Name
HAVING p.Name LIKE ‘A%’

Standard Query Language 37


Summary of SQL Statement
• In summary the general form the SELECT statement is as
follows
SELECT select_list
FROM table_source
[WHERE search_condition]
[GROUP BY group_by_expression]
[HAVING search_condition]
[ORDER BY order_expression [ASC | DESC] ]

Standard Query Language 38


Examples
1. SELECT CONCAT(employees.firstName, ',',employees.lastName) AS fullName
FROM employees
ORDER BY employees.firstName
DESC
LIMIT 10
2. SELECT SUM(products.quantityInStock) AS totalStock FROM products
3. SELECT DISTINCT COUNT(customers.customerName) FROM customers

Database systems (Biruk.A) 39


Views
• View in the context of SQL is a virtual table that is
derived from one or more tables in an alternative way.
• Syntax
CREATE VIEW <view_name>
AS <select_statement>
• Views as the database objects can also be dropped using
the DROP statement as follows:
DROP VIEW <view_name>

Standard Query Language 40


Example
Create view using the following query
1.SELECT CONCAT(employees.firstName,
',',employees.lastName) AS fullName
FROM employees
ORDER BY employees.firstName
DESC
LIMIT 10

Database systems (Biruk.A) 41


Advanced SQL concepts

Database systems (Biruk.A) 42


Outline
• Functions and procedures
• Triggers
• Authorization

Database systems (Biruk.A) 43


Functions and procedures
• Functions:
• We have seen some predefined functions like sum, average,
count
• Functions map input to some output
• Return single value
• Now, what if we want custom functions other than the
predefined functions?
• Allow business logic to be implemented in a database
• Implement business rules such as: maximum number of
courses that can be taken by a student in a semester

Database systems (Biruk.A) 44


Functions
• Syntax
CREATE FUNCTION function_name(param1 <datatype>, param2,…)
RETURNS <datatype>
[NOT] DETERMINISTIC (Returns the same value for same parameter)
<LIST OF STATEMENTS>
• Example:
Function that prepends “Hello” to a name
CREATE FUNCTION hello (s VARCHAR(20))
RETURNS VARCHAR(50) DETERMINISTIC
RETURN CONCAT(‘Hello ‘,’ ’,s);
• To execute a function:
>> SELECT hello(‘biruk’)
Hello, biruk

Database systems (Biruk.A) 45


Functions…
• May contain some control statements
DELIMITER $$
CREATE FUNCTION computeLevel(value double) RETURNS VARCHAR(10) DETERMINISTIC
BEGIN
DECLARE level VARCHAR(10);
IF value>=50000 THEN
SET level=‘gold’;
ELSE IF (value < 50000 AND value >= 20000) THEN
SET level=‘silver’;
ELSEIF value<20000 THEN
SET level=‘bronth’;
ENDIF;
RETURN (level);
END
DELIMITER ;

Database systems (Biruk.A) 46


Procedures
• Contains set of SQL statements executed together when a
procedure is called
• contains
• Name
• List of parameters
• SQL statements
• A method to encapsulate repetitive tasks

Database systems (Biruk.A) 47


Procedures syntax
DELIMITER $$
CREATE PROCEDURE <procedureName> ()
DETERMINISTIC
SQL SECURITY DEFINER <optional>
BEGIN
//set of SQL statemetns
END$$
DELIMITER ;
Calling stored procedure
CALL <procedure_name>(<parametres>….);
Database systems (Biruk.A) 48
Procedure with parameters
• CREATE PROCEDURE proc1 () : Parameter list is empty
• CREATE PROCEDURE proc1 (IN varname <DATA-TYPE>) : One input parameter.
The word IN is optional because parameters are IN (input) by default.
• CREATE PROCEDURE proc1 (OUT varname <DATA-TYPE>) : One output
parameter.
• CREATE PROCEDURE proc1 (INOUT varname <DATA-TYPE>) : One parameter
which is both input and output
• You can also define multiple parameters separated by comma
• Example:
DELIMITER $$
CREATE PROCEDURE `proc_OUT` (OUT var1 VARCHAR(100))
BEGIN
SET var1 = 'This is a test';
END $$

Database systems (Biruk.A) 49


Local variables and other control statements

• Declare inside BEGIN and END statement


DECLARE a, b INT DEFAULT 5;
• To set a variable use
SET a=10;
• You can also use IF, ELSEIF, CASE….WHILE
• Example:
1. Write procedure called expensiveProducts that
returns the name and buyprice of top 10 products with
highest buyprice
Database systems (Biruk.A) 50
Advantages of stored procedures
• Pros
• Ideal when a database is accessed from different applications
• Provide security mechanism
• Improve performance by reducing network traffic
• Prevent users from directly accessing tables
• Cons
• Increase load on database server
• Difficult when migrating to different DBMS

Database systems (Biruk.A) 51


Triggers
• Trigger: a statement that the system executes automatically as a side
effect of a modification to the database
• A trigger is defined to activate when a statement inserts, updates, or
deletes rows in the associated table
• To implement Trigger
• Specify when the trigger is executed
• Event
• Condition
• Specify the action taken when the trigger is executed
• Need for triggers
• Implementing custom constraints
• Alerting users
• Starting tasks automatically

Database systems (Biruk.A) 52


Trigger syntax
• CREATE TRIGGER <name> <action time> <operation> ON <tablename>
<statements to be executed>;
• Action time: BEFORE, AFTER
• Operation: INSERT, UPDATE, DELETE
Example: A trigger that checks age before inserting in to a table
DELIMITER $$
CREATE TRIGGER checkAge BEFORE INSERT ON person
FOR EACH ROW
BEGIN
IF NEW.age < 0 THEN
SET NEW.age = 0;
END IF;
END; $$
DELIMITER ;

NOTE THAT NEW: keyword represents the new row to be inserted, used only with BEFORE
OLD: keyword that represents the row which was modified, used with AFTER

Database systems (Biruk.A) 53


Triggers…
• Pros
• Alternative method for implementing referential integrity
• Easy to implement and maintain business rules
• Used for calling procedures, good to use them with procedures
• Cons
• May decrease performance of the database
• Application programmers may not have full control
• Difficult to keep track of triggers and find bugs on them

Database systems (Biruk.A) 54


Authorization
• Assign users several forms of authorization on parts of
the database
• To read data
• To insert new data
• Update data
• Delete data
• Authorization is granting privilege for the above database
operations
• We can give privilege to some, all or none of the above
privileges
• One way to maintain security and integrity of database

Database systems (Biruk.A) 55


Authorization…
• You can also specify column list in a table the user can
insert
• Example: GRANT UPDATE (budget) ON department TO alemu
• The user name PUBLIC represents all current and future
users of the database
• To revoke privilege
REVOKE UPDATE ON department FROM alemu
• Any user who has privilege can not further grant the
same privilege to other users by default

Database systems (Biruk.A) 56


Authorization…
• Supported privileges in SQL standard are SELECT,
INSERT, UPDATE, DELETE and ALL PRIVILAGES
• System administrator creates user accounts and grants
privileges to other users
• SYNTAX
GRANT <privilege list>
ON <relation name or view name>
TO <user lists>
• Example:
GRANT INSERT ON department TO alemu, abebe, eleni;

Database systems (Biruk.A) 57


Roles
• It is difficult to assign privileges to every user of the
system
• Create role for users and grant the privilege to the role
• Users are assigned for each role
• Example:
• Admin: grant all privileges
• Instructor: grant insertion of student record
• Registrar: grant update of student record
• Then assign users to either of the created roles

Database systems (Biruk.A) 58


Roles
• Syntax
CREATE ROLE instructor;
GRANT INSERT ON grades TO instructor
• Roles are also granted to other roles

Database systems (Biruk.A) 59

You might also like