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

Intro-To-SQL

The document provides an overview of SQL, its history, and its role as the standard language for relational database management systems. It covers key concepts such as data definition and manipulation languages, data types, and commands for creating, altering, and querying tables. Additionally, it discusses the benefits of standardized relational languages and outlines various SQL statements and their functionalities.

Uploaded by

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

Intro-To-SQL

The document provides an overview of SQL, its history, and its role as the standard language for relational database management systems. It covers key concepts such as data definition and manipulation languages, data types, and commands for creating, altering, and querying tables. Additionally, it discusses the benefits of standardized relational languages and outlines various SQL statements and their functionalities.

Uploaded by

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

Analisis Data Bisnis

Lecture 13
Introduction to SQL

Copyright © 2022, 2019, 2016 Pearson Education, Inc. All Rights Reserved
SQL Overview
• Structured Query Language – often pronounced
“Sequel”
• The standard 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

Copyright © 2022, 2019, 2016 Pearson Education, Inc. All Rights Reserved
History of SQL
• 1970 – E. F. Codd develops relational database concept

• 1974-79 – System R with Sequel (later SQL) created at IBM Research Lab

• 1979 – Oracle markets first relational D B 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
• Today – SQL is supported by most major database vendors

Is SQL a standard? No longer certified by NIST.

Copyright © 2022, 2019, 2016 Pearson Education, Inc. All Rights Reserved
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)

Copyright © 2022, 2019, 2016 Pearson Education, Inc. All Rights Reserved
Benefits of a Standardized Relational
Language
• Reduced training costs
• Productivity
• Application portability
• Application longevity
• Reduced dependence on a single vendor
• Cross-system communication

Copyright © 2022, 2019, 2016 Pearson Education, Inc. All Rights Reserved
SQL Environment
• Catalog
– A set of schemas that constitute the description of a database
• Schema
– The structure that contains descriptions of objects created by a user
(base tables, views, constraints)
• Data Definition Language (DDL)
– Commands that define a database, including creating, altering, and
dropping tables and establishing constraints
• Data Manipulation Language (DML)
– Commands that maintain and query a database
• Data Control Language (DCL)
– Commands that control a database, including administering privileges
and committing data

Copyright © 2022, 2019, 2016 Pearson Education, Inc. All Rights Reserved
Figure 5-1 A Simplified Schematic of a Typical SQL
Environment, as Described by the SQL:2016 Standards

Copyright © 2022, 2019, 2016 Pearson Education, Inc. All Rights Reserved
SQL Data Types
• Strings
– CHARACTER (n), VARYING CHARACTER (n)
• Binary
– Binary Large Object (BLOB)
• Number
– Numeric (precision, scale), Decimal (p, s), Integer
• Temporal
– Timestamp, Timestamp with local time zone
• Boolean
– True or False values
Copyright © 2022, 2019, 2016 Pearson Education, Inc. All Rights Reserved
Figure 5-4 DDL, DML, DCL, and the
Database Development Process

Copyright © 2022, 2019, 2016 Pearson Education, Inc. All Rights Reserved
SQL Database Definition
• 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

Copyright © 2022, 2019, 2016 Pearson Education, Inc. All Rights Reserved
Steps in Table Creation
1. Identify data types for attributes
2. Identify columns that can and cannot be null
3. Identify columns that must be unique (candidate keys)
4. Identify primary key–foreign key mates
5. Determine default values
6. Identify constraints on columns (domain specifications)
7. Create the table and associated indexes

Copyright © 2022, 2019, 2016 Pearson Education, Inc. All Rights Reserved
Figure 5-5 General Syntax of the CREATE TABLE
Statement Used in Data Definition Language

Copyright © 2022, 2019, 2016 Pearson Education, Inc. All Rights Reserved
The Following Slides Create Tables for
This Enterprise Data Model

(from Chapter 1, Figure 1-3)


Copyright © 2022, 2019, 2016 Pearson Education, Inc. All Rights Reserved
Figure 5-6 SQL Database Definition Commands for
Pine Valley Furniture Company (Oracle 12c)

