0% found this document useful (0 votes)
3 views21 pages

Week 11 - Introduction to SQL

This document provides an introduction to Structured Query Language (SQL), covering its basic commands for data definition and manipulation, as well as querying databases. It includes detailed tables of SQL commands, data types, and constraints, along with explanations of how to create and manage database structures. The document also outlines the use of logical and special operators in SQL for effective data handling.

Uploaded by

teresakcuttie
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)
3 views21 pages

Week 11 - Introduction to SQL

This document provides an introduction to Structured Query Language (SQL), covering its basic commands for data definition and manipulation, as well as querying databases. It includes detailed tables of SQL commands, data types, and constraints, along with explanations of how to create and manage database structures. The document also outlines the use of logical and special operators in SQL for effective data handling.

Uploaded by

teresakcuttie
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/ 21

Week 11:

Introduction to Structured Query


Language (SQL)
RECAP

Learning Objectives
• In this chapter, you will learn:
o The basic commands and functions of SQL
o How to use SQL for data administration (to create tables and
indexes)
o How to use SQL for data manipulation (to add, modify, delete, and
retrieve data)
o How to use SQL to query a database for useful information

Coronel/Morris, Database Systems: Design, Implementation, & Management, 12th Edition. © 2017 Cengage. All Rights Reserved.
May not be scanned, copied or duplicated, or posted to a publicly accessible website, in whole or in part.
Introduction to SQL
• Categories of SQL functions:
o Data definition language (DDL)
o Data manipulation language (DML)
• Nonprocedural language with basic command vocabulary set of
less than 100 words
• Differences in SQL dialects are minor

Coronel/Morris, Database Systems: Design, Implementation, & Management, 12th Edition. © 2017 Cengage. All Rights Reserved.
May not be scanned, copied or duplicated, or posted to a publicly accessible website, in whole or in part.

Table 7.1 – SQL Data Definition Commands (1 of 2)


COMMAND OR OPTION DESCRIPTION
CREATE SCHEMA Creates a database schema
AUTHORIZATION
CREATE TABLE Creates a new table in the user’s database schema
NOT NULL Ensures that a column will not have null values
UNIQUE Ensures that a column will not have duplicate values
PRIMARY KEY Defines a primary key for a table
FOREIGN KEY Defines a foreign key for a table
DEFAULT Defines a default value for a column (when no value is given)
CHECK Validates data in an attribute
CREATE INDEX Creates an index for a table
CREATE VIEW Creates a dynamic subset of rows and columns from one or
more tables (see Chapter 8, Advanced SQL)
Coronel/Morris, Database Systems: Design, Implementation, & Management, 12th Edition. © 2017 Cengage. All Rights Reserved.
May not be scanned, copied or duplicated, or posted to a publicly accessible website, in whole or in part.
Table 7.1 – SQL Data Definition Commands (2 of 2)
COMMAND OR OPTION DESCRIPTION
ALTER TABLE Modifies a table’s definition (adds, modifies, or deletes
attributes or constraints)
CREATE TABLE AS Creates a new table based on a query in the user’s database
schema
DROP TABLE Permanently deletes a table (and its data)
DROP INDEX Permanently deletes an index
DROP VIEW Permanently deletes a view

Coronel/Morris, Database Systems: Design, Implementation, & Management, 12th Edition. © 2017 Cengage. All Rights Reserved.
May not be scanned, copied or duplicated, or posted to a publicly accessible website, in whole or in part.

Table 7.2 – SQL Data Manipulation Commands (1 of 2)


COMMAND OR OPTION DESCRIPTION
INSERT Inserts row(s) into a table
SELECT Selects attributes from rows in one or more tables or views
WHERE Restricts the selection of rows based on a conditional expression
GROUP BY Groups the selected rows based on one or more attributes
HAVING Restricts the selection of grouped rows based on a condition
ORDER BY Orders the selected rows based on one or more attributes
UPDATE Modifies an attribute’s values in one or more table’s rows
DELETE Deletes one or more rows from a table
COMMIT Permanently saves data changes
ROLLBACK Restores data to its original values
Comparison operators
=, <, >, <=, >=, <>, != Used in conditional expressions

