0% found this document useful (0 votes)
16 views

Intro To SQL

This document provides an introduction to SQL queries for data analysis. It discusses key SQL concepts like the SELECT-FROM-WHERE statement to retrieve data, aggregation functions like COUNT and AVG, joins, null values, pattern matching and more. Examples are provided to illustrate different types of queries involving selection, projection, aggregation, joins and other SQL features.

Uploaded by

Nada Wael
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
16 views

Intro To SQL

This document provides an introduction to SQL queries for data analysis. It discusses key SQL concepts like the SELECT-FROM-WHERE statement to retrieve data, aggregation functions like COUNT and AVG, joins, null values, pattern matching and more. Examples are provided to illustrate different types of queries involving selection, projection, aggregation, joins and other SQL features.

Uploaded by

Nada Wael
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 34

Introduction to SQL

for Data Analysis


Introduction
• SQL: Structured Query Language
Company Database Tables
Database Programming
Retrieval Queries in SQL
• SELECT-FROM-WHERE Statement

SELECT <attribute list>


FROM <table list>
WHERE <condition>
– <attribute 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
UNSPECIFIED WHERE-clause
• A missing WHERE-clause indicates no condition; hence, all
tuples of the relations in the FROM-clause are selected

Query: Retrieve the SSN values for all employees.


SELECT SSN
FROM EMPLOYEE

• If more than one relation is specified in the FROM-clause and


there is no join condition, then the CARTESIAN PRODUCT of
tuples is selected
UNSPECIFIED
WHERE-clause (contd.)
• Example:

It is extremely important not to overlook specifying


any selection and join conditions in the WHERE-clause;
otherwise, incorrect and very large relations may result
Simple SQL Queries
Query : Retrieve the birthdate and address of the
employee whose name is 'John B. Smith’.

SELECT BDATE, ADDRESS


FROM EMPLOYEE
WHERE FNAME='John' AND MINIT='B’
AND LNAME='Smith’

The SELECT-clause specifies the projection attributes


and the WHERE-clause specifies the selection
condition
– However, the result of the query may contain
duplicate tuples
Simple SQL Queries
Query : Retrieve the name and address of all
employees who work for the 'Research' department.

SELECT FNAME, LNAME, ADDRESS


FROM EMPLOYEE, DEPARTMENT
WHERE DNAME='Research' AND DNUMBER=DNO

– (DNAME='Research') is a selection condition


– (DNUMBER=DNO) is a join condition

Database Systems Database Programming


Simple SQL Queries (contd.)
Query : For every project located in 'Stafford', list the project
number, the controlling department number, and the
department manager's last name, address, and birthdate.

SELECT PNUMBER, DNUM, LNAME, BDATE, ADDRESS


FROM PROJECT, DEPARTMENT, EMPLOYEE
WHERE DNUM=DNUMBER AND MGRSSN=SSN
AND PLOCATION='Stafford’

– There are two join conditions


– The join condition DNUM=DNUMBER relates a project to its
controlling department
– The join condition MGRSSN=SSN relates the controlling department to
the employee who manages that department
Database Systems Database Programming
Aliases, * and DISTINCT, Empty WHERE-
clause
• In SQL, we can use the same name for two (or
more) attributes as long as the attributes are
in different relations
• A query that refers to two or more attributes
with the same name must qualify the attribute
name with the relation's name by prefixing
the relation's name to the attribute name
• Example:
– EMPLOYEE.LNAME, DEPARTMENT.DNAME
USE OF *
• To retrieve all the attribute values of the selected
tuples, a * is used, which stands for all the attributes
Examples:

SELECT *
FROM EMPLOYEE
WHERE DNO=5

SELECT *
FROM EMPLOYEE, DEPARTMENT
WHERE DNAME='Research' AND
DNO=DNUMBER
USE OF DISTINCT
• SQL does not treat a relation as a set; duplicate tuples can
appear
• To eliminate duplicate tuples in a query result, the keyword
DISTINCT is used
• For example, the result of the first query may have duplicate
SALARY values whereas the second one does not have any
duplicate values