Copyright © 2022, 2019, 2016 Pearson Education, Inc. All Rights Reserved
Defining Attributes and Their Data Types

Copyright © 2022, 2019, 2016 Pearson Education, Inc. All Rights Reserved
Non-Nullable Specifications
Some primary keys are composite– composed of multiple
attributes

Copyright © 2022, 2019, 2016 Pearson Education, Inc. All Rights Reserved
Controlling the Values in Attributes

Copyright © 2022, 2019, 2016 Pearson Education, Inc. All Rights Reserved
Identifying Foreign Keys and
Establishing Relationships

Copyright © 2022, 2019, 2016 Pearson Education, Inc. All Rights Reserved
Data Integrity Controls
• Referential integrity – constraint that ensures that foreign
key values of a table must match primary key values of a
related table in 1: N relationships

• Restricting:
– Deletes of primary records
– Updates of primary records
– Inserts of dependent records

Copyright © 2022, 2019, 2016 Pearson Education, Inc. All Rights Reserved
Figure 5-7 Ensuring Data Integrity
Through Updates
Relational integrity is enforced via the primary-key to foreign-key match

Copyright © 2022, 2019, 2016 Pearson Education, Inc. All Rights Reserved
Changing Tables
• ALTER TABLE statement allows you to change column
specifications:
– ALTER TABLE table_name alter_table_action;
• Table Actions:
– ADD [COLUMN] column_definition
– ALTER [COLUMN] column_name SET DEFAULT default-
value
• Example (adding a new column with a default value):
– ALTER TABLE CUSTOMER_T ADD CustomerType
VARCHAR2 (10) DEFAULT ‘Commercial’;

Copyright © 2022, 2019, 2016 Pearson Education, Inc. All Rights Reserved
Removing Tables
• DROP TABLE statement allows you to remove tables
from your schema:
– DROP TABLE Customer_T

Copyright © 2022, 2019, 2016 Pearson Education, Inc. All Rights Reserved
INSERT Statement
• Adds one or more rows to a table
• Inserting into a table:
– INSERT INTO Customer_T VALUES (001, ‘Contemporary
Casuals’, ‘1355 S. Himes Blvd.’, ‘Gainesville’, ‘F L’, ‘32601’);
• Inserting a record that has some null attributes requires identifying
the fields that actually get data:
– INSERT INTO Product_T (ProductID, ProductDescription,
ProductFinish, ProductStandardPrice) VALUES (1, ‘End Table’,
‘Cherry’, 175, 8);
• Inserting from another table:
– INSERT INTO CaCustomer_T SELECT * FROM Customer_T
WHERE CustomerState = ‘CA’;

Copyright © 2022, 2019, 2016 Pearson Education, Inc. All Rights Reserved
Creating Tables With Identity Columns
Inserting into a table does not require explicit customer I D entry or
field list.

INSERT INTO Customer_T VALUES (‘Contemporary Casuals’, ‘1355


S. Himes Blvd.’, ‘Gainesville’, ‘FL’, ‘32601’);

Copyright © 2022, 2019, 2016 Pearson Education, Inc. All Rights Reserved
Defining a table

CREATE TABLE share (


shrcode CHAR(3),
shrfirm VARCHAR(20)NOT NULL,
shrprice DECIMAL(6,2),
shrqty DECIMAL(8),
shrdiv DECIMAL(5,2),
shrpe DECIMAL(2),
PRIMARY KEY(shrcode));

Copyright © 2022, 2019, 2016 Pearson Education, Inc. All Rights Reserved
25
Inserting rows

INSERT INTO share

(shrcode,shrfirm,shrprice,shrqty,shrdiv,shrpe)

VALUES ('FC','Freedonia Copper',27.5,10529,1.84,16);

Or

INSERT INTO share

VALUES ('FC','Freedonia Copper',27.5,10529,1.84,16);

