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

S07 Slides

Uploaded by

mathycheok
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views

S07 Slides

Uploaded by

mathycheok
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 17

7/22/2020

Seminar 7:
SQL

Learning Objectives
In this lecture, you will learn
 SQL introduction
 SQL syntax

1
7/22/2020

Database Fundamentals
• Database contains Database Tables, each
identified by a table name.
• Each Tables contains rows or records.
• Each record contains
columns/fields/attributes (these 3 terms refer
to the same thing).
• Every column has a name and contains data
of a specific type : string, integer, real(float)
and so on.

Relational Database management


systems (DBMS)
• A software package designed to define,
manipulate, retrieve and manage data in a
database
• Some popular ones are:
– DB2 and Informix Dynamic Server - IBM
– MySQL, Oracle and RDB – Oracle
– SQL Server and Access - Microsoft

2
7/22/2020

Relational Data Model in DBMS


• RELATIONAL MODEL (RM) represents the database as a
collection of relations.
• A relation is nothing but a table of values.
• Every row in the table represents a collection of related data values.
• These rows in the table denote a real-world entity or relationship.
Conceptural Relation model
Database Tables
Physical Receipts

SQL Overview
• The standard language for relational database
management systems (RDBMS).
• RDBMS: A database management system that
manages data as a collection of tables in which all
relationships are represented by common values
in related tables.
• The American National Standards Institute (ANSI)
prescribes a standard SQL. The ANSI SQL is also
accepted by International Organization for
Standardization (ISO).

3
7/22/2020

SQL Introduction
• Relatively easy to learn
• Several SQL dialects exist: DB2, MySQL,
MSSQL, Oracle, SQLite, etc.
• Specify syntax/semantics for data
definition and manipulation.
• Define data structures.
• Enable portability.
7

SQL Environment
• Catalog
– A set of schemas that constitute the description of a database
• Schema
– The structure that contains descriptions of objects created by user.
• Data Definition Language (DDL)
– Commands to create, alter, drop database objects like tables, indexes,
and views.
• Data Manipulation Language (DML)
– Commands to insert, update, delete, and retrieve database objects.
• Data Control Language (DCL)
– Commands to control and administer privileges.

4
7/22/2020

When and how to use SQL?


• SQL query is to answer questions such as:
– How many inventories has profit margin of 30%?
– What are the products that cost below $50 and
above $20?
• Steps:
– Start with creating database structure.
– Create tables base on entities.
– Load data into database by using INSERT
statements
– Extract data by using SELECT statements.

SQL Data Definition Language


(DDL)
• CREATE SCHEMA  FOREIGN KEY
AUTHORIZATION
 DEFAULT
• CREATE TABLE
• CREATE INDEX  CHECK
• CREATE VIEW  DROP TABLE
• ALTER TABLE (AS)
• NOT NULL  DROP INDEX
• UNIQUE  DROP VIEW
• PRIMARY KEY

10

10

5
7/22/2020

SQL Data Types

11

11

1. Creating Database
• The first step in creating database is to create a
structure for database -> Schema.
• The relevant physical files that will hold the
database will then be initialized together with
administrator rights.
• For Microsoft Access, creation of database is
straightforward. Other RDBMS requires SQL
commands like the following:
– CREATE SCHEMA AUTHORIZATION
CREATOR_NAME;

12

12

6
7/22/2020

SQL Constraint
NOT NULL constraint
◦ Ensures that a column does not accept nulls

UNIQUE constraint
◦ Ensures that all values in a column are unique

DEFAULT constraint
◦ Assigns a value to an attribute when a new row is added to a table

CHECK constraint
◦ Validates data when an attribute value is entered

13

13

2. Creating Table Structures


• After database structure has been created, table structures need to
be defined.
• Definition of table structures include providing the CREATE TABLE
command plus NAME of table then (COLUMN_NAME
DATATYPE(LENGTH) CONSTRAINT, …) Constraint
• CREATE TABLE MANAGER (
MANAGER_CODE INTEGER NOT NULL UNIQUE,
NAME VARCHAR(50) NOT NULL,
Data types
PRIMARY KEY (MANAGER_CODE));

14

14

7
7/22/2020

2. Creating Table
Structures with
Foreign Key
CREATE TABLE EXECUTIVE (
EXECUTIVE_CODE INTEGER
NOT NULL UNIQUE,
NAME VARCHAR(50) NOT
NULL,
MANAGER_CODE INTEGER,
For every manager, there
PRIMARY KEY will be many executives
(EXECUTIVE_CODE),
FOREIGN KEY Executive
(MANAGER_CODE) Manager

REFERENCES
PK Executive_Code
PK Manager_Code manages

MANAGER(MANAGER_CODE) Name
Name
); FK Manager_Code

For every executive, there will only be 1


manager

15

SQL Data Manipulation Language


(DML)

16

16

8
7/22/2020

DML Operators and Functions

17

17

3. Insert Data to
Table

• Syntax:
– INSERT INTO
TABLE_NAME VALUES (X,
Y, Z);
• Example:
– INSERT INTO MANAGER
VALUES (1002, "Mary" ); Executive
Manager
• Missing value: PK Executive_Code
PK Manager_Code
– If null is allowed, add in the
manages

Name

missing value as NULL Name


FK Manager_Code

18

18

9
7/22/2020

3. Insert Data to Table