Coronel/Morris, Database Systems: Design, Implementation, & Management, 12th Edition. © 2017 Cengage. All Rights Reserved.
May not be scanned, copied or duplicated, or posted to a publicly accessible website, in whole or in part.
Table 7.2 – SQL Data Manipulation Commands (2 of 2)
Logical operators
AND/OR/NOT Used in conditional expressions
Special operators Used in conditional expressions
BETWEEN Checks whether an attribute value is within a range
IS NULL Checks whether an attribute value is null
LIKE Checks whether an attribute value matches a given string pattern
IN Checks whether an attribute value matches any value within a value list
EXISTS Checks whether a subquery returns any rows
DISTINCT Limits values to unique values
Aggregate functions Used with SELECT to return mathematical summaries on columns
COUNT Returns the number of rows with non-null values for a given column
MIN Returns the minimum attribute value found in a given column
MAX Returns the maximum attribute value found in a given column
SUM Returns the sum of all values for a given column
AVG Returns the average of all values for a given column
Coronel/Morris, Database Systems: Design, Implementation, & Management, 12th Edition. © 2017 Cengage. All Rights Reserved.
May not be scanned, copied or duplicated, or posted to a publicly accessible website, in whole or in part.

Figure 7.1 - The Database Model

Coronel/Morris, Database Systems: Design, Implementation, & Management, 12th Edition. © 2017 Cengage. All Rights Reserved.
May not be scanned, copied or duplicated, or posted to a publicly accessible website, in whole or in part.
Creating the Database
• Create database structure
o RDBMS creates physical files that will hold database
o Differs from one RDBMS to another
• Authentication is the process DBMS uses to verify that only
registered users access the database
o Required for the creation tables
o User should log on to RDBMS using user ID and password created
by database administrator

Coronel/Morris, Database Systems: Design, Implementation, & Management, 12th Edition. © 2017 Cengage. All Rights Reserved.
May not be scanned, copied or duplicated, or posted to a publicly accessible website, in whole or in part.

The Database Schema


• Logical group of database objects – such as tables and indexes -
related to each other
• Command:
o CREATE SCHEMA AUTHORIZATION {creator};
o Seldom used directly as command is usually optional

Coronel/Morris, Database Systems: Design, Implementation, & Management, 12th Edition. © 2017 Cengage. All Rights Reserved.
May not be scanned, copied or duplicated, or posted to a publicly accessible website, in whole or in part.
Table 7.4 - Common SQL Data Types (1 of 2)
TABLE 7.4 SOME COMMON SQL DATA TYPES
DATA TYPE FORMAT COMMENTS
Numeric NUMBER(L,D) The declaration NUMBER(7,2) or NUMERIC(7,2) indicates that
or numbers will be stored with two decimal places and may be up to
NUMERIC(L,D) seven digits long, including the sign and the decimal place (for
example, 12.32 or −134.99).
INTEGER May be abbreviated as INT. Integers are (whole) counting numbers,
so they cannot be used if you want to store numbers that require
decimal places.
SMALLINT Like INTEGER but limited to integer values up to six digits. If your
integer values are relatively small, use SMALLINT instead of INT.

DECIMAL(L,D) Like the NUMBER specification, but the storage length is a


minimum specification. That is, greater lengths are acceptable, but
smaller ones are not. DECIMAL(9,2), DECIMAL(9), and DECIMAL
are all acceptable.
Coronel/Morris, Database Systems: Design, Implementation, & Management, 12th Edition. © 2017 Cengage. All Rights Reserved.
May not be scanned, copied or duplicated, or posted to a publicly accessible website, in whole or in part.

Table 7.4 - Common SQL Data Types (2 of 2)


