You are on page 1of 73

Unit Four

Basic Structured Query Language (SQL)

By: Araya M. (MPH-HI, Ass. Prof.)


June, 2021

08/11/2022 Araya Mesfin (MPH-HI) UoG 1


Introduction
What is Relational Database Management System (RDBMS)?

• Databases and database technology have had a major impact on the growing
use of computers.

• Databases play a critical role in almost all areas where computers are used

• RDBMS is a database management system that is based on the relational


model as introduced by E. F. Codd

• RDBMS is the basis for SQL and for all modern database systems

08/11/2022 2
Araya Mesfin (MPH-HI) UoG
Introduction
SQL RDBMS Concepts cont’d…cont’d…
What is the difference between table and relation?

A table is a collection of related data entries

A table consists of columns and rows

The data in RDBMS is stored in database objects called tables

A table is the most common and simplest form of data storage in a relational
database
08/11/2022 3
Araya Mesfin (MPH-HI) UoG
SQL RDBMS Concepts cont’d…
CUSTOMERS table

08/11/2022 4
Araya Mesfin (MPH-HI) UoG
Structured Query Language (SQL)
It is the standard language for relational database management systems

It is a language that communicates with databases

It is mainly used to create, insert, search, update, delete database records

It also allows the management of information inside the databases

SQL uses terms such as: table, row, and column for the formal relational
model terms relation, tuple, and attribute, respectively

08/11/2022 5
Araya Mesfin (MPH-HI) UoG
What can SQL do?
SQL can:
execute queries against a database

retrieve data from database

insert records in a database table

update records in a database table

delete records from a database table

create new databases

create new tables in a database


08/11/2022 6
Araya Mesfin (MPH-HI) UoG
What can SQL do cont’d…
create views in a database

set permissions on tables, procedures, and views

provides a fixed and variable set of data types in particular for


strings of different length e.g. char(n), varchar(n)

08/11/2022 7
Araya Mesfin (MPH-HI) UoG
Tips on SQL
• Use one line per column (attribute) definition

• Use spaces to line up the attributes

• Table and attribute names are capitalized

• i.e. we can mix uppercase and lowercase when referencing SQL keywords
(such as SELECT and INSERT)

• For most systems SQL commands are not case sensitive

• However, case does matter when referring to the contents of a column

• Before we can create a table we have to create a database

• Primary key attribute names contain both NOT NULL and a UNIQUE
specification
08/11/2022 8
Araya Mesfin (MPH-HI) UoG
Tips on SQL cont’d…
• The basic structure of an SQL expression consists of three clauses: select, from,
and where

• SQL uses the terms table, row, and column for the formal relational model
terms relation, tuple, and attribute respectively

• The main SQL command for data definition is the CREATE statement

• SQL can also be used to create tables (relations) and domains (as well as other
constructs such as views)

• RDBMS will automatically enforce referential integrity for foreign keys

• Every SQL statement is terminated by a semicolon


08/11/2022 9
Araya Mesfin (MPH-HI) UoG
Specifying the data type of a column
We have to use data types while creating database tables, choose a particular
data type for a table column based on your requirement

A data type defines what kind value a column can contain,

Data type selection is usually dictated by nature of data and by intended use

Pay close attention to expected use of attributes for sorting and data retrieval
purposes

When defining a column, you should always set its name and associated
domain or data type

The domain and data type limit the information that the column can accept
08/11/2022 10
Araya Mesfin (MPH-HI) UoG
Data types cont’d…

08/11/2022 11
Araya Mesfin (MPH-HI) UoG
Basic SQL constraints
Constraints are used to enforce valid data in columns

NOT NULL - Ensures that a column cannot have a NULL value

UNIQUE - Ensures that all values in a column are different

PRIMARY KEY - A combination of a NOT NULL and UNIQUE ...

FOREIGN KEY - Uniquely identifies a row/record in another table

CHECK – validates data when an attribute value is entered


08/11/2022 12
Araya Mesfin (MPH-HI) UoG
Activity
 Fill the EMPLOYEE table below (the data type, size and constraint as you
feel when appropriate)
Field Type Data Type Field Size Constraint
EmpID
FName
LName
Age
Date of Birth
Qualification
Address
City
Salary
Email address
08/11/2022 13
Araya Mesfin (MPH-HI) UoG
Classifications of SQL commands
SQL has different types of statements (commands) that you can use in
managing a database