Copyright © 2022, 2019, 2016 Pearson Education, Inc. All Rights Reserved
26
Latihan SQL
CREATE TABLE ship ( CREATE TABLE track (
regcode VARCHAR(15), trkid INTEGER,
shipname VARCHAR(30), tracknum INTEGER,
grosston INTEGER, title VARCHAR(20),
yearconstruct SMALLINT, length DECIMAL(4,2),
classification VARCHAR(10), PRIMARY KEY (trkid));
PRIMARY KEY (regcode));

Copyright © 2022, 2019, 2016 Pearson Education, Inc. All Rights Reserved
DELETE Statement
• Removes rows from a table
• Delete certain rows
– DELETE FROM Customer_T WHERE
CustomerState = ‘HI’;
• Delete all rows
– DELETE FROM Customer_T;

Copyright © 2022, 2019, 2016 Pearson Education, Inc. All Rights Reserved
UPDATE Statement
• Modifies data in existing rows
– UPDATE Product_T SET
ProductStandardPrice = 775 WHERE
ProductID = 7;

Copyright © 2022, 2019, 2016 Pearson Education, Inc. All Rights Reserved
MERGE Statement
Makes it easier to update a table. It allows combination of
Insert and Update in one statement.
Useful for updating master tables with new data.

Copyright © 2022, 2019, 2016 Pearson Education, Inc. All Rights Reserved
Schema Definition
• Control processing/storage efficiency:
– Choice of indexes
– File organizations for base tables
– File organizations for indexes
– Data clustering
– Statistics maintenance

• Creating 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

Copyright © 2022, 2019, 2016 Pearson Education, Inc. All Rights Reserved
SELECT Statement
• 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

Copyright © 2022, 2019, 2016 Pearson Education, Inc. All Rights Reserved
SELECT Example
• Find products with standard price less than $275

• Comparison operators include


– = Equal to
– > Greater than
– >= Greater than or equal to
– < Less than
– <= Less than or equal to
– <> Not equal to
– != Not equal to
Copyright © 2022, 2019, 2016 Pearson Education, Inc. All Rights Reserved
SELECT Example Using Alias
• Alias is an alternative column or table name

SELECT CUST.CustomerName AS Name,


CUST.CustomerAddress
FROM Customer_T AS Cust WHERE Name =
‘Home Furnishings’;

Copyright © 2022, 2019, 2016 Pearson Education, Inc. All Rights Reserved
SELECT Example Using a Function
• Using the COUNT aggregate function to find totals

SELECT COUNT (*) FROM OrderLine_T


WHERE OrderID = 1004;

• Note: With aggregate functions you can’t have single-


valued columns included in the SELECT clause, unless
they are included in the GROUP BY clause.

Copyright © 2022, 2019, 2016 Pearson Education, Inc. All Rights Reserved
SELECT Example – Boolean Operators
• AND, OR, and NOT Operators for customizing
conditions in WHERE clause

SELECT ProductDescription, ProductFinish,


ProductStandardPrice
FROM Product_T
WHERE ProductDescription LIKE ‘%Desk’
OR ProductDescription LIKE ‘%Table’
AND ProductStandardPrice > 300;

Copyright © 2022, 2019, 2016 Pearson Education, Inc. All Rights Reserved
Figure 5-8 Boolean Query a Without the
Use of Parentheses
By default, processing order of Boolean operators is NOT, then
AND, then OR

Copyright © 2022, 2019, 2016 Pearson Education, Inc. All Rights Reserved
SELECT Example–Boolean Operators
• With parentheses…these override the normal precedence of
Boolean operators

SELECT ProductDescription, ProductFinish,


ProductStandardPrice
FROM Product_T
WHERE (ProductDescription LIKE ‘%Desk’
OR ProductDescription LIKE ‘%Table’)
AND ProductStandardPrice > 300;

With parentheses, you can override normal precedence rules. In


this case parentheses make the OR take place before the AND.

Copyright © 2022, 2019, 2016 Pearson Education, Inc. All Rights Reserved
Figure 5-9 Boolean Query B With Use of
Parentheses
With parentheses, you can override normal precedence rules. In this
case parentheses make the OR take place before the AND.

