You are on page 1of 57

Week 9

Queries + SQL Joins


Questions
• Consider the following relations for a database that keeps
track of student enrollment in courses and the books adopted
for each course:
– STUDENT(Ssn, Name, Major, Bdate)
– COURSE(Course#, Cname, Dept)
– ENROLL(Ssn, Course#, Quarter, Grade)
– BOOK_ADOPTION(Course#, Quarter, Book_isbn)
– TEXT(Book_isbn, Book_title, Publisher, Author)
SQL Data Definition and Data Types

• Terminology:
– Table = Relation
– Row = Tuple
– Column = Attribute
• CREATE statement
– Main SQL command for data definition
The CREATE TABLE Command in SQL

• Specify a new relation


– Provide name
– Specify attributes and initial constraints.

Syntax Example
CREATE TABLE table_name CREATE TABLE Persons
( (
column_name1 data_type(size), PersonID int,
column_name2 data_type(size), LastName varchar(255),
column_name3 data_type(size), FirstName varchar(255),
.... Address varchar(255),
); City varchar(255)
);
Attribute Data Types and Domains in SQL
• Basic data types
– Numeric data types
• Integer numbers: INTEGER, INT, and SMALLINT
• Floating-point (real) numbers: FLOAT or REAL, and DOUBLE
PRECISION
– Character-string data types
• Fixed length: CHAR(n), CHARACTER(n)
• Varying length: VARCHAR(n), CHAR VARYING(n), CHARACTER
VARYING(n)
– Bit-string data types
• Fixed length: BIT(n)
• Varying length: BIT VARYING(n)
– Boolean data type
• Values of TRUE or FALSE or NULL
– DATE data type
• Ten positions
• Components are YEAR, MONTH, and DAY in the form YYYY-MM-DD
Attribute Data Types and Domains in SQL

• Additional data types


– Timestamp data type (TIMESTAMP)
• Includes the DATE and TIME fields
• Plus a minimum of six positions for decimal fractions of
seconds
• Optional WITH TIME ZONE qualifier
– INTERVAL data type
• Specifies a relative value that can be used to increment or
decrement an absolute value of a date, time, or timestamp
Specifying Constraints in SQL
• Basic constraints:
– Key and referential integrity constraints
– Restrictions on attribute domains and NULLs
– Constraints on individual tuples within a relation

• NOT NULL
– NULL is not permitted for a particular attribute
– CREATE TABLE Persons
(
P_Id int NOT NULL,
LastName varchar(255) NOT NULL,
FirstName varchar(255),
Address varchar(255),
City varchar(255)
)
Specifying Constraints in SQL
• Default value
– DEFAULT <value>
– CREATE TABLE Persons
(
P_Id int NOT NULL,
LastName varchar(255) NOT NULL,
FirstName varchar(255),
Address varchar(255),
City varchar(255) DEFAULT 'Sandnes'
)
Add new column alter table Command

ALTER table person


ADD city varchar(30) Not Null

Add default using Alter column Command

ALTER table person


ADD DEFAULT 'sialkot' FOR city
Specifying Constraints in SQL
• CHECK clause
– (value > 0 AND value < 21)
– CREATE TABLE Persons
(
P_Id int NOT NULL CHECK (P_Id>0),
LastName varchar(255) NOT NULL,
FirstName varchar(255),
Address varchar(255),
City varchar(255)
)
The CHECK constraint specifies that the column "P_Id" must only
include integers greater than 0.
Adding constraint using ADD
CONSTRAINT COMMAND
ALTER table person
ADD CONSTRAINT salary CHECK (salary > 10000)
Specifying Key and Referential Integrity Constraints

• PRIMARY KEY clause


– Specifies one or more attributes that make up the primary key of
a relation
– Dnumber INT PRIMARY KEY;

CREATE TABLE Persons


(
P_Id int NOT NULL PRIMARY KEY,
LastName varchar(255) NOT NULL,
FirstName varchar(255),
Address varchar(255),
City varchar(255)
)
Specifying Key and Referential Integrity Constraints

• UNIQUE clause
– Specifies alternate (secondary) keys

– CREATE TABLE Persons


(
P_Id int NOT NULL UNIQUE,
LastName varchar(255) NOT NULL,
FirstName varchar(255),
Address varchar(255),
City varchar(255)
)
Specifying Key and Referential Integrity Constraints

• FOREIGN KEY clause


P_Id LastName FirstName Address City O_Id OrderNo P_Id
1 Hansen Ola Timoteivn 10 Sandnes 1 77895 3
2 44678 3
2 Svendson Tove Borgvn 23 Sandnes
3 22456 2
3 Pettersen Kari Storgt 20 Stavanger 4 24562 1

CREATE TABLE Orders


(
O_Id int NOT NULL PRIMARY KEY,
OrderNo int NOT NULL,
P_Id int FOREIGN KEY REFERENCES Persons(P_Id)
)
Basic Retrieval Queries in SQL
• SELECT statement
– One basic statement for retrieving information
from a database.

SELECT column_name,column_name
FROM table_name;

SELECT * FROM table_name;
The SELECT-FROM-WHERE Structure of Basic
SQL Queries

• Basic form of the SELECT statement:

SELECT column_name,column_name SELECT * FROM Customers


FROM table_name WHERE CustomerID=1;
WHERE column_name operator value;
The SELECT-FROM-WHERE Structure of Basic
SQL Queries (cont’d.)

• Logical comparison operators


– =, <, <=, >, >=, and <>
• Projection attributes
– Attributes whose values are to be retrieved
• Selection condition
– Boolean condition that must be true for any
retrieved tuple
Ambiguous Attribute Names

• Same name can be used for two (or more)


attributes
– As long as the attributes are in different
relations
– Must qualify the attribute name with the
relation name to prevent ambiguity
Aliasing, Renaming, and Tuple
Variables
• Aliases or tuple variables
– Declare alternative relation names E and S
– EMPLOYEE AS E(Fn, Mi, Ln, Ssn, Bd,
Addr, Sex, Sal, Sssn, Dno)
Unspecified WHERE Clause
and Use of the Asterisk
• Missing WHERE clause
– Indicates no condition on tuple selection
• CROSS PRODUCT
– All possible tuple combinations
Unspecified WHERE Clause
and Use of the Asterisk (cont’d.)
• Specify an asterisk (*)
– Retrieve all the attribute values of the
selected tuples
The INSERT Structure of Basic SQL Queries

INSERT INTO table_name INSERT


VALUES (value1,value2,...); INTO table_name (column1,column2,...)
VALUES (value1,value2,value3,...);

Query 1:
INSERT a record of a person in PERSON table

INSERT INTO
Customers (P_Id, FirstName, LastName, Address City)
VALUES (‘1”, ‘Zahra’,‘Zahid’,‘Sialkot’, ‘Sialkot’);

INSERT INTO
Orders (O_Id, OrderNo, P_Id)
VALUES (1, 1000, 1);
Basic Retrieval Queries in SQL
• SELECT statement
– One basic statement for retrieving information
from a database.

SELECT column_name,column_name
FROM table_name;

SELECT * FROM table_name;
The SELECT-FROM-WHERE Structure of Basic
SQL Queries (cont’d.)

• Logical comparison operators


– =, <, <=, >, >=, and <>
• Projection attributes
– Attributes whose values are to be retrieved
• Selection condition
– Boolean condition that must be true for any
retrieved tuple
The SELECT-FROM-WHERE Structure of Basic SQL
Queries
Query 1:
Retrieve the person id, First name and City of Person(s).
SELECT P_Id, FirstName, City
FROM PERSON

Query 2:
Retrieve the person id, First name and City of Person(s)
whose Firs name is ‘Ahmed’
SELECT P_Id, FirstName, City
FROM PERSON
WHERE FirstName = ‘Ahmed’
Query 3:
Retrieve the person id, First name and City of Person(s)
whose id = ‘2’ and First name is ‘Ahmed’
SELECT P_Id, FirstName, City
FROM PERSON
WHERE P_Id = 2 AND FirstName = ‘Ahmed’
The UPDATE-WHERE Structure of Basic SQL Queries

UPDATE table_name
SET column1=value1,column2=value2,...
WHERE some_column=some_value;

Query 1:
Update First name and City of Person(s) where id is 3.
UPDATE PERSON
SET FirstName=‘Sabir', City=‘Lahore'
WHERE P_Id=‘3';
The DELETE Structure of Basic SQL Queries

DELETE FROM table_name
WHERE some_column=some_value;

Query 1:
Delete person whose id is 4
DELETE FROM PERSON
WHERE P_Id = 4
Comparisons Involving NULL
and Three-Valued Logic

• SQL allows queries that check whether an


attribute value is NULL
– IS or IS NOT NULL
Joined Tables in SQL and Outer Joins
• SQL joins are used to combine rows from two or more tables.
• An instruction to a database to combine data from more than one
table
• Types of JOINS:
– INNER JOIN: Returns all rows when there is at least one match in BOTH tables
– LEFT JOIN: Return all rows from the left table, and the matched rows from the
right table
– RIGHT JOIN: Return all rows from the right table, and the matched rows from the
left table
– FULL JOIN: Return all rows when there is a match in ONE of the tables
INNER JOIN
• The INNER JOIN creates a new result table by combining column values
of two tables (table1 and table2) based upon the join-predicate.
• The query compares each row of table1 with each row of table2 to find all
pairs of rows which satisfy the join-predicate.
• When the join-predicate is satisfied, column values for each matched pair
of rows of A and B are combined into a result row.

SELECT table1.column1, table2.column2...


FROM table1
INNER JOIN table2
ON table1.common_field = table2.common_field;
INNER JOIN
INNER JOIN

SELECT ID, NAME, AMOUNT, DATE


FROM CUSTOMERS
INNER JOIN ORDERS
ON CUSTOMERS.ID = ORDERS.CUSTOMER_ID;
LEFT JOIN
• The SQL LEFT JOIN returns all rows from the left table, even if there are no
matches in the right table.
• This means that if the ON clause matches 0 (zero) records in right table, the join
will still return a row in the result, but with NULL in each column from right table.
• This means that a left join returns all the values from the left table, plus matched
values from the right table or NULL in case of no matching join predicate

SELECT table1.column1, table2.column2...


FROM table1
LEFT JOIN table2
ON table1.common_field = table2.common_field;
LEFT JOIN

SELECT ID, NAME, AMOUNT, DATE


FROM CUSTOMERS
LEFT JOIN ORDERS
ON CUSTOMERS.ID = ORDERS.CUSTOMER_ID;
RIGHT JOIN
• The SQL RIGHT JOIN returns all rows from the right table, even if there
are no matches in the left table.
• This means that if the ON clause matches 0 (zero) records in left table, the
join will still return a row in the result, but with NULL in each column
from left table.
• This means that a right join returns all the values from the right table, plus
matched values from the left table or NULL in case of no matching join
predicate.

SELECT table1.column1, table2.column2...


FROM table1
RIGHT JOIN table2
ON table1.common_field = table2.common_field;
LEFT JOIN

SELECT ID, NAME, AMOUNT, DATE


FROM CUSTOMERS
RIGHT JOIN ORDERS
ON CUSTOMERS.ID = ORDERS.CUSTOMER_ID;
FULL JOIN
• The SQL FULL JOIN combines the results of both left and right outer
joins.
• The joined table will contain all records from both tables, and fill in
NULLs for missing matches on either side.

SELECT table1.column1, table2.column2...


FROM table1
FULL JOIN table2
ON table1.common_field = table2.common_field;
LEFT JOIN

SELECT ID, NAME, AMOUNT, DATE


FROM CUSTOMERS
FULL JOIN ORDERS
ON CUSTOMERS.ID = ORDERS.CUSTOMER_ID;
Aggregate Function:
Aggregate functions are functions that take a collection of
values as input and return a single value.

 Behavior of Aggregate Functions:


Operates - on a single column
Return - a single value.
Used only in the SELECT list and in the
HAVING clause.
Types of SQL Aggregate Functions

• SUM
• AVG
• MIN
• MAX
• COUNT
Input to Aggregate Function
• SUM and AVG :
 Operates only on collections of numbers .

• MIN , MAX and COUNT


 Operates on collection of numeric and non-numeric
data types.

 Each function eliminates NULL values and operates


on Non- null values.
Employee Table
create table Employee(
sno varchar(20) not null primary key,
fname varchar(255),
lname varchar(255),
salary int,
position varchar(255)
)

insert into employee(sno,fname,lname,salary,position)


values('SL100','Ahmed','Ali',30000,'Manager')

insert into employee(sno,fname,lname,salary,position)


values('SL101','Saqib','jahangir',24000,'Manager')

insert into employee(sno,fname,lname,salary,position)


values('SL102','Ruhma','Arif',12000,'Project Manager')

insert into employee(sno,fname,lname,salary,position)


values('SL103','Fizza','Azhar',12000,'Project Manager')

insert into employee(sno,fname,lname,salary,position)


values('SL104','Mohsin','Khan',12000,'Project Manager')

Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley


Employee Table

Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley


SUM()
Returns: The sum of the values in a specified column.

Example: Find the total/sum of the Managers salary

Query:

Result:
sum_salary
54000.00
Revised Query for AVG()
Query:

Result :
avg_salary
11000.00
MIN() and MAX()
Returns: MIN() returns the smallest value of a column.
MAX() returns the largest value of a column.

Example: Find the minimum and maximum staff salary.

Query:

Result: min_salary max_salary


9000.00 30000.00
COUNT()
Returns: The number of values in the specified column.

Example: Count number of staffs who are Manager.

Query:

Result:
sno_count
2
Use of COUNT() and SUM()
Example: Find the total number of Managers and the sum
of there salary.

Query:

Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley


COUNT(*)
Input: There is no input to this function.

Returns: It counts all the rows of a table , regardless of


whether Nulls or the duplicate occur.

Example: How many Project Manager salary is more than


9000.00

Query:
Usage of Aggregation Functions

• Use of GROUP BY

• Use of HAVING
Use of GROUP BY
The GROUP BY statement is used in conjunction with
the aggregate functions to group the result-set by one or
more columns.

Note: All column names in SELECT list must appear in the


GROUP BY clause unless the name is used only in the
aggregate function.
GROUP BY
Example: Find the number of staff working in each branch and
the sum of their salaries.
Query:

Result:

Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley


USE OF HAVING
HAVING clause: It is designed to be used with GROUP BY
so that it can restrict the groups that appear in the final result
table.

Example: For each branch office with more than one member
of staff, find the number of staff working in each
branch and the sum of their salaries.

Query:

You might also like