Commands can be classified into groups based on their nature

SQL commands are divided into four subgroups, DDL, DML, DCL, and TCL

08/11/2022 14
Araya Mesfin (MPH-HI) UoG
Classifications of SQL commands cont’d….
1. Data Definition Language (DDL)
 DDL deals with database schemas and descriptions, of how the data should
reside in the database

 These statements allow you to generate, delete, or modify database objects

 The most important Commands and Operations in DDL are:

 CREATE: used for creating a database and its objects (Like: table, index, views, store)

 ALTER: alters the structure of the existing database.

 DROP: delete objects from the database

 TRUNCATE TABLE: removing all records from a table, including all spaces
allocated for the records are removed
 RENAME: rename database objects
08/11/2022 15
Araya Mesfin (MPH-HI) UoG
Classifications of SQL commands cont’d….
• CREATE TABLE is the keyword telling the DB system what you want to do
• It can be used to create schemas, tables, types, views, and domains
Syntax 

Each field in the CREATE TABLE has three parts:

• ColumnName

• Data type

• Column Constraint (Optional)


08/11/2022 16
Araya Mesfin (MPH-HI) UoG
Classifications of SQL commands cont’d….
Example 1:

Create table STUDENT(

StudID varchar (25) primary key,

Sname varhar (15),

Gender varchar (1) check (Gender in (‘F’,’M’)) ,

DOB date,

Avg_Score Decimal (3,2));

Execution of the above DDL statement creates the STUDENT table


08/11/2022 17
Araya Mesfin (MPH-HI) UoG
Classifications of SQL commands cont’d….
2. Data Manipulation Language (DML)

 Allows users to add, modify, delete or retrieve information stored inside your
database entries

INSERT: Insert one or more rows from a table or views (creates a record)

SELECT: retrieves one or more rows from a table or views

UPDATE: changes existing data in a table or view (modifies record)

DELETE: removes one or more rows from a table or view (deletes a record)

08/11/2022 18
Araya Mesfin (MPH-HI) UoG
Classifications of SQL commands cont’d….
• The INSERT INTO statement is used to add new data to a database.

• INSERT INTO can contain values for some or all of its columns

• It is possible to write the INSERT INTO statement in two ways:

o The first way specifies both the column names and the values to be
inserted

08/11/2022 19
Araya Mesfin (MPH-HI) UoG
Classifications of SQL commands cont’d….
The second way, if you are adding values for all the columns of the table, you
do not need to specify the column names in the SQL query

• However, make sure the order of the values is in the same order as the
columns in the table.

• The INSERT INTO syntax would be as follows:

08/11/2022 20
Araya Mesfin (MPH-HI) UoG
Classifications of SQL commands cont’d….
• SELECT: the SELECT statement is used to select data from a database.

• The data returned is stored in a result table, called the result-set

SELECT Syntax

• Here, column1, column2, ... are the field names of the table you want to select
data from.

• If you want to select all the fields available in the table, use the following
syntax:

08/11/2022 21
Araya Mesfin (MPH-HI) UoG
Classifications of SQL commands cont’d…
Example1:
Select StudID, Sname, Avg_Score
from STUDENT
 The query displays StudID, Sname, Avg_Score from STUDENT table
Example1:
Select *
from STUDENT
where sex= ‘F’

 The query display only female students with all the fields name from STUDENT
table
08/11/2022 22
Araya Mesfin (MPH-HI) UoG
Classifications of SQL commands cont’d….
3. Data Control Language (DCL)

 Which defines the privileges granted to database users.

 Or it is a statement used to control the access of the data stored in the


database and provide data security.

GRANT: used to provide any user access privileges or other privileges


for the database a privilege to user

REVOKE: removes a previously granted or denied permission (i.e.


takes back privilege granted from the user)

08/11/2022 23
Araya Mesfin (MPH-HI) UoG
Classifications of SQL commands cont’d….
4. Transaction Control Language (TCL)

It is used to perform some operations (transactions like insert, delete and
update). i.e. it is used to manage the changes made by DML statements

The DML operations are used to control the data in the table.

COMMIT: ends the transaction with success and makes updates


permanent (command is used to permanently save any transaction into
the database)

ROLL BACK: the command restores the database to last committed state
08/11/2022 24
Araya Mesfin (MPH-HI) UoG
Classifications of SQL commands cont’d….
Note 1: Saving table changes made to table contents are not physically saved
on disk until, one of the following occurs:

