You are on page 1of 61

Chapter 3: Structured Query

Language (SQL)

Fundamentals of Database Systems


for 2nd year Computer Science students.

Prepared by: Gebriye Embafresu


- Huawei HCIA Security Certified
- Huawei HCIA Datacom Certified
- Huawei HCIP Datacom Certified

Computer Science Department

E-mail: gebriye14@gmail.com
Outline
• Introduction to SQL
• SQL Statements
• Data Definition Language SQL Statements
• Data Manipulation Language SQL Statements
• SQL Constraints
• SQL Data Types
• Grant and Invoke SQL Statements
• SQL functions
• What is SQL Injection?
• and how to secure the database

(C) 2016, Gebriye E. Dept. Computer Science HCIA Security, HCIA R&S and HCIP R&S Certified 6-2
Introduction to SQL
• The full form of SQL is Structured Query Language

• It is the language used to communicate with the database

• SQL is used by all major relational database systems like


MySQL, PostgreSQL, SQL Server, IBM DB2, Oracle etc.
• SQL was initially developed at IBM (1970’s) by Donald
Chamberlin and Raymond Boyce. Initially it was called as “
Structured English Query Language” (SEQUEL) and
pronounced as “sequel”

(C) 2016, Gebriye E. Dept. Computer Science HCIA Security, HCIA R&S and HCIP R&S Certified 1-3
Introduction to SQL (Contd.)
• SQL is ANSI standard: American National Standards Institute
Standard
• SQL is composed of commands that enable users to create
database and table structures, perform various types of data
manipulation and data administration, and query the database
to extract useful information.
• SQL is a standard way to query/ obtain/ add/delete/modify
the data in a database.

(C) 2016, Gebriye E. Dept. Computer Science HCIA Security, HCIA R&S and HCIP R&S Certified 1-4
Introduction to SQL (Contd.)
• SQL used by Academician’s, Data Scientist, Machine
learning Engineers, Software Engineers, etc.
• SQL is not general purpose programming language, like
C/C++/JAVA/Python, are general purpose programming
languages.
• SQL is called Domain Specific language, because SQL is
only useful in the domain of databases.

(C) 2016, Gebriye E. Dept. Computer Science HCIA Security, HCIA R&S and HCIP R&S Certified 1-5
Introduction to SQL (Contd.)

• Its primarily task is way to query/ obtain/


add/delete/modify the data efficiently
• SQL is a declarative programming language,
means you DONOT have to define step by step
procedures to get something, instead just, focus
on: what you want, not how to get it?

(C) 2016, Gebriye E. Dept. Computer Science HCIA Security, HCIA R&S and HCIP R&S Certified 1-6
SQL Statements
• SQL Statements play a major role in interacting with the database
• SQL statement is the smallest standalone element that
expresses some actions to be carried out.
• A syntax is how the keyword, identifiers and constants are
combined to from a valid statement
• SQL statements are made up of special words Keywords,
Identifiers, Constants, and Clauses
• SQL is not case sensitive, “select ” and “SELECT” are same.
• To distinguish keywords in a statement, all keywords should
be written in uppercase letters
• Semicolon (;) is required at the end of every SQL statement

(C) 2016, Gebriye E. Dept. Computer Science HCIA Security, HCIA R&S and HCIP R&S Certified 1-7
SQL Statements (Contd.)
• Keywords: SQL standard words used to
construct the SQL statement. Some
keywords are optional, while some are
mandatory
• Identifiers: Names we give to the database,
tables or columns
• Constants: Literals representing fixed values
• Clauses: portion of an SQL statement

(C) 2016, Gebriye E. Dept. Computer Science HCIA Security, HCIA R&S and HCIP R&S Certified 1-8
SQL Statements (Contd.)
• Example: SELECT fname FROM students WHERE
studentid=5;
• KEYWORDS: SELECT,FROM & WHERE (optional)
• Keyword (operator): Equal sign (=)
• Identifiers: fname,students, and studentid
– Fname and studentid are column names
– Students is a table name
• Constant: numeric constant 5
• Clauses: SELECT, FROM, and WHERE clauses