Copyright © 2022, 2019, 2016 Pearson Education, Inc. All Rights Reserved
Sorting Results With ORDER BY Clause
• Sort the results first by STATE, and within a state by the
CUSTOMER NAME

SELECT CustomerName, CustomerCity, CustomerState


FROM Customer_T
WHERE CustomerState IN (‘FL’, ‘TX’, ‘CA’, ‘HI’)
ORDER BY CustomerState, CustomerName;

• Note: The IN operator in this example allows you to


include rows whose CustomerState value is either FL, TX,
CA, or HI. It is more efficient than separate OR conditions.

Copyright © 2022, 2019, 2016 Pearson Education, Inc. All Rights Reserved
Categorizing Results Using GROUP BY
Clause
• For use with aggregate functions
– Scalar aggregate: single value returned from S QL query
with aggregate function
– Vector aggregate: multiple values returned from S QL
query with aggregate function (via GROUP BY)

SELECT CustomerState, COUNT (CustomerState)


FROM Customer_T
GROUP BY CustomerState

• You can use single-value fields with aggregate functions if they


are included in the GROUP BY clause

Copyright © 2022, 2019, 2016 Pearson Education, Inc. All Rights Reserved
Qualifying Results by Categories Using
the HAVING Clause
• For use with GROUP BY

SELECT CustomerState, COUNT (CustomerState)


FROM Customer_T
GROUP BY CustomerState
HAVING COUNT (CustomerState) > 1;

• Like a WHERE clause, but it operates on groups


(categories), not on individual rows. Here, only those
groups with total numbers greater than 1 will be included
in the final result.
Copyright © 2022, 2019, 2016 Pearson Education, Inc. All Rights Reserved
A Query With Both WHERE and HAVING
SELECT ProductFinish, AVG (ProductStandardPrice)
FROM Product_T
WHERE ProductFinish IN (‘Cherry’, ‘Natural Ash’, ‘Natural
Maple’, ‘White Ash’)
GROUP BY ProductFinish
HAVING AVG (ProductStandardPrice) < 750
ORDER BY ProductFinish;

Copyright © 2022, 2019, 2016 Pearson Education, Inc. All Rights Reserved
Figure 5-10 SQL Statement Processing
Order
SELECT [ALL/DISTINCT] column_list
FROM table list
[WHERE conditional expression]
[GROUP BY group_by_column_list]
[HAVING conditional expression]
[ORDER BY order_by_column_list]

(based on van der Lans, 2006, p. 100)

Copyright © 2022, 2019, 2016 Pearson Education, Inc. All Rights Reserved
Ana;isis Data Bisnis

Advanced SQL

Copyright © 2022, 2019, 2016 Pearson Education, Inc. All Rights Reserved
Processing Multiple Tables (1 of 2)
• Join
– A relational operation that causes two or more tables with
a common domain to be combined into a single table or
view
• Equi-join
– A join in which the joining condition is based on equality
between values in the common columns; common
columns appear redundantly in the result table
• Natural (inner) join
– An equi-join in which one of the duplicate columns is
eliminated in the result table

Copyright © 2022, 2019, 2016 Pearson Education, Inc. All Rights Reserved
Processing Multiple Tables (2 of 2)
• 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 join
– Includes all data from each table that was joined

Copyright © 2022, 2019, 2016 Pearson Education, Inc. All Rights Reserved
Figure 6-2 Visualization of Different Join Types,
With the Results Returned in the Shaded Area

Copyright © 2022, 2019, 2016 Pearson Education, Inc. All Rights Reserved
The Following Slides Create Tables for
This Enterprise Data Model
(from Chapter 1, Figure 1-3)

Copyright © 2022, 2019, 2016 Pearson Education, Inc. All Rights Reserved
Figure 6-1 Pine Valley Furniture Company Customer_T
and Order_T Tables, With Pointers From Customers to
Their Orders

With pointers from orders to the customers who placed


them

Copyright © 2022, 2019, 2016 Pearson Education, Inc. All Rights Reserved
Equi-Join Example