• Syntax:
– INSERT INTO TABLE_NAME(COL_NAME,
COL2_NAME) VALUES (X, Y);
• Example:
– INSERT INTO MANAGER(MANAGER_CODE,
NAME) VALUES (1003, "Jenny");
• This is useful for insertion to specific fields, other
fields which are not specified may be optional for
insertion.

19

19

4. Querying Data
• Syntax:
– SELECT COLUMN_LIST FROM TABLE_NAME;
• Example:
– SELECT MANAGER_CODE, NAME FROM MANAGER;
• This will list out manager_code and name from
manager table.
• Equivalent SQL using * asterisk to denote list out all
fields.
– SELECT * FROM MANAGER;
• Select unique values.
– SELECT DISTINCT NAME FROM MANAGER;
20

20

10
7/22/2020

Aggregate Functions for SQL


• COUNT
– SELECT COUNT(*) FROM MANAGER;
• MIN
– SELECT MIN(PORTFOLIO_VALUE) FROM MANAGER;
• MAX
– SELECT MAX(PORTFOLIO_VALUE) FROM MANAGER;
• SUM
– SELECT SUM(PORTFOLIO_VALUE) AS TOTAL_VALUE FROM
MANAGER;
• AVG
– SELECT AVG(PORTFOLIO_VALUE) FROM MANAGER;

21

21

Ordering the result


• ORDER BY
– SELECT NAME, PORTFOLIO_VALUE
FROM MANAGER
ORDER BY PORTFOLIO_VALUE;
• ORDER BY, DESC
– SELECT NAME, PORTFOLIO_VALUE
FROM MANAGER
ORDER BY PORTFOLIO_VALUE DESC;
22

22

11
7/22/2020

WHERE clause
• WHERE condition
– SELECT NAME, PORTFOLIO_VALUE FROM MANAGER
WHERE PORTFOLIO_VALUE >= 50000
ORDER BY PORTFOLIO_VALUE;
• Boolean Operators to customize WHERE condition
– and, or, not
• Comparison Operators
– =. <, <=, >, >=, <> (not equal)
AS for giving alias
• Arithmetic Operators name to the result.
– +, -, *, /, ^ (to the power of)
– SELECT PORTFOLIO_VALUE, PORTFOLIO_VALUE * 1.3 AS USD_EQV
FROM MANAGER;

23

23

Other Operators
• BETWEEN SELECT * FROM MANAGER
– Look for values within a range WHERE PORTFOLIO_VALUE BETWEEN 30000 AND 50000;
• IS NULL
– Check if an attribute value is null
• LIKE SELECT * FROM MANAGER
– Matching pattern with string WHERE NAME LIKE ‘Je%';

• EXISTS
– Check if the sql statement returns any result
• IN
– Check existence of value in a list of value

24

24

12
7/22/2020

GROUP BY Statement
• GROUP BY clause is used to create frequency
distribution of data, grouping data into a few groups to
summarise the data.
• It is often used in conjunction with aggregate functions.
– SELECT COUNT(*),DEPARTMENT FROM MANAGER
GROUP BY DEPARTMENT;

25

25

HAVING + GROUP BY
• Having filters results after GROUP BY.
• It sets the condition with comparison operators and
displays only results that satisfies this condition
– SELECT COUNT(*),DEPARTMENT FROM MANAGER
GROUP BY DEPARTMENT
HAVING COUNT(*) >= 2;

26

26

13
7/22/2020

Joining tables
Executive
Manager
PK Executive_Code
PK Manager_Code manages

Name
Name
FK Manager_Code

• SELECT * FROM MANAGER, EXECUTIVE


WHERE MANAGER.MANAGER_CODE =
EXECUTIVE.MANAGER_CODE;

27

27

Join clause
• SQL Join clause is used to combine records from
two or more tables.
• Join will combine the respective fields set within
JOIN requirements and match the values.
• INNER JOIN combines the results similar to AND
operation look for values common to both tables.
• OUTER JOIN keeps the non-matching results
when join is done.

28

28

14
7/22/2020

Inner Join
Executive
Manager
PK Executive_Code
PK Manager_Code manages

Name
Name
FK Manager_Code

• SELECT * FROM MANAGER M INNER JOIN


EXECUTIVE E
on M.MANAGER_CODE = E.MANAGER_CODE;

29

29

SQL Outer Joins

• LEFT JOIN, left table records will be


shown even for non-matching results.
• RIGHT JOIN, right table records will be
shown even for non-matching results.
[Not supported by SQLite]
• FULL JOIN, join left and right tables all
records. [Not supported by SQLite]

30

30

15
7/22/2020

Right join example

• SELECT * FROM MANAGER M RIGHT JOIN


EXECUTIVE E
on M.MANAGER_CODE = E.MANAGER_CODE;

31

31

Subqueries
• For nested selection, subquery can be used
to generate information. Runs the inner query
first, then apply outer queries on the inner
queries.

• SELECT NAME FROM MANAGER


WHERE PORTFOLIO_VALUE >= (
SELECT AVG(PORTFOLIO_VALUE) FROM
MANAGER);
32

32

16
7/22/2020

IN Operator
• The IN operator allows multiple values to be specified to
match with the column name.
• SELECT NAME FROM MANAGER
WHERE MANAGER_CODE IN (1001, 1003);

• SELECT NAME FROM MANAGER


WHERE MANAGER_CODE IN (
SELECT MANAGER_CODE FROM EXECUTIVE);

33

33

You have learnt...


1. Overview of SQL.
2. SQL statements.

34

34

17

You might also like