DATA TYPE FORMAT COMMENTS
Character CHAR(L) Fixed-length character data for up to 255 characters. If you
store strings that are not as long as the CHAR parameter
value, the remaining spaces are left unused. Therefore, if you
specify CHAR(25), strings such as Smith and Katzenjammer
are each stored as 25 characters. However, a U.S. area code
is always three digits long, so CHAR(3) would be appropriate
if you wanted to store such codes.
VARCHAR(L) or Variable-length character data. The designation
VARCHAR2(L) VARCHAR2(25) or VARCHAR(25) will let you store characters
up to 25 characters long. However, unlike CHAR, VARCHAR
will not leave unused spaces. Oracle automatically converts
VARCHAR to VARCHAR2.
Date DATE Stores dates in the Julian date format.

Coronel/Morris, Database Systems: Design, Implementation, & Management, 12th Edition. © 2017 Cengage. All Rights Reserved.
May not be scanned, copied or duplicated, or posted to a publicly accessible website, in whole or in part.
Creating Table Structures
• Use one line per column (attribute) definition
• Use spaces to line up attribute characteristics and constraints
• Table and attribute names are fully capitalized
• Features of table creating command sequence:
o NOT NULL specification ensures data entry
o UNIQUE specification avoids duplicated values
• Table definition enclosed in parentheses
• RDBMS automatically enforces referential integrity for foreign
keys.

Coronel/Morris, Database Systems: Design, Implementation, & Management, 12th Edition. © 2017 Cengage. All Rights Reserved.
May not be scanned, copied or duplicated, or posted to a publicly accessible website, in whole or in part.

SQL Constraints
• NOT NULL
o Ensures that column does not accept nulls
• UNIQUE
o Ensures that all values in column are unique
• DEFAULT
o Assigns value to attribute when a new row is added to table
• CHECK
o Validates data when attribute value is entered

Coronel/Morris, Database Systems: Design, Implementation, & Management, 12th Edition. © 2017 Cengage. All Rights Reserved.
May not be scanned, copied or duplicated, or posted to a publicly accessible website, in whole or in part.
SQL Indexes
• When primary key is declared, DBMS automatically creates
unique index
• The CREATE INDEX command can be used to create indexes on
the basis of any selected attribute
• UNIQUE qualifier prevents a value that has been used before
• Composite indexes prevent data duplication
• To delete an index use the DROP INDEX command

Coronel/Morris, Database Systems: Design, Implementation, & Management, 12th Edition. © 2017 Cengage. All Rights Reserved.
May not be scanned, copied or duplicated, or posted to a publicly accessible website, in whole or in part.

Data Manipulation Commands (1 of 3)


• INSERT: Command to insert data into table
o Syntax - INSERT INTO tablename VALUES();
o Used to add table rows with NULL and NOT NULL attributes
• COMMIT: Command to save changes
o Syntax - COMMIT [WORK];
o Ensures database update integrity

Coronel/Morris, Database Systems: Design, Implementation, & Management, 12th Edition. © 2017 Cengage. All Rights Reserved.
May not be scanned, copied or duplicated, or posted to a publicly accessible website, in whole or in part.
Data Manipulation Commands (2 of 3)
• SELECT: Command to list the contents
o Syntax - SELECT columnlist FROM tablename;
o Wildcard character(*): Substitute for other characters/command
• UPDATE: Command to modify data
o Syntax - UPDATE tablename SET columnname = expression [,
columnname = expression] [WHERE conditionlist];

Coronel/Morris, Database Systems: Design, Implementation, & Management, 12th Edition. © 2017 Cengage. All Rights Reserved.
May not be scanned, copied or duplicated, or posted to a publicly accessible website, in whole or in part.

Data Manipulation Commands (3 of 3)


• WHERE condition
o Specifies the rows to be selected
• ROLLBACK: Command to restore the database
o Syntax - ROLLBACK;
o Undoes the changes since last COMMIT command
• DELETE: Command to delete
o Syntax - DELETE FROM tablename
o [WHERE conditionlist];