(C) 2016, Gebriye E. Dept. Computer Science HCIA Security, HCIA R&S and HCIP R&S Certified 1-9
SQL Statements (Contd.)
• SQL statements are used to manage the database from a
webpage or application, users interact with the database
using form fields.
• SQL statements are dived into two types
– 1. Data Definition Language (DDL)
– 2. Data Manipulation Language (DML)
• DDL and DML, both are SQL statements
• The best way to distinguish between DDL and DML is, by the
type of the SQL statement used and their effect on the
database
• DDL changes the database structure, while DML changes
only the data

(C) 2016, Gebriye E. Dept. Computer Science HCIA Security, HCIA R&S and HCIP R&S Certified 1-10
Data Definition Language (DDL)
• Data Definition Language is used to specify the database
schema
• Data Definition Language is used to manage database
objects like tables, columns, indexes and views.
• DDL changes the database structure
• Database objects like tables, columns, are created,
modified, or removed using Data Definition Language
SQL statements.
• The most important Data Definition Language statements are
– CREATE create database, table with columns
– ALTER modifies the table and column structure
– DROP removes the tables and columns from the database

(C) 2016, Gebriye E. Dept. Computer Science HCIA Security, HCIA R&S and HCIP R&S Certified 1-11
Data Definition Language (DDL),…
• The SQL data-definition language (DDL) allows the specification of
information about relations, including:
– The schema for each relation.

– The type of values associated with each attribute.

– The Integrity constraints

– The set of indices to be maintained for each relation.

– Security and authorization information for each relation.

– The physical storage structure of each relation on disk.

(C) 2016, Gebriye E. Dept. Computer Science HCIA Security, HCIA R&S and HCIP R&S Certified 1-12
How to create and use databases
• To Display the existing databases
– SHOW DATABASES; the SQL statement will return all
the existing databases in our database management software.

• SQL statement to create a new database is


– CREATE DATABASE database-name;
• To Use database ; goes here
– USE database-name;
• Delete database
– DROP DATABASE database-name;
(C) 2016, Gebriye E. Dept. Computer Science HCIA Security, HCIA R&S and HCIP R&S Certified 1-13
What is Database Table?
• A database table is consist of a
systematically structured vertical columns or
fields, and horizontal rows or record
• Each column is a property of the item, while
each row is an item
• Cell is the smallest unit where a column and
row intersect
• Data elements (or) values are stored in cells

(C) 2016, Gebriye E. Dept. Computer Science HCIA Security, HCIA R&S and HCIP R&S Certified 1-14
What is Database Table? (Contd.)
• A database table has a specified number of
columns, but it can have any number of rows.
• A single database must have a unique table
name, while, in multiple databases, same
table name can exist in other databases.

(C) 2016, Gebriye E. Dept. Computer Science HCIA Security, HCIA R&S and HCIP R&S Certified 1-15
SQL Statement create Database Table
• SQL statement to Select the database is
– USE existing-database-name;
• SQL statement to Display existing tables inside the
selected database is
– SHOW TABLES; returns all the existing tables inside the
selected database
• SQL statement to get the Structure of a database table is
– DESCRIBE table-name;
• SQL statement to delete a table is
– DROP TABLE existing-table-name;

(C) 2016, Gebriye E. Dept. Computer Science HCIA Security, HCIA R&S and HCIP R&S Certified 1-16
SQL Statement to create new table
• The SQL statement to create a new database table is
CREATE TABLE table-name
(A1 D1, A2 D2, ..., An Dn,
(integrity-constraint1),
...,
(integrity-constraint n ));
– table-name is the name of the relation
– each Ai is an attribute name in the schema of relation table-name
– Di is the data type of values in the domain of attribute Ai
• Here is an example SQL statement to create a new table:
CREATE TABLE instructor (
ID CHAR(5) NOT NULL PRIMARY KEY,
name VARCHAR(20),
dept_name VARCHAR(20),
salary NUMERIC(8,2));
• This SQL statement creates a new table called instructor with the given
columns and their data types.
(C) 2016, Gebriye E. Dept. Computer Science HCIA Security, HCIA R&S and HCIP R&S Certified
Integrity Constraints in Create Table

• Types of integrity constraints


– PRIMARY KEY (A1, ..., An )
– FOREIGN KEY (Am, ..., An ) references r
– NOT NULL
• SQL prevents any update to the database that violates an integrity
constraint.
• Example:
CREATE TABLE instructor (
ID CHAR(5),
name VARCHAR(20) NOT NULL,
dept_name VARCHAR(20),
salary NUMERIC(8,2),
PRIMARY KEY (ID),
FOREIGN KEY (dept_name) REFERENCES department);