Result:
Customerid Customerid Customername Orderid
1 1 Contemporary Casuals 1001
8 8 California Classics 1002
15 15 Mountain Scenes 1003
5 5 Impressions 1004
3 3 Home Furnishings 1005
2 2 Value Furniture 1006
11 11 American Euro Lifestyles 1007
12 12 Battle Creek Furniture 1008
4 4 Eastern Furniture 1009
1 1 Contemporary Casuals 1010
10 rows selected. Blank Blank Blank

What are the customer I Ds and names of all customers, along with the order I Ds for
all the orders they have placed?
Copyright © 2022, 2019, 2016 Pearson Education, Inc. All Rights Reserved
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.
Copyright © 2022, 2019, 2016 Pearson Education, Inc. All Rights Reserved
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.

For the tables in figure 6.1, this will return 16 rows. That’s because there are 15
customers, and one of these customers has 2 orders.

Copyright © 2022, 2019, 2016 Pearson Education, Inc. All Rights Reserved
Result
Customerid Customername Orderid
Note two rows for 1 Contemporary Casuals 1001

customer #1 1 Contemporary Casuals 1010


2 Value Furniture 1006
Contemporary 3 Home Furnishings 1005

Casuals. 4 Eastern Furniture 1009


5 Impressions 1004
Blank

6 Furniture Gallery
Also note that 7 Period Furniture
Blank

several customers 8 California Classics 1002


Blank

9 M & H Casual Furniture


don’t have orders. 10 Seminole Interiors
Blank

11 American Euro Lifestyles 1007


This is because of 12 Battle Creek Furniture 1008

the left outer join.


Blank

13 Heritage Furnishings
Blank

14 Kaneohe Homes
15 Mountain Scenes 1003
Blank Blank

16 rows selected.

Copyright © 2022, 2019, 2016 Pearson Education, Inc. All Rights Reserved
Multiple Table Join Example
Assemble all information necessary to create an invoice for order
number 1006.
Each pair of tables requires an equality-check condition in the WHERE
clause, matching primary keys against foreign keys.

Copyright © 2022, 2019, 2016 Pearson Education, Inc. All Rights Reserved
Figure 6-4 Results From a Four-Table Join
(Edited for Readability)

All rows returned from this query will pertain to Order ID


1006.
Note that the full query results include columns from four
different tables.

Copyright © 2022, 2019, 2016 Pearson Education, Inc. All Rights Reserved
Self Join Example
What are the employee ID and name of each employee and the name
of his or her supervisor (label the supervisor’s name Manager)?

Result:

Employeeid Employeename Manager


123-44-347 Jim Jason Robert Lewis

The same table is used on both sides of the join; distinguished using
table aliases. See the next slide for details.

Copyright © 2022, 2019, 2016 Pearson Education, Inc. All Rights Reserved
Figure 6-5 Example of a Self-Join
Self join involve tables that implement 1-to-many unary
relationships.

Copyright © 2022, 2019, 2016 Pearson Education, Inc. All Rights Reserved
Subqueries
• Subquery – placing an inner query (SELECT statement)
inside an outer query
• Options:
– In a condition of the WHERE clause
– As a “table” of the FROM clause
– Returning a field for the SELECT clause
– Within the HAVING clause
• Subqueries can be:
– Noncorrelated – executed once for the entire outer query
– Correlated – executed once for each row returned by the
outer query
Copyright © 2022, 2019, 2016 Pearson Education, Inc. All Rights Reserved
Subquery Example
What are the name and address of the customer who
placed order number 1008?

Copyright © 2022, 2019, 2016 Pearson Education, Inc. All Rights Reserved
Alternative Approach, Using a Join
What are the name and address of the customer who
placed order number 1008?

Copyright © 2022, 2019, 2016 Pearson Education, Inc. All Rights Reserved
Figure 6-6 Graphical Depiction of Two Ways to
Answer a Query With Different Types of Joins (1 of 2)

a) Join query approach