Coronel/Morris, Database Systems: Design, Implementation, & Management, 12th Edition. © 2017 Cengage. All Rights Reserved.
May not be scanned, copied or duplicated, or posted to a publicly accessible website, in whole or in part.
Inserting Table Rows with a SELECT Subquery
• Syntax
o INSERT INTO tablename SELECT columnlist FROM tablename
• Used to add multiple rows using another table as source
• SELECT command - Acts as a subquery and is executed first
o Subquery: Query embedded/nested inside another query

Coronel/Morris, Database Systems: Design, Implementation, & Management, 12th Edition. © 2017 Cengage. All Rights Reserved.
May not be scanned, copied or duplicated, or posted to a publicly accessible website, in whole or in part.

Selecting Rows Using Conditional Restrictions


• Can select partial table contents by placing restrictions on rows to
be included
• Syntax enables to specify which rows to select:
o SELECT columnlist
o FROM tablelist
o [WHERE conditionlist];
• WHERE clause adds conditional restrictions to the SELECT
statement

Coronel/Morris, Database Systems: Design, Implementation, & Management, 12th Edition. © 2017 Cengage. All Rights Reserved.
May not be scanned, copied or duplicated, or posted to a publicly accessible website, in whole or in part.
Table 7.6 - Comparison Operators
• Adds conditional restrictions on selected character attributes and
dates

SYMBOL MEANING
= Equal to
< Less Than
<= Less than or equal to
> Greater than
>= Greater than or equal to
<> Or != Not equal to

Coronel/Morris, Database Systems: Design, Implementation, & Management, 12th Edition. © 2017 Cengage. All Rights Reserved.
May not be scanned, copied or duplicated, or posted to a publicly accessible website, in whole or in part.

Comparison Operators: Computed Columns


and Column Aliases
• SQL accepts any valid expressions/formulas in the computed
columns
• Alias: Alternate name given to a column or table in any SQL
statement to improve the readability
• Computed column, an alias, and date arithmetic can be used in a
single query

Coronel/Morris, Database Systems: Design, Implementation, & Management, 12th Edition. © 2017 Cengage. All Rights Reserved.
May not be scanned, copied or duplicated, or posted to a publicly accessible website, in whole or in part.
Arithmetic Operators
• The Rule of Precedence: Establish the order in which
computations are completed
• Performed in this order:
o Operations within parentheses
o Power operations
o Multiplications and divisions
o Additions and subtractions

Coronel/Morris, Database Systems: Design, Implementation, & Management, 12th Edition. © 2017 Cengage. All Rights Reserved.
May not be scanned, copied or duplicated, or posted to a publicly accessible website, in whole or in part.

Table 7.7 - The Arithmetic Operators

OPERATOR DESCRIPTION
+ Add
− Subtract
* Multiply
/ Divide
^ Raise to the power of (some application use ** instead of ^)

Coronel/Morris, Database Systems: Design, Implementation, & Management, 12th Edition. © 2017 Cengage. All Rights Reserved.
May not be scanned, copied or duplicated, or posted to a publicly accessible website, in whole or in part.
Logical Operators: AND, OR and NOT
• OR and AND: Used to link multiple conditional expressions in a
WHERE or HAVING clause
o OR requires only one of the conditional expressions to be true
o AND requires all of the conditional expressions to be true
• NOT is used to negate the result of a conditional expression
• Boolean algebra is dedicated to the use to logical operations

Coronel/Morris, Database Systems: Design, Implementation, & Management, 12th Edition. © 2017 Cengage. All Rights Reserved.
May not be scanned, copied or duplicated, or posted to a publicly accessible website, in whole or in part.

