Introduction to SQL
Structured Query
Language
Beginners to Advance
[Link]
2
▪ Explore basic commands and functions
of SQL
▪ How to use SQL for data administration
(to create tables, indexes, and views)
Objectives ▪ How to use SQL for data manipulation
(to add, modify, delete, and retrieve
data)
▪ How to use SQL to query a database to
extract useful information
3
▪ SQL functions fit into two broad
categories:
▪ Data definition language
▪ SQL includes commands to:
Introduction
▪ Create database objects, such as
tables, indexes, and views
to SQL ▪ Define access rights to those database
objects
▪ Data manipulation language
▪ Includes commands to insert, update,
delete, and retrieve data within database
tables
4
▪ SQL is relatively easy to learn
▪ Basic command set has vocabulary of
Introduction to less than 100 words
SQL ▪ Nonprocedural language
▪ American National Standards Institute
(continued) (ANSI) prescribes a standard SQL
▪ Several SQL dialects exist
Introduction to SQL (continued)
5
Introduction to SQL (continued)
6
Introduction to SQL (continued)
7
8
▪ Examine simple database model and
database tables that will form basis for
Data Definition many SQL examples
Commands ▪ Understand data environment
The Database Model
9
10
▪ Following two tasks must be completed:
▪ Create database structure
▪ Create tables that will hold end-user data
Creating the ▪ First task:
▪ RDBMS creates physical files that will
Database hold database
▪ Tends to differ substantially from one
RDBMS to another
11
▪ Authentication
▪ Process through which DBMS verifies that
only registered users are able to access
The Database database
▪ Log on to RDBMS using user ID and
Schema password created by database administrator
▪ Schema
▪ Group of database objects—such as tables
and indexes—that are related to each other
12
▪ Data type selection is usually dictated
by nature of data and by intended use
Data Types ▪ Pay close attention to expected use of
attributes for sorting and data retrieval
purposes
Data Types (continued)
13
14
▪ Use one line per column (attribute)
definition
▪ Use spaces to line up attribute
characteristics and constraints
Creating Table ▪ Table and attribute names are
Structures capitalized
▪ NOT NULL specification
▪ UNIQUE specification
15
▪ Primary key attributes contain both a
NOT NULL and a UNIQUE specification
Creating Table ▪ RDBMS will automatically enforce
Structures referential integrity for foreign keys
(continued) ▪ Command sequence ends with
semicolon
16
▪ NOT NULL constraint
▪ Ensures that column does not accept
nulls
▪ UNIQUE constraint
▪ Ensures that all values in column are
SQL unique
▪ DEFAULT constraint
Constraints ▪ Assigns value to attribute when a new
row is added to table
▪ CHECK constraint
▪ Validates data when attribute value is
entered
17
▪ When primary key is declared, DBMS
automatically creates unique index
▪ Often need additional indexes
▪ Using CREATE INDEX command, SQL indexes
can be created on basis of any selected
attribute
SQL Indexes ▪ Composite index
▪ Index based on two or more attributes
▪ Often used to prevent data duplication
18
▪ Adding table rows
▪ Saving table changes
▪ Listing table rows
Data ▪ Updating table rows
Manipulation ▪ Restoring table contents
Commands ▪ Deleting table rows
▪ Inserting table rows with a select
subquery
19
▪ INSERT
▪ Used to enter data into table
Adding Table ▪ Syntax:
Rows ▪ INSERT INTO columnname
VALUES (value1, value2, … , valuen);
20
▪ When entering values, notice that:
▪ Row contents are entered between
parentheses
▪ Character and date values are entered
Adding Table between apostrophes
▪ Numerical entries are not enclosed in
Rows apostrophes
(continued) ▪ Attribute entries are separated by
commas
▪ A value is required for each column
▪ Use NULL for unknown values
21
▪ Changes made to table contents are not
physically saved on disk until, one of the
following occurs:
▪ Database is closed
Saving Table ▪ Program is closed
Changes ▪ COMMIT command is used
▪ Syntax:
▪ COMMIT [WORK];
▪ Will permanently save any changes made
to any table in the database
22
▪ SELECT
▪ Used to list contents of table
▪ Syntax:
▪ SELECT columnlist
FROM tablename;
Listing Table ▪ Columnlist represents one or more
Rows attributes, separated by commas
▪ Asterisk can be used as wildcard character
to list all attributes
23
▪ UPDATE
▪ Modify data in a table
▪ Syntax:
▪ UPDATE tablename
Updating SET columnname = expression [,
columname = expression]
Table Rows [WHERE conditionlist];
▪ If more than one attribute is to be
updated in row, separate corrections
with commas
24
▪ ROLLBACK
▪ Used to restore database to its previous
condition
▪ Only applicable if COMMIT command has
not been used to permanently store changes
Restoring in database
Table Contents ▪ Syntax:
▪ ROLLBACK;
▪ COMMIT and ROLLBACK only work with data
manipulation commands that are used to add,
modify, or delete table rows
25
▪ DELETE
▪ Deletes a table row
▪ Syntax:
▪ DELETE FROM tablename
Deleting Table [WHERE conditionlist ];
Rows ▪ WHERE condition is optional
▪ If WHERE condition is not specified, all
rows from specified table will be
deleted
26
▪ INSERT
▪ Inserts multiple rows from another table
(source)
Inserting Table ▪ Uses SELECT subquery
Rows with a
▪ Query that is embedded (or nested) inside
another query
Select ▪ Executed first
▪ Syntax:
Subquery ▪ INSERT INTO tablename SELECT columnlist
FROM tablename;
27
▪ Select partial table contents by placing
restrictions on rows to be included in
Selecting Rows output
▪ Add conditional restrictions to SELECT
with statement, using WHERE clause
Conditional ▪ Syntax:
Restrictions ▪ SELECT columnlist
FROM tablelist
[ WHERE conditionlist ] ;
Selecting Rows with
Conditional Restrictions (continued)
28
Selecting Rows with
Conditional Restrictions (continued)
29
30
Arithmetic ▪ Perform operations within parentheses
Operators: ▪ Perform power operations
▪ Perform multiplications and divisions
The Rule of ▪ Perform additions and subtractions
Precedence
Arithmetic Operators:
The Rule of Precedence (continued)
31
32
▪ BETWEEN
▪ Used to check whether attribute value is
within a range
▪ IS NULL
Special ▪ Used to check whether attribute value is
Operators null
▪ LIKE
▪ Used to check whether attribute value
matches given string pattern
33
▪ IN
▪ Used to check whether attribute value
Special matches any value within a value list
Operators ▪ EXISTS
(continued) ▪ Used to check if subquery returns any
rows
34
▪ All changes in table structure are made
by using ALTER command
Advanced ▪ Followed by keyword that produces
specific change
Data Definition ▪ Following three options are available:
Commands ▪ ADD
▪ MODIFY
▪ DROP
35
▪ ALTER can be used to change data type
Changing a ▪ Some RDBMSs (such as Oracle) do not
Column’s Data permit changes to data types unless
Type column to be changed is empty
36
▪ Use ALTER to change data
characteristics
Changing a ▪ If column to be changed already
Column’s Data contains data, changes in column’s
Characteristics characteristics are permitted if those
changes do not alter the data type
37
▪ Use ALTER to add column
Adding a ▪ Do not include the NOT NULL clause for
Column new column
38
▪ Use ALTER to drop column
Dropping a ▪ Some RDBMSs impose restrictions on the
Column deletion of an attribute
Advanced Data Updates
39
40
▪ SQL permits copying contents of
selected table columns so that the data
need not be reentered manually into
Copying Parts newly created table(s)
of Tables ▪ First create the PART table structure
▪ Next add rows to new PART table using
PRODUCT table rows
41
▪ When table is copied, integrity rules do
not copy, so primary and foreign keys
need to be manually defined on new
Adding table
Primary and ▪ User ALTER TABLE command
Foreign Key ▪ Syntax:
Designations
▪ ALTER TABLE tablename ADD
PRIMARY KEY(fieldname);
▪ For foreign key, use FOREIGN KEY in place
of PRIMARY KEY
42
▪ DROP
Deleting a ▪ Deletes table from database
Table from the ▪ Syntax:
Database ▪ DROP TABLE tablename;
43
▪ SQL provides useful functions that can:
▪ Count
▪ Find minimum and maximum values
Advanced ▪ Calculate averages
Select Queries ▪ SQL allows user to limit queries to only
those entries having no duplicates or
entries whose duplicates may be
grouped
Aggregate Functions
44
Aggregate Functions (continued)
45
Aggregate Functions (continued)
46
Aggregate Functions (continued)
47
Aggregate Functions (continued)
48
Grouping Data
49
Grouping Data (continued)
50
Grouping Data (continued)
51
52
▪ View is virtual table based on SELECT
query
▪ Can contain columns, computed columns,
Virtual Tables: aliases, and aggregate functions from one
or more tables
Creating a ▪ Base tables are tables on which view is
based
View ▪ Create view by using CREATE VIEW
command
Virtual Tables: Creating a View (continued)
53
54
▪ Ability to combine (join) tables on
common attributes is most important
distinction between relational database
and other databases
Joining ▪ Join is performed when data are
Database retrieved from more than one table at a
time
Tables ▪ Join is generally composed of an
equality comparison between foreign
key and primary key of related tables
55
▪ Alias can be used to identify source
table
▪ Any legal table name can be used as
Joining Tables alias
▪ Add alias after table name in FROM
with an Alias clause
▪ FROM tablename alias
56
▪ SQL commands can be divided into two
overall categories:
▪ Data definition language commands
▪ Data manipulation language commands
Summary ▪ The ANSI standard data types are
supported by all RDBMS vendors in
different ways
▪ Basic data definition commands allow
you to create tables, indexes, and views
57
▪ DML commands allow you to add, modify, and
delete rows from tables
▪ The basic DML commands are SELECT,
INSERT, UPDATE, DELETE, COMMIT, and
Summary ROLLBACK
(continued) ▪ INSERT command is used to add new rows to
tables
▪ SELECT statement is main data retrieval
command in SQL
58
▪ Many SQL constraints can be used with
columns
▪ The column list represents one or more
Summary column names separated by commas
(continued) ▪ WHERE clause can be used with
SELECT, UPDATE, and DELETE
statements to restrict rows affected by
the DDL command
59
▪ Aggregate functions
▪ Special functions that perform arithmetic
computations over a set of rows
▪ ORDER BY clause
Summary ▪ Used to sort output of SELECT statement
(continued) ▪ Can sort by one or more columns and use
either an ascending or descending order
▪ Join output of multiple tables with
SELECT statement
60
▪ Natural join uses join condition to match
only rows with equal values in specified
columns
Summary
▪ Right outer join and left outer join used
(continued) to select rows that have no matching
values in other related table