Copyright © 2022, 2019, 2016 Pearson Education, Inc. All Rights Reserved
Figure 6-6 Graphical Depiction of Two Ways to
Answer a Query With Different Types of Joins (2 of 2)

b) Subquery approach

Copyright © 2022, 2019, 2016 Pearson Education, Inc. All Rights Reserved
Correlated v s Noncorrelated Subqueries
ersu

• Noncorrelated subqueries:
– Do not depend on data from the outer query
– Execute once for the entire outer query
• Correlated subqueries:
– Make use of data from the outer query
– Execute once for each row of the outer query
– Can use the EXISTS and ALL operators

Copyright © 2022, 2019, 2016 Pearson Education, Inc. All Rights Reserved
Example of a Correlated Subquery
List the details about the product with the highest standard price.

Result:

Productdescription Productfinish Productstandardprice

Dining Table Natural Ash 800

Copyright © 2022, 2019, 2016 Pearson Education, Inc. All Rights Reserved
Another Correlated Subquery
What are the order IDs for all orders that have included furniture
finished in natural ash?

A correlated subquery always refers to an attribute from a table


referenced in the outer query.

Copyright © 2022, 2019, 2016 Pearson Education, Inc. All Rights Reserved
Figure 6-8 Subquery Processing (1 of 2)

a) Processing a noncorrelated subquery

Copyright © 2022, 2019, 2016 Pearson Education, Inc. All Rights Reserved
Figure 6-8 Subquery Processing (2 of 2)

b) Processing a correlated subquery

Copyright © 2022, 2019, 2016 Pearson Education, Inc. All Rights Reserved
Derived Table (Subquery in the FROM
Clause of the Outer Query)
What are the order I Ds for all orders that have included furniture
finished in natural ash?

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.

Copyright © 2022, 2019, 2016 Pearson Education, Inc. All Rights Reserved
UNION — Combining Queries
Combine the output
(union of multiple
queries) together into a
single result table

With UNION queries,


the quantity and data
types of the attributes in
the SELECT clauses of
both queries must be
identical. Result:

CustomerID CustomerName OrderedQuantity Quantity


1 Contemporary Casuals 1 Smallest Quantity
2 Value Furniture 1 Smallest Quantity
1 Contemporary Casuals 10 Largest Quantity

Copyright © 2022, 2019, 2016 Pearson Education, Inc. All Rights Reserved
Conditional Expressions Using Case
Keyword

A CASE expression Result:


acts like an if-then Productdescription
statement. It allows you End Table

to choose what will ####


####
appear in a column of ####
the result set, Writers Desk
####
depending on a ####
condition. ####

Copyright © 2022, 2019, 2016 Pearson Education, Inc. All Rights Reserved
More Complicated SQL Queries
• Production databases contain hundreds or even
thousands of tables, and tables could include
hundreds of columns.
• So, sometimes query requirements can be very
complex.
• Sometimes it’s useful to combine queries, through the
use of Views.
• If you use a view (which is a query), you could have
another query that uses the view as if it were a table.

Copyright © 2022, 2019, 2016 Pearson Education, Inc. All Rights Reserved
Using a View in Your Query
For each
salesperson, list
his or her biggest-
selling product.
The view:

The query using


the view:

Copyright © 2022, 2019, 2016 Pearson Education, Inc. All Rights Reserved
Tips for Developing Queries
• Be familiar with the data model (entities and relationships)
• Understand the desired results
• Know the attributes desired in results
• Identify the entities that contain desired attributes
• Review ERD
• Construct a WHERE equality for each link
• Fine tune with GROUP BY and HAVING clauses if needed
• Consider the effect on unusual data

Copyright © 2022, 2019, 2016 Pearson Education, Inc. All Rights Reserved
Query Efficiency Considerations
• Instead of SELECT *, identify the specific attributes in
the SELECT clause; this helps reduce network traffic of
result set
• Limit the number of subqueries; try to make everything
done in a single query if possible
• If data is to be used many times, make a separate
query and store it as a view