(C) 2016, Gebriye E. Dept. Computer Science HCIA Security, HCIA R&S and HCIP R&S Certified
And a Few More Relation Definitions
• CREATE TABLE student (
ID VARCHAR(5),
name VARCHAR(20) NOT NULL,
dept_name VARCHAR(20),
tot_cred NUMERIC(3,0),
PRIMARY KEY (ID),
FOREIGN KEY (dept_name) REFERENCES department);

• CREATE TABLE takes (


ID VARCHAR(5),
course_id VARCHAR(8),
sec_id VARCHAR(8),
semester VARCHAR(6),
year NUMERIC(4,0),
grade VARCHAR(2),
PRIMARY KEY (ID, course_id, sec_id, semester, year) ,
FOREIGN KEY (ID) REFERENCES student,
FOREIGN KEY (course_id, sec_id, semester, year) REFERENCES
section);

(C) 2016, Gebriye E. Dept. Computer Science HCIA Security, HCIA R&S and HCIP R&S Certified
And more still

• CREATE TABLE course (


course_id varchar(8),
title varchar(50),
dept_name varchar(20),
credits numeric(2,0),
primary key (course_id),
foreign key (dept_name) references
department);

(C) 2016, Gebriye E. Dept. Computer Science HCIA Security, HCIA R&S and HCIP R&S Certified
DROP
• The DROP DATABASE statement is used to delete
(or) remove the database including all the tables and
data rows in it.
• Be Careful before deleting the database completely
from the database management system, because the
system doesn’t ask for confirmation.
• After executing the SQL statement, DROP
DATABASE, the system will remove the database,
tables and data rows and there is no easy method to
recover the lost database.

(C) 2016, Gebriye E. Dept. Computer Science HCIA Security, HCIA R&S and HCIP R&S Certified 1-21
DROP (Contd.)
• DROP is used to remove a database and
table from the schema.
• Syntax is:
– DROP DATABASE existing database-name;
– DROP TABLE existing-table-name;
– Example: DROP DATABASE school; where
school is existing database name
• DROP TABLE user; where user is table name

(C) 2016, Gebriye E. Dept. Computer Science HCIA Security, HCIA R&S and HCIP R&S Certified 1-22
ALTER
• The ALTER TABLE SQL statement is used to
– Rename (or) change table name,
– Add a column, change datatype of column, change the name of
an existing column and drop table columns in the existing
database table
• To rename the table:
– ALTER TABLE old-table-name RENAME TO new-table-name;
• To add new column in the existing table name:
– ALTER TABLE table-name ADD new-column-name data type;
• To modify the column data type in the existing table:
– ALTER TABLE table-name MODIFY COLUMN column-name new
data type;

(C) 2016, Gebriye E. Dept. Computer Science HCIA Security, HCIA R&S and HCIP R&S Certified 1-23
ALTER (Contd.)
• To drop a column from existing table
– ALTER TABLE table-name DROP COLUMN column-name;
• To change the name of an existing column name
– ALTER TABE table-name CHANGE old_column_name new-
column-name data type;
• Example: assume table name is user
– ALTER TABLE user RENAME TO user1;
– ALTER TABLE user ADD firstname VARCHAR(30);
– ALTER TABLE user MODIFY firstname VARCHAR(50);
– ALTER TABLE user CHANGE password pasd CHAR(20);
– ALTER TABLE user DROP firstname;

(C) 2016, Gebriye E. Dept. Computer Science HCIA Security, HCIA R&S and HCIP R&S Certified 1-24
Data Manipulation Language (DML)
• Data Manipulation Language is used to
express database queries and update
• DML is used to manage the data that
resides in our tables and columns
• DML changes only the data, not the
database structure
• The data inside a table is inserted, updated,
or deleted using the DML SQL statements

(C) 2016, Gebriye E. Dept. Computer Science HCIA Security, HCIA R&S and HCIP R&S Certified 1-25
Data Manipulation Language (DML)
• The most important Data Manipulation Languages are:
• INSERT INTO
• UPDATE
• DELETE
– INSERT SQL statement add the data
– UPDATE modifies the data
– DELETE removes the data from the database
• Language for accessing and updating the data organized by the
appropriate data model
– DML also known as query language