Special Operators
• BETWEEN
o Checks whether attribute value is within a range
• IS NULL
o Checks whether attribute value is null
• LIKE
o Checks whether attribute value matches given string pattern
• IN
o Checks whether attribute value matches any value within a value list
• EXISTS
o Checks if subquery returns any rows
Coronel/Morris, Database Systems: Design, Implementation, & Management, 12th Edition. © 2017 Cengage. All Rights Reserved.
May not be scanned, copied or duplicated, or posted to a publicly accessible website, in whole or in part.
Additional Data Definition Commands
• ALTER TABLE command: To make changes in the table structure
• Keywords use with the command
o ADD - Adds a column
o MODIFY - Changes column characteristics
o DROP - Deletes a column
• Used to:
o Add table constraints
o Remove table constraints

Coronel/Morris, Database Systems: Design, Implementation, & Management, 12th Edition. © 2017 Cengage. All Rights Reserved.
May not be scanned, copied or duplicated, or posted to a publicly accessible website, in whole or in part.

Changing a Column’s Data Type and Data


Characteristics
• ALTER used to change data type and characteristics
o Some RDBMSs do not permit changes to data types unless column
is empty
o Changes in characteristics are permitted if they do not alter the
existing data type
• Syntax:
o Data Type: ALTER TABLE tablename MODIFY
(columnname(datatype));
o Data Characteristic: ALTER TABLE tablename MODIFY
(columnname(characteristic));

Coronel/Morris, Database Systems: Design, Implementation, & Management, 12th Edition. © 2017 Cengage. All Rights Reserved.
May not be scanned, copied or duplicated, or posted to a publicly accessible website, in whole or in part.
Adding and Dropping Columns
• Adding a column
o Use ALTER and ADD
o Do not include the NOT NULL clause for new column
• Dropping a column
o Use ALTER and DROP
o Some RDBMSs impose restrictions on the deletion of an attribute

Coronel/Morris, Database Systems: Design, Implementation, & Management, 12th Edition. © 2017 Cengage. All Rights Reserved.
May not be scanned, copied or duplicated, or posted to a publicly accessible website, in whole or in part.

Advanced Data Updates


• UPDATE command updates only data in existing rows
• If a relationship is established between entries and existing
columns, the relationship can assign values to appropriate slots
• Arithmetic operators are useful in data updates
• In Oracle, ROLLBACK command undoes changes made by last
two UPDATE statements

Coronel/Morris, Database Systems: Design, Implementation, & Management, 12th Edition. © 2017 Cengage. All Rights Reserved.
May not be scanned, copied or duplicated, or posted to a publicly accessible website, in whole or in part.
Copying Parts of Tables
• SQL permits copying contents of selected table columns
o Data need not be reentered manually into newly created table(s)
• Table structure is created
• Rows are added to new table using rows from another table

Coronel/Morris, Database Systems: Design, Implementation, & Management, 12th Edition. © 2017 Cengage. All Rights Reserved.
May not be scanned, copied or duplicated, or posted to a publicly accessible website, in whole or in part.

Adding Primary and Foreign Key Designations


• A created new table based on another table does not include old
table’s integrity rule (no primary key)
• Can re-establish integrity rules using ALTER command
• Use ALTER TABLE command to ADD primary and foreign keys
o Composite primary keys and multiple foreign keys can be
designated in a single SQL command

Coronel/Morris, Database Systems: Design, Implementation, & Management, 12th Edition. © 2017 Cengage. All Rights Reserved.
May not be scanned, copied or duplicated, or posted to a publicly accessible website, in whole or in part.
Deleting a Table from the Database
• DROP TABLE: Deletes table from database
o Syntax - DROP TABLE tablename;
• Can drop a table only if it is not the one side of any relationship
o RDBMS generates a foreign key integrity violation error message if
the table is dropped

Coronel/Morris, Database Systems: Design, Implementation, & Management, 12th Edition. © 2017 Cengage. All Rights Reserved.
May not be scanned, copied or duplicated, or posted to a publicly accessible website, in whole or in part.