Copyright © 2022, 2019, 2016 Pearson Education, Inc. All Rights Reserved
Guidelines for Better Query Design (1 of 2)
• Understand how indexes are used in query processing
• Keep optimizer statistics up to date
• Use compatible data types for fields and literals
• Write simple queries
• Break complex queries into multiple simple parts
• Don’t nest one query inside another query
• Don’t combine a query with itself (if possible avoid self-
joins)

Copyright © 2022, 2019, 2016 Pearson Education, Inc. All Rights Reserved
Guidelines for Better Query Design (2 of 2)
• Create temporary tables for groups of queries
• Combine update operations
• Retrieve only the data you need
• Don’t have the DBMS sort without an index
• Learn!
• Consider the total query processing time for ad hoc
queries

Copyright © 2022, 2019, 2016 Pearson Education, Inc. All Rights Reserved
Using and Defining Views
• Dynamic View
– A “virtual table” created dynamically upon request by
a user
– No data actually stored; instead data from base table
made available to user
– Based on SQL SELECT statement on base tables or
other views
• Materialized View
– Copy or replication of data, data actually stored
– Must be refreshed periodically to match
corresponding base tables
Copyright © 2022, 2019, 2016 Pearson Education, Inc. All Rights Reserved
A Sample Create View Command

• View has a name


• View is based on a SELECT statement
• CHECK_OPTION works only for updateable views and
prevents updates that would create rows not included in
the view

Copyright © 2022, 2019, 2016 Pearson Education, Inc. All Rights Reserved
Advantages of Dynamic Views (1 of 2)
• Simplify query commands
• Assist with data security
• Enhance programming productivity
• Contain most current base table data
• Use little storage space
• Provide customized view for user
• Establish physical data independence

Copyright © 2022, 2019, 2016 Pearson Education, Inc. All Rights Reserved
Advantages of Dynamic Views (2 of 2)
• Use processing time each time view is referenced
• May or may not be directly updateable
• As with all SQL constructs, you should use views with
discretion

Copyright © 2022, 2019, 2016 Pearson Education, Inc. All Rights Reserved
Routines and Triggers
• Routines
– Program modules that execute on demand
• Functions
– routines that return values and take input parameters
• Procedures
– 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)
Copyright © 2022, 2019, 2016 Pearson Education, Inc. All Rights Reserved
Figure 6-12 Triggers Contrasted With Stored
Procedures (Based on Mullins, 1995)

Procedures and functions are called explicitly. Triggers are


event-driven.

Copyright © 2022, 2019, 2016 Pearson Education, Inc. All Rights Reserved
Figure 6-13 Simplified Trigger Syntax in
SQL:2008

Example DML trigger

Example DDL trigger

Copyright © 2022, 2019, 2016 Pearson Education, Inc. All Rights Reserved
Figure 6-14 Syntax for Creating a
Routine in SQL:2011

Example DDL trigger

Calling the procedure

Copyright © 2022, 2019, 2016 Pearson Education, Inc. All Rights Reserved
Data Dictionary Facilities
• System tables that store metadata
• Users usually can view some of these tables
• Users are restricted from updating them
• Examples in Oracle 12c
– DBA_TABLES – descriptions of tables
– DBA_USERS – information about the users of the system
• Examples in Microsoft SQL Server 2016
– sys.columns – table and column definitions
– sys.indexes – table index information

Copyright © 2022, 2019, 2016 Pearson Education, Inc. All Rights Reserved
SQL Enhancements/Extensions (1 of 2)
• User-defined data types (U DT)
– Subclasses of standard types or an object type
• Analytical functions (for OLAP)
– CEILING, FLOOR, SQRT, RANK, DENSE_RANK, ROLLUP,
CUBE, SAMPLE,
– WINDOW – improved numerical analysis capabilities
• New Data Types
– BIGINT, MULTISET (collection), XML
• CREATE TABLE LIKE
– create a new table similar to an existing one
• MERGE

Copyright © 2022, 2019, 2016 Pearson Education, Inc. All Rights Reserved
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

Copyright © 2022, 2019, 2016 Pearson Education, Inc. All Rights Reserved

You might also like