SELECT SALARY
FROM EMPLOYEE

SELECT DISTINCT SALARY


FROM EMPLOYEE
String Pattern Matching
• Partial strings are specified using two reserved
characters:
– % replaces an arbitrary number of zero or more
characters,
– the underscore (_) replaces a single character
Query: Retrieve all employees whose address is in
Houston,Texas.
SELECT Fname, Lname
FROM EMPLOYEE
WHERE Address LIKE ‘%Houston,TX%’;
String Pattern Matching
Query: Find all employees who were born
during the 1950s.
SELECT Fname, Lname
FROM EMPLOYEE
WHERE Bdate LIKE ‘195 _ _ _ _ _ _ _’;
SET OPERATIONS
• SQL has directly incorporated some set operations
• There is a union operation (UNION), and in some versions of
SQL there are set difference (MINUS) and intersection
(INTERSECT) operations
• The resulting relations of these set operations are sets of
tuples; duplicate tuples are eliminated from the result
• The set operations apply only to union compatible relations;
the two relations must have the same attributes and the
attributes must appear in the same order
SET OPERATIONS (contd.)
Query: Make a list of all project numbers for projects that
involve an employee whose last name is 'Smith' as a
worker or as a manager of the department that controls
the project.
(SELECT PNAME
FROM PROJECT, DEPARTMENT, EMPLOYEE
WHERE DNUM=DNUMBER AND
MGRSSN=SSN AND LNAME='Smith')
UNION
(SELECT PNAME
FROM PROJECT, WORKS_ON, EMPLOYEE
WHERE PNUMBER=PNO AND
ESSN=SSN AND NAME='Smith')
ORDER BY
• The ORDER BY clause is used to sort the tuples in a
query result based on the values of some attribute(s)
Query: Retrieve a list of employees and the projects
each works in, ordered by the employee's
department, and within each department ordered
alphabetically by employee last name.
Q28: SELECT DNAME, LNAME, FNAME, PNAME
FROM DEPARTMENT, EMPLOYEE,
WORKS_ON, PROJECT
WHERE DNUMBER=DNO AND
SSN=ESSN AND
PNO=PNUMBER
ORDER BY DNAME, LNAME
ORDER BY (contd.)
• The default order is in ascending order of
values
• We can specify the keyword DESC if we want a
descending order; the keyword ASC can be
used to explicitly specify ascending order,
even though it is the default
Summary of SQL Queries
• A query in SQL can consist of up to six clauses,
but only the first two, SELECT and FROM, are
mandatory. The clauses are specified in the
following order:

SELECT <attribute list>