• Database is closed

• Program is closed

• COMMIT command is used

Syntax: COMMIT [WORK];

• Will permanently save any changes made to any table in the database

08/11/2022 25
Araya Mesfin (MPH-HI) UoG
Classifications of SQL commands cont’d….
Note 2: Restoring table contents

• ROLLBACK

• Used to restore database to its previous condition

• Only applicable if COMMIT command has not been used to


permanently store changes in database

Syntax:

• ROLLBACK;

• COMMIT and ROLLBACK only work with data manipulation commands


that are used to add, modify, or delete table rows

08/11/2022 26
Araya Mesfin (MPH-HI) UoG
08/11/2022 Araya Mesfin (MPH-HI) UoG 27
N.B: 1) The create database statement is used to create a new database

Syntax: create database <Database_name>

2) To change the database name (Rename the database name)

Syntax: Alter database <old_database_name> modify name=


<new_databse_name>;

Example: Alter Database ABCED modify name=HELLO;

3. To rename table name

Syntax: EXEC SP_rename ‘Old_table_name’, ‘new_table_name’;

4. To rename a column name

Syntax: EXEC SP_rename ‘table_name.old_column_name’, ‘new_column_name’;


08/11/2022 Araya Mesfin (MPH-HI) UoG 28
08/11/2022 Araya Mesfin (MPH-HI) UoG 29
08/11/2022 Araya Mesfin (MPH-HI) UoG 30
Example

08/11/2022 Araya Mesfin (MPH-HI) UoG 31


08/11/2022 Araya Mesfin (MPH-HI) UoG 32
08/11/2022 Araya Mesfin (MPH-HI) UoG 33
Two different techniques of adding a primary key constraint during a single
table creation

08/11/2022 Araya Mesfin (MPH-HI) UoG 34


Adding two fields as a primary key constraint during a single table creation

08/11/2022 Araya Mesfin (MPH-HI) UoG 35


Adding a primary key constraint after creating a single table
using ALTER command

08/11/2022 Araya Mesfin (MPH-HI) UoG 36


The following are examples of multiple tables with out relationship

08/11/2022 Araya Mesfin (MPH-HI) UoG 37


Adding a foreign key constraint during the table creation process

08/11/2022 Araya Mesfin (MPH-HI) UoG 38


08/11/2022 Araya Mesfin (MPH-HI) UoG 39
08/11/2022 Araya Mesfin (MPH-HI) UoG 40
08/11/2022 Araya Mesfin (MPH-HI) UoG 41
08/11/2022 Araya Mesfin (MPH-HI) UoG 42
08/11/2022 Araya Mesfin (MPH-HI) UoG 43
08/11/2022 Araya Mesfin (MPH-HI) UoG 44
08/11/2022 Araya Mesfin (MPH-HI) UoG 45
08/11/2022 Araya Mesfin (MPH-HI) UoG 46
08/11/2022 Araya Mesfin (MPH-HI) UoG 47
08/11/2022 Araya Mesfin (MPH-HI) UoG 48
08/11/2022 Araya Mesfin (MPH-HI) UoG 49
Examples

08/11/2022 Araya Mesfin (MPH-HI) UoG 50


SQL Operators

Important categories of SQL operators are:

1. Arithmetic operators

2. Comparison operators

3. Logical Operators

08/11/2022 Araya Mesfin (MPH-HI) UoG 51


Athematic Operators
+ Add
_ Subtraction
* Multiply
/ Division
% Modules

08/11/2022 Araya Mesfin (MPH-HI) UoG 52


Examples
i) + ( Add)
Select 30+20;
ii) _ (Subtraction)
Select 30-20;
iii) * (Multiply)
Select 30 *20;
iv) / (Division)
Select 30 *20;
v) % (Modules)
8%3
08/11/2022 Araya Mesfin (MPH-HI) UoG 53
08/11/2022 Araya Mesfin (MPH-HI) UoG 54
08/11/2022 Araya Mesfin (MPH-HI) UoG 55
08/11/2022 Araya Mesfin (MPH-HI) UoG 56
08/11/2022 Araya Mesfin (MPH-HI) UoG 57
08/11/2022 Araya Mesfin (MPH-HI) UoG 58
08/11/2022 Araya Mesfin (MPH-HI) UoG 59
08/11/2022 Araya Mesfin (MPH-HI) UoG 60
08/11/2022 Araya Mesfin (MPH-HI) UoG 61
Aggregate Functions
Aggregate functions perform a calculation on a set of values and return a
single value.

