Chapter 5 Intro To SQL Fall22
Chapter 5 Intro To SQL Fall22
2
WHY SQL?
SQL is widely popular because it offers the following advantages:
1. Allows users to access data in the relational database management
systems.
2. Allows users to describe the data.
3. Allows users to define the data in a database and manipulate that
data.
4. Allows to embed within other languages using SQL modules, libraries
&
5. pre-compilers.
6. Allows users to create and drop databases and tables.
7. Allows users to create view, stored procedure, functions in a
database.
8. Allows users to set permissions on tables, procedures and views.
3
4
SQL – CREATE DATABASE
5
SQL ─ DROP OR DELETE DATABASE
6
SQL ─ SELECT DATABASE, USE STATEMENT
7
SQL ─ CREATE TABLE
8
SQL ─ CREATE TABLE
Example
9
SQL ─ CREATE TABLE
10
SQL - CREATING A TABLE FROM AN EXISTING
TABLE
A copy of an existing table can be created using a combination of
the CREATE TABLE statement and the SELECT statement.
11
SQL - CREATING A TABLE FROM AN EXISTING
TABLE
12
SQL ─ DROP OR DELETE TABLE
Example
13
SQL ─ CREATE TABLE
FULL EXAMPLE THE COMPANY DATABASE
• Figure shows the COMPANY database schema diagram introduced in
previous chapter
14
One possible database state for the COMPANY
relational database schema
CREATE TABLE
The simplest form:
TYPE
User Defined Types (UDTs) are supported for object-oriented
applications. Uses the command: CREATE TYPE
SPECIFYING FOREIGN KEY OPTIONS AND NAMING
OF CONSTRAINTS
• We can specify RESTRICT (the default), CASCADE, SET NULL or SET
DEFAULT on referential integrity constraints (foreign keys)
• Separate options for ON DELETE, ON UPDATE
• ON DELETE SET DEFAULT SQL Server sets the rows in the child table to their default
values if the corresponding rows in the parent table are deleted.
• ON UPDATE CASCADE / ON DELETE CASCADE A foreign key with cascade delete means
that if a record in the parent table is updated or deleted, then the corresponding records in
the child table will automatically be deleted
• Figure (next slide) gives some examples
• A constraint can be given a constraint name; this allows to DROP the
constraint later
• Figure (next slide) illustrates naming of constraints
Relational
Schema
SQL ─ INSERT QUERY
29
OPERATIONS TO MODIFY RELATIONS
• Three basic operations:
– INSERT
– DELETE
– UPDATE
SQL STATEMENTS FOR UPDATING THE DATABASE
42
INSERTING DATA INTO TABLES WITH
REFERENTIAL CONSTRAINTS
If you are inserting data into a dependent table with foreign keys:
1- Each non-null value you insert into a foreign key column must be equal to
some value in the corresponding parent key of the parent table.
2- If any column in the foreign key is null, the entire foreign key is considered
null. If all foreign keys that contain the column are null, the INSERT succeeds
(as long as there are no unique index violations).
43
Ssn Dnumber Emp_start_date
Ssn Dnumber Emp_start_date
UPDATED COMPANY relational database schema
SQL ─ SELECT QUERY
48
SQL ─ SELECT QUERY
49
SQL ─ SELECT QUERY
50
NORTHWIND DATABASE - PRACTICING
SELECTING SPECIFIC COLUMNS
/*
Select the FirstName and LastName
columns from the Employees table.
*/
SELECT FirstName, LastName
FROM Employees;
51
NORTHWIND DATABASE - PRACTICING
SELECTING SPECIFIC COLUMNS
Duration: 5 to 15 minutes.
In this exercise, you will practice selecting specific columns from tables in the Northwind
database.
52
NORTHWIND
Solution:
DATABASE - PRACTICING
SELECTING SPECIFIC COLUMNS
SELECT CategoryName, Description
FROM Categories;
54
SQL ─ ALIAS SYNTAX
Note: It requires double quotation marks or square brackets if the alias
name contains spaces:
Example
SELECT CustomerName AS Customer, ContactName AS “Contact Person”
FROM Customers;
55
SQL ─ ALIAS SYNTAX – COMBINE COLUMNS
The following SQL statement creates an alias named “Full_Name" that combines two columns
(FirstName and LastName) in one displayed column:
56
SQL ─ ALIAS SYNTAX
The following SQL statement creates an alias named "Address" that combine four columns
(Address, PostalCode, City and Country):
Example
SELECT CONCAT(ContactName, Address , “ “, PostalCode, “ , ”, City, Country) AS Address
FROM Customers;
Select *
57
THE SQL SELECT LIMIT
The SELECT LIMIT clause is used to specify the number of records to return.
58
SQL ─ WHERE CLAUSE
The SQL WHERE clause is used to specify a condition while fetching the data
from a single table or by joining with multiple tables. If the given condition is
satisfied, then only it returns a specific value from the table.
The WHERE clause is not only used in the SELECT statement, but it is also
used in the UPDATE, DELETE statement, etc.
59
SQL ─ WHERE CLAUSE
Example:
60
SQL – OPERATORS
An operator is a reserved word or a character used primarily in an SQL
statement's WHERE clause to perform operation(s)
Comparison operators
Arithmetic operators
Logical operators
Operators used to negate conditions
61
SQL COMPARISON OPERATORS
Assume ‘variable a’ holds 10 and ‘variable b’ holds 20, then:
62
SQL COMPARISON OPERATORS
63
NORTHWIND DATABASE - PRACTICING
THE WHERE CLAUSE AND OPERATOR SYMBOLS
- CHECKING FOR EQUALITY
/*
Create a report showing the title and the first and
last name
of all sales representatives.
*/
64
NORTHWIND DATABASE - PRACTICING
CHECKING FOR INEQUALITY
/*
Create a report showing the first and last name of
all employees
excluding sales representatives.
*/
65
NORTHWIND DATABASE - PRACTICING
CHECKING FOR GREATER OR LESS THAN
/*
Create a report showing the first and last name of
all employees whose last names start with a letter
in the last half of the alphabet.
*/
66
THE AND OPERATOR
67
NORTHWIND DATABASE - PRACTICING
THE AND OPERATOR
/*
Create a report showing the first and last name of all
sales representatives whose title of courtesy is "Mr.".
*/
68
THE OR OPERATOR
69
THE OR OPERATOR
/*
Create a report showing the first and last name and the city of all
employees who are from Seattle or Redmond.
*/
70
ORDER OF EVALUATION
By default, SQL processes AND operators before it processes OR operators. To illustrate
how this works, take a look at the following example.
/*
Create a report showing the first and last name of all sales
representatives who are from Seattle or Redmond.
*/
71
WRITING SELECTS WITH MULTIPLE
CONDITIONS
In this exercise, you will practice writing SELECT statements that filter records
based on multiple conditions.
1. Create a report that shows the first and last names and cities of
employees from cities other than Seattle in the state of Washington.
2. Create a report that shows the company name, contact title, city and
country of all customers in Mexico or in any city in Spain except Madrid.
72
SOLUTION
SELECT FirstName, LastName, City
FROM Employees
WHERE Region = 'WA' AND City <> 'Seattle';
73
SQL MIN() AND MAX() FUNCTIONS
The MIN() function returns the smallest value of the selected column.
The MAX() function returns the largest value of the selected column.
Example
SELECT MAX(UnitPrice) AS LargestPrice
FROM Products;
74
SQL COUNT(), AVG() AND SUM() FUNCTIONS
The COUNT() function returns the number of rows that matches a specified
criteria.
The AVG() function returns the average value of a numeric column.
The SUM() function returns the total sum of a numeric column.
75
SQL COUNT(), AVG() AND SUM() FUNCTIONS
count() Example
The following SQL statement finds the number of products:
SELECT count(ProductID)
FROM Products;
avg() Example
The following SQL statement finds the average price of all
products:
SELECT avg(UnitPrice)
FROM Products;
sum() Example
The following SQL statement finds the sum of the "Quantity"
fields in the "OrderDetails" table:
SELECT sum(Quantity)
FROM OrderDetails;
76
NORTHWIND DATABASE - PRACTICING
CHECKING FOR NULL
/*
Create a report showing the first and last names of
all
employees who have a region specified.
*/
77
NORTHWIND DATABASE - PRACTICING
CHECKING FOR NULL
/*
Create a report showing the first and last names of
all employees whose region is unspecified.
*/
78
NORTHWIND DATABASE - PRACTICING
WHERE AND ORDER BY
/*
Create a report showing the first and last name of all employees
whose
last names start with a letter in the last half of the alphabet.
Sort by LastName in descending order.
*/
79
SQL LIKE OPERATOR
80
SQL LIKE OPERATOR
81
SQL LIKE OPERATOR
Example: selects all customers with a CustomerName starting with "a":
SELECT * FROM Customers
WHERE ContactName LIKE ‘a%’;
Example: selects all customers with a CustomerName that have "or" in any position:
SELECT * FROM Customers
WHERE ContactName LIKE '%or%';
82
SQL LIKE OPERATOR
Example: selects all customers with a CustomerName that have "r" in the second position:
SELECT * FROM Customers
WHERE ContactName LIKE '_r%';
Example: selects all customers with a CustomerName that starts with "a" and are at least 3
characters in length:
SELECT * FROM Customers
WHERE ContactName LIKE 'a_%_%';
Example: selects all customers with a ContactName that starts with "a" and ends with "o":
SELECT * FROM Customers
WHERE ContactName LIKE 'a%o';
83
SQL UPDATE STATEMENT
The UPDATE statement is used to modify the existing records in a table.
It is the WHERE clause that determines how many records that will be
updated.
The following SQL statement will update the contactname to "Juan" for all
records where country is "Mexico":
Example
UPDATE Customers
SET ContactName='Juan'
WHERE Country='Mexico';
85
SQL DELETE
The DELETE statement is used to delete existing records in a table.
Example
The following SQL statement deletes the customer "Alfreds Futterkiste" from
the "Customers" table:
Example
DELETE FROM Customers WHERE CustomerName='Alfreds Futterkiste';
86
SQL DELETE
Delete All Records
It is possible to delete all rows in a table without deleting the table. This
means that the table structure, attributes, and indexes will be intact:
DELETE FROM table_name;
The following SQL statement deletes all rows in the "Customers" table,
without deleting the table:
Example
DELETE FROM Customers;
87