FROM <table list>
[WHERE <condition>]
[ORDER BY <attribute list>]
EXPLICIT SETS
• It is also possible to use an explicit
(enumerated) set of values in the WHERE-
clause rather than a nested query
Query: Retrieve the social security numbers of
all employees who work on project number 1,
2, or 3.
SELECT DISTINCT ESSN
FROMWORKS_ON
WHERE PNO IN (1, 2, 3)
NULLS IN SQL QUERIES
• SQL allows queries that check if a value is NULL
(missing or undefined or not applicable)
• SQL uses IS or IS NOT to compare NULLs because it
considers each NULL value distinct from other NULL
values, so equality comparison is not appropriate.
Query: Retrieve the names of all employees who do
not have supervisors.
SELECT FNAME, LNAME
FROM EMPLOYEE
WHERE SUPERSSN IS NULL
Joined Relations Feature in SQL
• Can specify a "joined relation" in the FROM-clause
– Looks like any other relation but is the result of a join
– Allows the user to specify different types of joins
(regular INNER JOIN, LEFT OUTER JOIN, RIGHT OUTER
JOIN,NATURAL JOIN, etc)
– In a NATURAL JOIN on two relations R and S, no join
condition is specified; an implicit EQUIJOIN condition
for each pair of attributes with the same name from R
and S is created
Joined Relations Feature in SQL
• INNER JOIN: a tuple is included in the result only if a
matching tuple exists in the other relation.
• LEFT OUTER JOIN (every tuple in the left table must
appear in the result; if it does not have a matching
tuple, it is padded with NULL values for the attributes of
the right table).
• RIGHT OUTER JOIN (every tuple in the right table must
appear in the result; if it does not have a matching
tuple, it is padded with NULL values for the attributes of
the left table)
Joined Relations Feature
in SQL (contd.)
• Examples:
SELECT FNAME, LNAME, ADDRESS
FROM EMPLOYEE, DEPARTMENT
WHERE DNAME='Research' AND
DNUMBER=DNO
• could be written as:
SELECT FNAME, LNAME, ADDRESS
FROM (EMPLOYEE Inner JOIN DEPARTMENT
ON DNUMBER=DNO)
WHERE DNAME='Research’
Joined Relations Feature
in SQL (contd.)
• Another Example:
SELECT PNUMBER, DNUM, LNAME,
BDATE, ADDRESS
FROM (PROJECT JOIN
DEPARTMENT ON
DNUM=DNUMBER) JOIN
EMPLOYEE ON
MGRSSN=SSN) )
WHERE PLOCATION='Stafford’
AGGREGATE FUNCTIONS
• Include COUNT, SUM, MAX, MIN, and AVG
Query: Find the maximum salary, the minimum
salary, and the average salary among all
employees.
SELECT MAX(SALARY),
MIN(SALARY), AVG(SALARY)
FROM EMPLOYEE

• Some SQL implementations may not allow more


than one function in the SELECT-clause
AGGREGATE FUNCTIONS (contd.)
Query: Find the maximum salary, the minimum
salary, and the average salary among employees
who work for the 'Research' department.
SELECT MAX(SALARY),
MIN(SALARY), AVG(SALARY)
FROM EMPLOYEE, DEPARTMENT
WHERE DNO=DNUMBER AND
DNAME='Research'
AGGREGATE FUNCTIONS (contd.)
Query: Retrieve the total number of employees in the
company (Q1), and the number of employees in the
'Research' department (Q2).
Q1: SELECT COUNT (*)
FROM EMPLOYEE

Q2: SELECT COUNT (*)


FROM EMPLOYEE, DEPARTMENT
WHERE DNO=DNUMBER AND
DNAME='Research’

Database Systems Database Programming


GROUPING
• In many cases, we want to apply the aggregate
functions to subgroups of tuples in a relation
• Each subgroup of tuples consists of the set of
tuples that have the same value for the
grouping attribute(s)
• The function is applied to each subgroup
independently
• SQL has a GROUP BY-clause for specifying the
grouping attributes, which must also appear in
the SELECT-clause
GROUPING (contd.)
Query: 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

– The EMPLOYEE tuples are divided into groups-


• Each group having the same value for the grouping attribute DNO
– The COUNT and AVG functions are applied to each such group of
tuples separately
– The SELECT-clause includes only the grouping attribute and the
functions to be applied on each group of tuples
– A join condition can be used in conjunction with grouping
GROUPING (contd.)
Query: For each project, retrieve the project number, project
name, and the number of employees who work on that project.

SELECT PNUMBER, PNAME, COUNT (*)


FROM PROJECT, WORKS_ON
WHERE PNUMBER=PNO
GROUP BY PNUMBER, PNAME

– In this case, the grouping and functions are applied after the joining
of the two relations
THE HAVING-CLAUSE
• Sometimes we want to retrieve the values of
these functions for only those groups that
satisfy certain conditions
• The HAVING-clause is used for specifying a
selection condition on groups (rather than on
individual tuples)
THE HAVING-CLAUSE (contd.)
Query: For each project on which more than
two employees work, retrieve the project
number, project name, and the number of
employees who work on that project.
SELECT PNUMBER, PNAME,
COUNT(*)
FROMPROJECT, WORKS_ON
WHERE PNUMBER=PNO
GROUP BY PNUMBER, PNAME
HAVING COUNT (*) > 2

You might also like