(C) 2016, Gebriye E. Dept. Computer Science HCIA Security, HCIA R&S and HCIP R&S Certified 1-26
Data Manipulation Language (DML),…
• There are basically two types of data-manipulation language
– Procedural DML -- require a user to specify what data are needed
and how to get those data.
– Declarative DML -- require a user to specify what data are needed
without specifying how to get those data.
• Declarative DMLs are usually easier to learn and use than
are procedural DMLs.
• Declarative DMLs are also referred to as non-procedural DMLs
• The portion of a DML that involves information retrieval is
called a query language.

(C) 2016, Gebriye E. Dept. Computer Science HCIA Security, HCIA R&S and HCIP R&S Certified 1-27
INSERT INTO Statement
• The INSERT INTO statement is used to insert or add new data rows
(or) records to a database table
• To add data rows to a table, first select the existing database

• There are two methods that we can use INSERT statement.


Method-1:

INSERT INTO table-name VALUES (value1,value2,value3,…);


• Column names are not specified, values for each column must be
specified sequentially by column order similar the database table.

(C) 2016, Gebriye E. Dept. Computer Science HCIA Security, HCIA R&S and HCIP R&S Certified 1-28
INSERT INTO Statement (Contd.)
• Method 2:

• INSERT INTO table-name (column1, column2,…, column


n) VALUES (value1, value2, value3 ,…, value n);
• The column names are given in first bracket and the values
are given in second bracket.
• In first method, we must provide all the columns values, while
in the second method we can add the values to only selected
columns.

(C) 2016, Gebriye E. Dept. Computer Science HCIA Security, HCIA R&S and HCIP R&S Certified 1-29
INSERT INTO Statement (Contd.)
• The string values must be enclosed in double quotes, but
enclosed numeric values in quote is optional or not
required. Here arefew examples
• INSERT INTO teachers VALUES (“John Doe”, 1234);
• INSERT INTO students (firstname, lastname, class, age) VALUES
(“John”,”Doe”,”First”, 26);
• insert into instructor values (“10211”, “Smith”, “Biology”, 66000);

(C) 2016, Gebriye E. Dept. Computer Science HCIA Security, HCIA R&S and HCIP R&S Certified 1-30
INSERT INTO Statement (Contd.)
• In first method, we must provide all columns values
in the sequence, while in the second method, we
can add the values to a selected columns
• In most of the cases, the second method is more
convenient.

(C) 2016, Gebriye E. Dept. Computer Science HCIA Security, HCIA R&S and HCIP R&S Certified 1-31
UPDATE Statement
• UPDATE statement is used to update the data rows
in a database table
• The update statement can update one (or) multiple
column values in a single SQL statement
• WHERE clause is used to specify the data row to be
updated, UPDATE statement without WHERE clause
will update all the data rows in a table

(C) 2016, Gebriye E. Dept. Computer Science HCIA Security, HCIA R&S and HCIP R&S Certified 1-32
UPDATE Statement (Contd.)
• Any existing data rows or records in target table
remain unaffected
• Syntax for update statement is:
– UPDATE table_name SET column_name = new_value WHERE
condition;
• Example
– UPDATE tablename SET column1=newvalue;

– UPDATE tablename SET column1=newvalue1,


column2=newvalue2, column3=newvalue3 WHERE
columneid=3;

(C) 2016, Gebriye E. Dept. Computer Science HCIA Security, HCIA R&S and HCIP R&S Certified 1-33
Basic SQL Query Structure
• A typical SQL query has the form:

select A1, A2, ..., An


from r1, r2, ..., rm
where P

– Ai represents an attribute
– Ri represents a relation
– P is a predicate logic (condtion).
• The result of an SQL query is a relation.

(C) 2016, Gebriye E. Dept. Computer Science HCIA Security, HCIA R&S and HCIP R&S Certified
The select Clause
• The select clause lists the attributes desired in the result
of a query
– Main purpose is to retrieve the data from the database
and return it in a tabular structure
• Example: find the names of all instructors:
select name from instructor;
• It defines the columns that will be returned in the final
tabular result set.
• It is executed after the FROM clause and any optional
WHERE, GROUP BY and HAVING clauses if present.

