NCCU DBMS Spring 2024 - Week - 04 - SQL - Student Version - Print
NCCU DBMS Spring 2024 - Week - 04 - SQL - Student Version - Print
Management
Systems
Course No. 306008001 & 306008011
Instructor: Chih-Yuan Chou
Mar 12, 19, 26 & Mar 14, 21, 28, 2024
Lecture 4, 5, & 6- SQL
Your 1st booked TA consulting session by group
We may change your responsible TAs temporarily if time conflicts occur. Note that all our TAs will be able to help you during the semester.
Sandy + Julian + Pei-Han John + Richard + Bo-Yi Wen-Jing + Meng-Mei Andy + Mavis
2024/3/15
16:30-17:00 Group 03
(Friday)
Location: College of Commerce Building 260526 Please get ready with your needs analysis findings (HW1), initial ERD,
(5th floor, IT Innovation Lab ) and proposed functional decomposition diagram. Also, kindly wait
Turn LEFT after leaving the elevators. patiently outside if the preceding group requires more time.
© 2024 Spring (112-2) NCCU Department of MIS, DBMS Course
SQL
Introduction to SQL
SQL Overview
Structured Query Language
History of SQL
1970 E. F. Codd develops relational database concept Donald Chamberlin & Raymond Boyce
1974-79 System R with Sequel (later SQL) created at IBM Research Lab
1979 Oracle markets first relational DB with SQL
1981 SQL/DS first available RDBMS system on DOS/VSE
Others followed: INGRES (1981), IDM (1982), DG/SGL (1984), Sybase (1986)
1986 ANSI SQL standard released
Major ANSI standard updates in 1989, 1992, 1999, 2003, 2006, 2008, 2011, 2016,
2019
Today SQL is supported by most major database vendors
Oracle, Microsoft SQL Server, IBM DB2, MySQL, Postgre SQL, etc.
Original Purpose of SQL Standard
Specify syntax/semantics for data definition and manipulation
Define data structures and basic operations
Enable portability of database definition and application
modules
Specify minimal (level 1) and complete (level 2) standards
Allow for later growth/enhancement to standard (referential
integrity, transaction management, user-defined functions,
extended join operations, national character sets)
Strings
BIT VARING(n): varying length bit string
DML :
INSERT
UPDATE
DELETE
SELECT
DCL :
GRANT
ADD
REVOKE
ORDER BY (ASC/DESC)
BUILT-IN FUNCTIONS
UNION
Common build-in functions or operators
COUNT() NOT
SUM() AND
AVG() OR
MAX() DATEDIFF (get the time difference, dialect exists)
MIN() LIKE
ABS() (get absolute value) AS
ROUND() (get round value) LIMIT/TOP (limit the query, dialect exists: LIMIT
for MySQL, TOP for SQL server)
BETWEEN
(NOT) EXISTS
IF ()
ALL
LEAD (), LAG()
ANY
ROWNUM(), RANK(), DENSE_RANK()
(NOT) IN
DISTINCT
When you are in a hurry without your own SQL environment, use it.
SQL
Free SQL environment for command testing
SQL Fiddle: https://sqlfiddle.com/
MySQL Online: https://paiza.io/en/projects/new?language=mysql
DB Fiddle: https://www.db-fiddle.com/
SQL Online: https://sqliteonline.com/
Oracle Live SQL: https://livesql.oracle.com/apex/f?p=590:1000
Note: these free platforms may have security/privacy problems. DO NOT upload your real data.
We recommend creating a real database on your localhost computer. Instructions for MySQL
installations have been provided during our TA sessions. MS SQL Server, PostgreSQL, SQLite, and
other NoSQL platforms such as MongoDB and Redis are also possible options.
Introduction to DDL
Data Definition Language (DDL)
Major CREATE statements:
CREATE SCHEMA defines a portion of the database owned by a
particular user
CREATE TABLE defines a new table and its columns
CREATE VIEW defines a logical table from one or more tables or
views
Other CREATE statements: CHARACTER SET, COLLATION,
TRANSLATION, ASSERTION, DOMAIN
Create/Drop Database /
[] (optional)
{} (multiple choices)
The Following Slides Create Tables for This Enterprise Data Model
Customer_ID Customer_Name
(from Chapter 1, Figure 1-3)
Standard_Price
Places
Has
Order_ID
Product_ID
Order_ID
Order_Date Quantity
Non-Nullable Specifications
Some primary keys are composite composed of multiple attributes
Controlling the Values in Attributes
Domain constraint
Figure 5-7
Ensuring Data 1
Integrity
Through
Updates 2
Table Actions:
,
Removing Tables
DROP TABLE statement allows you to remove tables from
your schema:
,
Create Indexes
Speed up random/sequential access to base table data
Example
CREATE INDEX NAME_IDX ON CUSTOMER_T(CUSTOMERNAME)
This makes an index for the CUSTOMERNAME field of the
CUSTOMER_T table
Introduction to DML
INSERT Statement
Adds one or more rows to a table
Inserting into a table:
,
Inserting into a table does not require explicit customer ID entry or field list.
DELETE Statement
Removes rows from a table
Delete certain rows
,
UPDATE Statement
Modifies data in existing rows
Example
UPDATE Product_T
SET ProductStandardPrice = 775
WHERE ProductID = 7;
Example
Practices
UPDATE PACKAGE
SET PACKNAME = 'MANTA II'
WHERE
Delete data: DELETE
Example: Delete from the database the employee whose
phone number is 8716.
DELETE FROM EMPLOYEE
WHERE EMPHONE = 8716;
SELECT Statement (SQL Query)
Used for queries on single or multiple tables
Clauses of the SELECT statement:
SELECT: List the columns (and expressions) to be returned from the query
FROM: Indicate the table(s) or view(s) from which data will be obtained
WHERE: Indicate the conditions under which a row will be included in the
result
GROUP BY: Indicate categorization of results
HAVING: Indicate the conditions under which a category (group) will be
included
ORDER BY: Sorts the result according to specified criteria
Example: List the complete PC table.
Query: SELECT SELECT *
FROM WHERE FROM PC;
Query: SELECT
FROM WHERE
Example: What is the name
of employee 124?
SELECT EMPNAME
FROM EMPLOYEE
WHERE EMPNUM = 124;
The computer responds with:
EMPNAME
Alvarez, Ramon
Substring Comparisons, Arithmetifc Operations
SQL allows comparison conditions on only parts of a character string,
using the LIKE comparison operator
Partial strings are specified using '%' replaces an arbitrary number of
characters
Ex: Retrieve all employees whose address is in Houston, Texas
SELECT FNAME, LNAME
FROM EMPLOYEE
WHERE ADDRESS LIKE '%Houston,TX%
55
Example: Find the package ID and name for any package whose type
is Database.
SELECT PACKID, PACKNAME
FROM PACKAGE
WHERE
Query with compound conditions
Compound conditions are formed by connecting two or more simple
conditions using AND, OR, and NOT. (Boolean operators)
Example: List the names of all packages whose type is Database and
whose cost is over $400.
By default, processing order of Boolean
SELECT PACKNAME operators is NOT, then AND, then OR
FROM PACKAGE
WHERE PACKTYPE = 'Database' AND PACKCOST > 400;
The computer will respond with:
PACKNAME
Manta
Nesting Queries
Example : List the package ID and name for all packages whose cost is
greater than the average cost of the database packages.
Without nesting queries in two steps.
2. After viewing the answer (405.09), we could use the following
SELECT statement to do the query.
SELECT PACKID, PACKNAME
FROM PACKAGE
WHERE PACKCOST > 405.09;
The computer will respond with:
PACKID PACKNAME
AC01 Boise Accounting
DB33 Manta
Nesting Queries
Example : List the package ID and name for all packages whose cost is
greater than the average cost of the database packages.
With nesting queries in one step.
SELECT PACKID, PACKNAME The portion in parentheses is called a
FROM PACKAGE subquery.
WHERE PACKCOST > This subquery is evaluated first.
(SELECT AVG (PACKCOST)
FROM PACKAGE
WHERE PACKTYPE = 'Database');
The computer will respond with:
PACKID PACKNAME
AC01 Boise Accounting
DB33 Manta
Query by Union
Example : List the computer ID and manufacturer name of all
computers which either have a 486DX processor or have been
assigned for home use, or both.
Query by Union
Example : List the computer ID and manufacturer name of all
computers which either have a 486DX processor or have been
assigned for home use, or both.
SELECT COMPID, MFGNAME
FROM COMPUTER
WHERE PROCTYPE = '486DX'
UNION
SELECT COMPUTER.COMPID, MFGNAME
FROM COMPUTER, PC
WHERE COMPUTER.COMPID = PC.COMPID
AND LOCATION = 'HOME';
Query by Union
Example : List the computer ID and manufacturer name of all
computers which either have a 486DX processor or have been
assigned for home use, or both.
The computer responds with:
COMPID MFGNAME
B121 Bantam
B221 Bantam
C007 Cody
M759 Lemmin
Creating a New Table from an Existing Table
Example : Create a new table called DBPACK containing the package
ID, name, version, and cost for all rows in the PACKAGE table of type
Database.
The first thing to do is to describe this new table using the data
definition facilities of SQL, as follows:
CREATE TABLE DBPACK
(PACKID CHAR(4),
PACKNAME CHAR(20),
PACKVER DECIMAL(3, 2),
PACKCOST DECIMAL (5, 2));
Join
Multiple Tables
Outer join: A join in which rows that do not have
matching values in common columns are nonetheless
included in the result table (as opposed to inner join,
in which rows must have matching values in order to
appear in the result table)
Union
Includes all data from each table that was joined
Unions are not literally joins
Visualization of
Different Join
Types with
Results
Returned in
Shaded Area
The Following Slides Create Tables for This Enterprise Data Model
Customer_ID Customer_Name
(from Chapter 1, Figure 1-3)
Standard_Price
Places
Has
Order_ID
Product_ID
Order_ID
Order_Date Quantity
Example
1 Jack 1 1 MIS 3
2 Rose 2 2 BA 4
3 Vicky 1 4 FI 5
4 Jane 2
5 Samuel 3
Example
1 Jack 1 1 MIS 3
2 Rose 2 2 BA 4
3 Vicky 1 4 FI 5
4 Jane 2
5 Samuel 3
Source: https://www.w3resource.com/sql/joins/perform-an-equi-join.php
Example
1 Jack 1 1 MIS 3
2 Rose 2 2 BA 4
3 Vicky 1 4 FI 5
4 Jane 2
5 Samuel 3
Example
1 Jack 1 1 MIS 3
2 Rose 2 2 BA 4
3 Vicky 1 4 FI 5
4 Jane 2
5 Samuel 3
Equi-Join
Example
What are the customer
IDs and names of all
customers, along with
the order IDs for all the
orders they have placed?
Equi-Join Example Alternative Syntax An INNER Join
INNER JOIN clause is an alternative to WHERE clause, and is used to match primary
and foreign keys.
An INNER join will only return rows from each table that have matching rows in the
other.
This query produces the same results as the previous equi-join example.
Outer-Join Example
List the customer name, ID number, and order number for all customers. Include
customer information even for customers that do not have an order.
LEFT OUTER JOIN clause causes rows from the first mentioned table (customer) to
appear even if there is no corresponding order data.
Unlike an INNER join, this will include customer rows with no matching order rows.
All rows returned from this query will pertain to OrderID 1006.
Note that the full query results include columns from four different tables.
The same table is used on both sides of the join; distinguished using table aliases. See
the next slide for details.
Self join involve tables that
Example of a Self Join implement 1-to-many unary
relationships.
Subqueries
Subqueries
Subquery placing an inner query (SELECT statement) inside an outer query
Options:
In a condition of the WHERE clause
Subquery Approach
Alternative Approach, Using a Join
What are the name and address of the customer who placed order number 1008?
Join Query
Approach
Subquery Approach
Noncorrelated subqueries:
Do not depend on data from the outer
query
Correlated Execute once for the entire outer query
versus.
Noncorrelated Correlated subqueries:
Subqueries Make use of data from the outer query
Execute once for each row of the outer
query
Can use the EXISTS, ALL, and ANY operators
Example of a Correlated Subquery
List the details about the product with the highest standard price.
Here, the subquery forms the derived table used in the FROM clause of the outer
query. The AvgPrice column from the subquery is used in the SELECT clause of the
outer query.
UNION
CASE
Introduction
Conditional Expressions Using Case Keyword
Views
-joins)
Learn!
Consider the total query processing time for ad hoc queries
Dynamic View
Using and request by a user
Materialized View
Copy or replication of data, data actually
stored
Must be refreshed periodically to match
corresponding base tables
Introduction
Routines
Program modules that execute on demand
Functions
routines that return values and take input
parameters
Routines and Procedures
Triggers routines that do not return values and can
take input or output parameters
Triggers
routines that execute in response to a
database event (INSERT, UPDATE, or
DELETE)
SQL
ORDER BY
BUILT-IN FUNCTIONS
GROUP BY
UNION
JOIN
Common build-in functions or operators
COUNT() (NOT) IN
SUM() DISTINCT
AVG() NOT
MAX() AND
MIN() OR
ABS() (get absolute value) DATEDIFF (get the time difference, dialect exists)
ROUND() (get round value) LIKE
BETWEEN AS
EXISTS LIMIT/TOP/ROWNUM (limit the query, dialect
exists: LIMIT for MySQL, TOP for SQL server)
ALL
CASE
ANY
SQL Statement Processing Order
(based on van der Lans, 2006, p. 100)
SQL Enhancements/Extensions (2 of 2)
Programming extensions
Persistent Stored Modules (SQL/PSM)
Capability to create and drop code modules
New statements: CASE, IF, LOOP, FOR, WHILE, etc.
Makes SQL into a procedural language
Oracle has propriety version called PL/SQL, and Microsoft SQL Server
has Transact/SQL (T-SQL)
CASE or IF?
SELECT FirstName, LastName, Salary, DOB, SELECT FirstName, LastName, Salary, DOB,
CASE Gender IF (Gender='M', 'Male', 'Female')
WHEN 'M' THEN 'Male' FROM Employees
WHEN 'F' THEN 'Female'
ELSE 'Others'
END
FROM Employees;
GROUP BY normally reduces the number of rows returned by rolling them up and calculating
averages or sums for each row. GROUP BY query row
PARTITION BY does not affect the number of rows returned, but it changes how a window
function's result is calculated. PARTITION BY window function row
Source: https://stackoverflow.com/questions/2404565/sql-difference-between-partition-by-and-group-by
TA Discussion Sessions
Mavis Tsai Meng Mei Chen Andy Lee Sandy Lee Richard Lin
MS Student MS Student MS Student MS Student MS Student
[email protected] [email protected] [email protected] [email protected] [email protected]
Pei Han Hao Wen Jing Chen John Jiang Julian Lee Bo-Yi Li
MS Student MS Student MS Student MS Student PhD Candidate
[email protected] [email protected] [email protected] [email protected] [email protected]