Chapter : 5
Structured Query Language
prepare by:Fikirte G
1
Structure Query Language(SQL) commands
• SQL is a computer language for storing,
manipulating and retrieving data stored in a relational
database.
• SQL is the standard language for Relational Database
System.
• It has statements for data definitions, queries, and
updates
• The main SQL command for data definition is the
CREATE statement,
2
Why SQL?
• SQL is widely popular because it offers the following
advantages:
✓ Allows users to access data in the relational database management
systems.
✓ Allows users to describe the data.
✓ Allows users to define the data in a database and manipulate that data.
✓ Allows to embed within other languages using SQL modules, libraries
& pre-compilers.
✓ Allows users to create and drop databases and tables.
3
Cont’d
• SQL commands can be divided into the following three
functional groups:-
▪ Data Definition Language (DDL) - used to define the
schema (structure) of the database.
➢ DATABASE
✓ CREATE DATABSE
✓ DROP DATABASE
▪ Table
✓ CREATE TABLE
✓ ALTER TABLE
✓ DROP TABLE
4
Data Manipulation Language (DML) - used to retrieve and
update data from the database.
SELECT
INSERT
UPDATE
DELETE
Data Control Language (DCL) - used to manipulate the
processing of data.
5
SQL DATA DEFINITION LANGUEGE (DDL)
• The SQL CREATE DATABASE statement is used to create a new SQL database.
Syntax
The basic syntax of this CREATE DATABASE statement is as follows −
CREATE DATABASE DatabaseName;
Example : CREATE DATABASE Employee
Syntax
The basic syntax of DROP DATABASE statement is as follows
DROP DATABASE DatabaseName;
Example : DROP DATABASE Employee
6
Cont’d
• The SQL USE statement is used to select any existing
database in the SQL schema.
Syntax
• The basic syntax of the USE statement is as shown below −
Example USE DatabaseName
USE Employee;
7
Cont’d
TABLES
Creating a basic table involves naming the table and defining its columns
and each column's data type.
• The SQL CREATE TABLE statement is used to create a new table.
Syntax
• The basic syntax of the CREATE TABLE statement is as follows −
CREATE TABLE table_name( column1 datatype, column2
datatype, column3 datatype, ..... columnN datatype, PRIMARY
KEY( one or more columns ) );
8
Cont’d
Example: Define the student table:
CREATE TABLE STUDENT
( SID int,
FNAME varchar(18),gender varchar(18),age int
PRIMARY KEY (SID));
9
Cont’
➢ The SQL DROP TABLE statement is used to remove a
table
Syntax
The basic syntax of this DROP TABLE statement is as follows
DROP TABLE table_name;
Example
DROP TABLE employee
10
SQL DATA MANIPULATION LANGUAGE (DML)
⚫ The DML component of SQL is the part that is used to query
and update the tables
⚫ The most commonly used DML statement is the SELECT.
⚫ It combines a range of functionality into one complex
command.
⚫ Insert
⚫ Select
⚫ Update
⚫ Delete
11
INSERT
• The SQL INSERT INTO Statement is used to add new rows of data
to a table in the database.
Syntax
• There are two basic syntaxes of the INSERT INTO statement which
are shown below.
INSERT INTO TABLE_NAME (column1, column2,
column3,...columnN) VALUES (value1, value2, value3,...valueN);
INSERT INTO TABLE_NAME VALUES
(value1,value2,value3,...valueN);
12
Cont’d
Example
• The following statements would create two records
in the employee table.
• INSERT INTO Employee (ID,NAME,AGE,ADDRESS,SALARY)
VALUES (1, ‘Abebe', 32, ‘yeka', 2000.00 );
• INSERT INTO Employee (ID,NAME,AGE,ADDRESS,SALARY)
VALUES (2, ‘Mohamed', 25, ‘Mixico', 3500.00 );
• create a record second syntax as shown below.
• INSERT INTO Employee VALUES (3, ‘Saron', 24,
‘4 kilo', 10000.00 );
13
DELETE
• The DELETE statement removes tuples from a
relation.
• It includes a WHERE clause, similar to that used in
an SQL query, to select the tuples to be deleted.
• Tuples are explicitly deleted from only one table at a
time.
syntax
• DELETE FROM table name
WHERE condition
14
UPDATE
• The UPDATE statement is used to modify attribute
values of one or more selected tuples.
• As in the DELETE statement, a WHERE clause in the
UPDATE command selects the tuples to be modified from a
single relation
• syntax
UPDATE table name
SET values
WHERE condition
15
SELECT
SELECT
▪The SQL SELECT statement is used to fetch the data
from a database table which returns this data in the form of
a result table.
▪These result tables are called result-sets.
Syntax
▪The basic syntax of the SELECT statement is as follows:
SELECT column1, column2, column N
FROM table_name;
WHERE <condition>;
.
16
Cont’d
where
■ <column list> is a list of attribute names whose values are
to be retrieved by the query.
■ <table list> is a list of the relation names required to process
the query.
■ <condition> is a conditional (Boolean) expression that
identifies the tuples to be retrieved by the query.
• In SQL, the basic logical comparison operators for
comparing attribute values with one another and with
literal constants are =, <, <=, >, >=, and <>.
17
Cont’d
• If you want to fetch all the fields available in the
field, then you can use the following syntax.
• SELECT * FROM table_name;
• The following code is an example, which would
fetch the ID, Name and Salary fields of the
customers available in CUSTOMERS table.
• SELECT ID, NAME, SALARY FROM
CUSTOMERS;
18
Cont’d
Example
• Find Cid, FName and Salary fields from the
CUSTOMERS table, where the salary is greater
than 2500 −
SELECT Cid, FName, Salary FROM
CUSTOMERS WHERE Salary > 2500;
19
GROUP BY
The SQL GROUP BY clause is used in collaboration with the
SELECT statement to arrange identical data into groups.
⚫ The GROUP BY clause is used to specify one or more
fields that are to be used for organizing tuples into groups.
⚫ Rows that have the same value(s) are grouped together.
⚫ The only fields that can be displayed are the ones used for
grouping and ones derived using column functions.
20
Cont’d
Syntax
• The basic syntax of a GROUP BY clause is shown in the following
code block.
• The GROUP BY clause must follow the conditions in the WHERE
clause and must precede the ORDER BY clause if one is used.
• SELECT column1, column2
FROM table_name
WHERE [ conditions ]
GROUP BY column1, column2
ORDER BY column1, column2
21
Cont’d
• If you want to know the total amount of the
salary on each customer, then the GROUP BY
query would be as follows.
SELECT NAME, SUM(SALARY)
FROM CUSTOMERS
GROUP BY NAME
22
ORDER BY clause
• The SQL ORDER BY clause is used to sort the data in ascending or
descending order, based on one or more columns.
• Some databases sort the query results in an ascending order by default.
Syntax
• The basic syntax of the ORDER BY clause is as follows −
SELECT column-list FROM table_name
[WHERE condition]
[ORDER BY column1, column2, .. columnN] [ASC | DESC];
23
Cont’d
• The following code block has an example, which would sort
the result in an ascending order by the NAME and the
SALARY −
SELECT * FROM CUSTOMERS
ORDER BY NAME, SALARY;
• The following code block has an example, which would sort
the result in the descending order by NAME.
SELECT * FROM CUSTOMERS
ORDER BY NAME DESC;
24
Cont’d
⚫ You can select either ascending or descending sort for each named
column.
Example 1: List the FName and SID of all faculty members arranged
in alphabetical order.
SELECT SID, FNAME
FROM Student
ORDER BY FName;
25
HAVING Clause
• The HAVING Clause enables you to specify conditions that
filter which group results appear in the results.
• The WHERE clause places conditions on the selected
columns,
• whereas the HAVING clause places conditions on groups
created by the GROUP BY clause.
• The HAVING clause must follow the GROUP BY clause in
a query and must also precede the ORDER BY clause if
used.
26
Cont’d
Syntax
The following code block has the syntax of the SELECT
statement including the HAVING clause −
SELECT column1, column2
FROM table1, table2
WHERE [ conditions ]
GROUP BY column1, column2
HAVING [ conditions ]
ORDER BY column1, column2
27
MORE COMPLEX SINGLE TABLE RETRIEVAL
⚫ The WHERE clause can be enhanced to be more selective.
⚫ Operators that can appear in WHERE conditions include:
= ,< ,> ,>= ,<=
IN
BETWEEN...AND...
LIKE
IS NULL
AND, OR, NOT
28
COLUMN FUNCTIONS (AGGREGATE FUNCTIONS)
⚫ Aggregate functions allow you to calculate values based upon all
data in an attribute of a table.
⚫ The SQL aggregate functions are: Max, Min, Avg, Sum, Count
etc
⚫ Note:
⚫ AVG and SUM work only with numeric values and both exclude
NULL values from the calculations.
Example 1: How many students are there?
SELECT COUNT(*)
FROM STUDENT;
29
MULTIPLE TABLE QUERIES
▪ A JOIN operation is performed when more than one table is
specified in the FROM clause.
▪ You would join two tables if you need information from both.
▪ You must specify the JOIN condition explicitly in SQL.
▪ This includes naming the columns in common and the
comparison operator.
▪ SQL specifies alias names in the FROM clause immediately
following the actual table
30
Join statement
▪ A JOIN clause is used to combine rows from two or more tables ,
based on a related column between them.
▪ There are different types of the JOINs in SQL:
▪ INNER JOIN
▪ LEFT (OUTER) JOIN
▪ RIGHT (OUTER) JOIN
▪ FULL (OUTER) JOIN
31
Inner Join
• INNER JOIN: returns records that have matching
values in both tables
• Syntax
• SELECT column_name(s)
FROM table1
INNER JOIN table2
ON table1.column_name = table2.column_name;
32
Left Join
• LEFT (OUTER) JOIN: returns all records from the left
table, and the matched records from the right table
• Syntax
• SELECT column_name(s)
FROM table1
LEFT JOIN table2
ON table1.column_name = table2.column_name;
33
RIGHT JOIN
• RIGHT (OUTER) JOIN: returns all records from
the right table, and the matched records from the left
table
• Syntax
• SELECT column_name(s)
FROM table1
RIGHT JOIN table2
ON table1.column_name = table2.column_name;
34
FULL OUTER JOIN
▪ The FULL OUTER JOIN keyword returns all records when
there is a match in left (table1) or right (table2) table
▪ Syntax
SELECT column_name(s)
FROM table1
FULL OUTER JOIN table2
ON table1.column_name = table2.column_name
WHERE condition;
35