(C) 2016, Gebriye E. Dept. Computer Science HCIA Security, HCIA R&S and HCIP R&S Certified 1-35
The select Clause
• The general SELECT statement syntax is:
SELECT expression(s) involving keywords, identifiers and constants
FROM table name
[WHER clause]
[GROUP BY clause]
[HAVING clause]
[ORDER BY clause]

• SELECT columnname1,columnname2 FROM table-name;


–In this statement, the SELECT clause only returns the column names mentioned in
the SQL statement.

(C) 2016, Gebriye E. Dept. Computer Science HCIA Security, HCIA R&S and HCIP R&S Certified 1-36
The select Clause (Cont.)
• An asterisk in the select clause denotes “all attributes”
select *
from instructor
• An attribute can be a literal with from clause
select 'A'
from instructor
– Result is a table with one column and N rows
(number of tuples in the instructors table), each row
with value “A”

(C) 2016, Gebriye E. Dept. Computer Science HCIA Security, HCIA R&S and HCIP R&S Certified
The select Clause (Cont.)

• The select clause can contain arithmetic expressions


involving the operation, +, –, , and /, and operating on
constants or attributes of tuples.
– The query:
select ID, name, salary/12
from instructor
would return a relation that is the same as the instructor
relation, except that the value of the attribute salary is
divided by 12.
– Can rename “salary/12” using the as clause:
select ID, name, salary/12 as monthly_salary

(C) 2016, Gebriye E. Dept. Computer Science HCIA Security, HCIA R&S and HCIP R&S Certified
SELECT DISTINICT Statement
• SELECT DISTINICT Statement is used to return distinct or different
values from a table column.
• In a database table, a column name may contain duplicate or similar
values, in such cases if we want only the distinct values to be
displayed from the columns, the SELECT DISTINICT Statement is
very useful.

(C) 2016, Gebriye E. Dept. Computer Science HCIA Security, HCIA R&S and HCIP R&S Certified 1-39
The select Clause (Cont.)
• SQL allows duplicates in relations as well as in query results.
• To force the elimination of duplicates, insert the keyword
distinct after select.
• Find the department names of all instructors, and remove
duplicates
select distinct dept_name
from instructor
• The keyword all specifies that duplicates should not be
removed.

select all dept_name


from instructor

(C) 2016, Gebriye E. Dept. Computer Science HCIA Security, HCIA R&S and HCIP R&S Certified
The where Clause
• The where clause specifies conditions that the result must satisfy
– Corresponds to the selection predicate of the relational algebra.
• To find all instructors in Comp. Sci. dept
SELECT name
FROM instructor
WHERE dept_name = 'Comp. Sci.'
• SQL allows the use of the logical connectives AND, OR, and NOT
• The operands of the logical connectives can be expressions involving the
comparison operators <, <=, >, >=, ==, and <>.
• Comparisons can be applied to results of arithmetic expressions
• To find all instructors in Comp. Sci. dept with salary > 7000
SELECT name
FROM instructor
WHERE dept_name = 'Comp. Sci.’ AND salary > 7000

(C) 2016, Gebriye E. Dept. Computer Science HCIA Security, HCIA R&S and HCIP R&S Certified
FROM Clause
• The from clause lists the relations involved in the query
– Corresponds to the Cartesian product operation of the relational
algebra.
• The FROM clause produces a tabular structure also called
as the “result set” or an “intermediate set” or an
intermediate table of the FROM clause.
• The FROM clause is the first clause that the database
system looks at when it parses the SQL statement.
– Example: SELECT firstname FROM students;
• The FROM statements can return the result sets from one
table, more than table, using joins, views and subqueries.

(C) 2016, Gebriye E. Dept. Computer Science HCIA Security, HCIA R&S and HCIP R&S Certified
Examples
• Find the names of all instructors who have
taught some course and the course_id
– select name, course_id
from instructor , teaches
where instructor.ID = teaches.ID

• Find the names of all instructors in the Art


department who have taught some course
and the course_id
– select name, course_id
from instructor , teaches
where instructor.ID = teaches.ID
and instructor. dept_name = 'Art'

(C) 2016, Gebriye E. Dept. Computer Science HCIA Security, HCIA R&S and HCIP R&S Certified
WHERE Clause
• The WHERE clause is an optional clause used in SQL
statements
• Acts as a filter on the rows of the result set produced by
the FROM clause.
• The WHERE clause mainly depend up on a condition
which evaluates as either be true, false or unknown.
• A condition is made up of keywords, identifiers and
constants to compare values with the data rows values. If
condition is matched it is called as True condition,
otherwise, it is False condition.
• the condition can be simple or complex condition.