With the exception of the COUNT aggregate function, all other aggregate
functions ignore NULL values

Are frequently used with the GROUP BY clause of the SELECT statement

Are used to summarize information from multiple tuples into a single-


tuple summary

08/11/2022 62
Araya Mesfin (MPH-HI) UoG
Aggregate Function cont’d….
The functions SUM, MAX, MIN, and AVG can be applied to a set or multi
set of numeric values and return, respectively, the sum, maximum value,
minimum value, and average (mean) of those values.

These functions can be used in the SELECT clause or in a HAVING clause

The functions MAX and MIN can also be used with attributes that have
nonnumeric domains if the domain values have a total ordering among
one another.

08/11/2022 Araya Mesfin (MPH-HI) UoG 63


Aggregate Function cont’d…..
Find the sum of the salaries of all employees, the maximum salary, the
minimum salary, and the average salary.

SELECT SUM(Salary),MAX(Salary),MIN(Salary),AVG(Salary)
FROM EMPLOYEE;

08/11/2022 64
Araya Mesfin (MPH-HI) UoG
Aggregate Function cont’d…..
Retrieve the total number of employees in the company and the number of
employees in the ‘Research’ department.
SELECT COUNT(*)
FROM EMPLOYEE;

SELECT COUNT(*)
FROM EMPLOYEE, DEPARTMENT
WHERE DNO=DNUMBER AND DNAME=‘Research’;

08/11/2022 Araya Mesfin (MPH-HI) UoG 65


Aggregate Function cont’d…..
• Count the number of distinct salary values in the database.
SELECT COUNT(DISTINCT Salary)
FROM EMPLOYEE;

• If we write COUNT(SALARY) instead of COUNT(DISTINCT SALARY), then


duplicate values will not be eliminated.

• However, any tuples with NULL for SALARY will not be counted. In general,
NULL values are discarded when aggregate functions are applied to a particular
column (attribute)

08/11/2022 Araya Mesfin (MPH-HI) UoG 66


Aggregate Function cont’d…..
GROUP BY and HAVING Clauses
The GROUP BY clause is used to create one output row per each group

Produces summary values for the selected columns, which should also appear
in the SELECT clause,

For each department, retrieve the department number, the number of


employees in the department, and their average salary.
SELECT Dno, COUNT(*),AVG(Salary)
FROM EMPLOYEE
GROUP BY Dno;
08/11/2022 67
Araya Mesfin (MPH-HI) UoG
Aggregate Function cont’d…..
•The GROUP BY statement is often used with aggregate functions (COUNT,
MAX, MIN, SUM, AVG) to group the result-set by one or more columns.

GROUP BY Syntax

SELECT column_name(s)
FROM table_name
WHERE condition
GROUP BY column_name(s)
ORDER BY column_name(s);

08/11/2022 Araya Mesfin (MPH-HI) UoG 68


Aggregate Function cont’d…..
•MAX ( ) Syntax

• SELECT MAX(column_name)
FROM table_name
WHERE condition;

COUNT ( ) Syntax

SELECT COUNT(column_name)
FROM table_name
WHERE condition;

 Count (Distinct field) displays the number of unique values in the specified
field, taken only from the records returned

08/11/2022 Araya Mesfin (MPH-HI) UoG 69


Aggregate Function cont’d…..
The HAVING clause can be used to restrict rows.
It is similar to the WHERE condition except HAVING can include the
aggregate
HAVING Syntax
SELECT column_name(s)
FROM table_name
WHERE condition
GROUP BY column_name(s)
HAVING condition
ORDER BY column_name(s);
SQL HAVING Examples
•The following SQL statement lists the number of customers in each country
•Only include countries with more
08/11/2022 Arayathan 5 customers
Mesfin (MPH-HI) UoG 70
Aggregate Function cont’d…..
Example

SELECT COUNT(CustomerID), Country


FROM Customers
GROUP BY Country
HAVING COUNT(CustomerID) > 5
ORDER BY COUNT(CustomerID) DESC;

08/11/2022 Araya Mesfin (MPH-HI) UoG 71


Aggregate Function Summary

08/11/2022 72
Araya Mesfin (MPH-HI) UoG
Thank You!

Thank You!!!

You might also like