Additional SELECT Query Keywords


• Logical operators work well in the query environment
• SQL provides useful functions that:
o Count
o Find minimum and maximum values
o Calculate averages
• SQL allows user to limit queries to entries:
o Having no duplicates
o Whose duplicates can be grouped

Coronel/Morris, Database Systems: Design, Implementation, & Management, 12th Edition. © 2017 Cengage. All Rights Reserved.
May not be scanned, copied or duplicated, or posted to a publicly accessible website, in whole or in part.
Ordering a Listing
• ORDER BY clause is useful when listing order is important
• Syntax - SELECT columnlist
FROM tablelist
[WHERE conditionlist]
[ORDER BY columnlist [ASC | DESC]];
• Cascading order sequence: Multilevel ordered sequence
o Created by listing several attributes after the ORDER BY clause

Coronel/Morris, Database Systems: Design, Implementation, & Management, 12th Edition. © 2017 Cengage. All Rights Reserved.
May not be scanned, copied or duplicated, or posted to a publicly accessible website, in whole or in part.

Listing Unique Values


• DISTINCT clause: Produces list of values that are unique
• Syntax - SELECT DISTINCT columnlist
FROM tablelist;
• Placement of nulls does not affect list contents

Coronel/Morris, Database Systems: Design, Implementation, & Management, 12th Edition. © 2017 Cengage. All Rights Reserved.
May not be scanned, copied or duplicated, or posted to a publicly accessible website, in whole or in part.
Table 7.8 - Some Basic SQL Aggregate
Functions

FUNCTION OUTPUT
COUNT The number of rows containing non-null values
MIN The minimum attribute value encountered in a given column
MAX The maximum attribute value encountered in a given column
SUM The sum of all values for a given column
AVG The arithmetic mean (average) for a specified column

Coronel/Morris, Database Systems: Design, Implementation, & Management, 12th Edition. © 2017 Cengage. All Rights Reserved.
May not be scanned, copied or duplicated, or posted to a publicly accessible website, in whole or in part.

Grouping Data
• Frequency distributions created by GROUP BY clause within
SELECT statement
• Syntax - SELECT columnlist
FROM tablelist
[WHERE conditionlist]
[GROUP BY columnlist]
[HAVING conditionlist]
[ORDER BY columnlist [ASC | DESC]];

Coronel/Morris, Database Systems: Design, Implementation, & Management, 12th Edition. © 2017 Cengage. All Rights Reserved.
May not be scanned, copied or duplicated, or posted to a publicly accessible website, in whole or in part.
HAVING Clause
• Extension of GROUP BY feature
• Applied to output of GROUP BY operation
• Used in conjunction with GROUP BY clause
• Similar to WHERE clause in SELECT statement

Coronel/Morris, Database Systems: Design, Implementation, & Management, 12th Edition. © 2017 Cengage. All Rights Reserved.
May not be scanned, copied or duplicated, or posted to a publicly accessible website, in whole or in part.

Joining Database Tables


• Performed when data are retrieved from more than one table at a
time
o Equality comparison between foreign key and primary key of related
tables
• Tables are joined by listing tables in FROM clause of SELECT
statement
o DBMS creates Cartesian product of every table in the FROM clause

Coronel/Morris, Database Systems: Design, Implementation, & Management, 12th Edition. © 2017 Cengage. All Rights Reserved.
May not be scanned, copied or duplicated, or posted to a publicly accessible website, in whole or in part.
Joining Tables With an Alias and Recursive Joins
• Alias identifies source table from which data are taken
o Any legal table name can be used as alias
o Add alias after table name in FROM clause
• Recursive query: Table is joined to itself using alias
o Use aliases to differentiate the table from itself

Coronel/Morris, Database Systems: Design, Implementation, & Management, 12th Edition. © 2017 Cengage. All Rights Reserved.
May not be scanned, copied or duplicated, or posted to a publicly accessible website, in whole or in part.

You might also like