(C) 2016, Gebriye E. Dept. Computer Science HCIA Security, HCIA R&S and HCIP R&S Certified 1-44
DELETE Statement
• DELETE removes the definition of the relation as well as the data
in the given relation, delete only deletes the tuples but maintains
the table definition.
• DELETE statement is used to delete the data rows in a database
table

• The DELETE statement can delete one or multiple data rows from
a database table.

(C) 2016, Gebriye E. Dept. Computer Science HCIA Security, HCIA R&S and HCIP R&S Certified 1-45
DELETE Statement (Contd.)
• WHERE clause is used to specify the data row to be
deleted, DELETE statement without WHERE clause will
delete all the data rows in a table

• Examples
– DELETE FROM table-name; Remove all tuples from the table

– DELETE FROM table-name WHERE column1=value;

(C) 2016, Gebriye E. Dept. Computer Science HCIA Security, HCIA R&S and HCIP R&S Certified 1-46
SQL Data Types

• Every column in a database table is defined


with a data type, depending up on the data
value its going to store.
• A SQL datatype defines what kind of value a
column can store.
• There are mainly 3 SQL data types:
– Numeric
– Character and
– Temporal data types

(C) 2016, Gebriye E. Dept. Computer Science HCIA Security, HCIA R&S and HCIP R&S Certified
SQL Data Types
• NUMERIC data types stores only numeric values. Numeric data
types are integers, floating point numbers and fixed-point numbers.
– The INT data type stores integers ranging from 2,147,483,648 to
2,147,483,647. An optional "unsigned" can be denoted with the declaration,
modifying the range to be 0 to 4,294,967,295.
– A FLOAT represents small decimal numbers, used when a somewhat
more precise representation of a number is required.
– E.g. Rainfall FLOAT (4, 2);

– Character data types can store alphabets, symbols and numbers.


Example: full name, description, address, etc.
– Temporal data types can store date, time, date and time together.

(C) 2016, Gebriye E. Dept. Computer Science HCIA Security, HCIA R&S and HCIP R&S Certified
SQL Data Types
• CHAR(N). Fixed length character string, with user-specified length n.
– The CHAR or CHARACTER data type stores fixed width character columns.
– It is required to enter the column width in CHAR and VARCHAR datatypes.
– Example: CHAR(20), CHAR(50)
– If the inserted character length is less than the defined column width, the value is
positioned to the left and padded with spaces on the right until the character length is
equal to the defined column width.
– Example: in firstname CHAR(20), String ‘John’ will be appended with 16 spaces.
• VARCHAR(N). Variable length character strings, with user-specified
maximum length n.
– The VARCHAR CHARACTER store dynamic width character column
– In VARCHAR the defined width is the maximum width of the value allowed in the data
column.
– The inserted data character length will be exactly similar to the character length itself.
– Example in VARCHAR (250) data column will store only 4 character for the value
‘John’

(C) 2016, Gebriye E. Dept. Computer Science HCIA Security, HCIA R&S and HCIP R&S Certified
Temporal Data Types
• The Temporal data types consist of date, time
and timestamp (have both date and time)
• The date value stores standard 365- day Gregorian
calendar.
• The most popular date format is YYYY-MM-DD, where 4Y
means Year, 2M means Month and 2D is for the Day.
• The TIMESTAMP data type can store date as well as time
components.
• Example: Date_Of_Birth (DATE): 1994-02-13 and
last_login (TIMESTAMP): YYYY-MM-DD HH:MM:SS

(C) 2016, Gebriye E. Dept. Computer Science HCIA Security, HCIA R&S and HCIP R&S Certified 1-50
SQL functions
• These functions operate on the multiset of
values of a column of a relation, and return
a value
AVG: average value
MIN: minimum value
MAX: maximum value
SUM: sum of values
COUNT: number of values

(C) 2016, Gebriye E. Dept. Computer Science HCIA Security, HCIA R&S and HCIP R&S Certified 1-51
SQL functions Cont’d…
• AVG : This SQL function returns the average value of a
column that contains numeric values
• SUM: This SQL function returns the sum of a column that
contains numeric values.
• MIN: This SQL function returns the smallest, or minimum
value found in a column that contains numeric values
• MAX: This SQL function returns the largest, or maximum
value found in a column that contains numeric values.
• COUNT: This SQL function returns the number of rows in a
table, or the number of rows that match a search criteria.

(C) 2016, Gebriye E. Dept. Computer Science HCIA Security, HCIA R&S and HCIP R&S Certified 1-52
Aggregate Functions – Group By
• Find the average salary of instructors in each department
– select dept_name, avg (salary) as avg_salary
from instructor
group by dept_name;

(C) 2016, Gebriye E. Dept. Computer Science HCIA Security, HCIA R&S and HCIP R&S Certified
Aggregation (Cont.)

• Attributes in select clause outside of aggregate functions must


appear in group by list
– /* erroneous query */
select dept_name, ID, avg (salary)
from instructor
group by dept_name;

(C) 2016, Gebriye E. Dept. Computer Science HCIA Security, HCIA R&S and HCIP R&S Certified
SQL Constraints
• What is a constraint ?
– A constraint is a property assigned to a column or the set of
columns in a table that prevents certain types of inconsistent
data values from
being placed in the column(s).
– Constraints are used to enforce the data integrity
– There are various categories of integrity constraints:
• Entity Integrity: ensures that there are no duplicate rows in a table
• Domain Integrity: enforces valid entries for a given column by
restricting the type, the format, or the range of possible values

(C) 2016, Gebriye E. Dept. Computer Science HCIA Security, HCIA R&S and HCIP R&S Certified 1-55
SQL Constraints (Contd.)
• Referential integrity: ensures that rows cannot be deleted, which are
used by other records
• User-Defined Integrity: enforces some specific business rules that do
not fall into entity, domain, or referential integrity categories.
• The SQL constraints defines the specific rules to be follow to the
column data in a database table.
• While INSERTING, UPDATING or DELETING the data rows, if the
constraints rules are not followed, the system will display an error
message and the action will be terminated.
• The SQL constraints are defined while creating a new database table.
We can also alter the table and add new constraints. The standard
SQL supports six constraints: NOT NULL, UNIQUE, PRIMARY KEY,
FORIGEN KEY, CHECK and DEFAULT.

(C) 2016, Gebriye E. Dept. Computer Science HCIA Security, HCIA R&S and HCIP R&S Certified 1-56
PRIMARY KEY Constraint
• The primary key constraint is useful to
restrict storing of duplicate data rows in a
given column.
• The primary key column cannot contain
NULL values.
• The primary key can be defined while
creating a new database table or can be
added by using ALTER statement.

(C) 2016, Gebriye E. Dept. Computer Science HCIA Security, HCIA R&S and HCIP R&S Certified 1-57
HAVING Clause
• It is designed for use with the GROUP BY
clause to restrict the groups that appear in
the final result table.
• WHERE clause filters individual rows going
into the final result table
• HAVING clause filters groups going into the
final result table.

(C) 2016, Gebriye E. Dept. Computer Science HCIA Security, HCIA R&S and HCIP R&S Certified 1-58
What is SQL Injection?
• SQL Injection refers to the act of someone inserting a
MySQL statement to be run on your database without your
knowledge.
• SQL injection is a method where a malicious user can
inject some SQL commands to display other information or
destroy the database, using form fields on web page or
application.
• Injection usually occurs when you ask a user for input, like
their name, email and instead of that, they give you a
MYSQL statement that you will unknowingly run on your
database.

(C) 2016, Gebriye E. Dept. Computer Science HCIA Security, HCIA R&S and HCIP R&S Certified 1-59
What is SQL Injection? (Contd.)
• SQL injection is a code injection technique that might
destroy your database
• SQL injection is one of the most common web hacking
techniques,
• by using SQL injection, a hacker may get access to other
users password and other information
• SQL injection is the placement of malicious code in SQL
statements, via web page input

(C) 2016, Gebriye E. Dept. Computer Science HCIA Security, HCIA R&S and HCIP R&S Certified 1-60
Fundamentals of Database Systems

End of Chapter Three !!!

Have a nice day!!

Never Stop Learning!

(C) 2016, Gebriye E. Dept. Computer Science HCIA Security, HCIA R&S and HCIP R&S Certified 1-61

You might also like