Chapter 6 The SQL Language Part II
Chapter 6 The SQL Language Part II
The Data Manipulation Language (DML) is used to retrieve, insert and modify database
information
INSERT INTO: This is used to add records into a relation. These are three type of INSERT
INTO queries which are as
Syntax:
Example
Run the following queries:
1
Sex varchar(6) default 'Male'
)
INSERT INTO Student (StudID, FirstName, LastName, Sex)
VALUES ('AB101', 'Jemal', 'Abdella', 'Male')
2
Exercise- INSERT Query
1. .Run the following create sql query in testdb
3
The following example inserts multiple rows using the
multirow VALUES syntax
UPDATE Statement
To modify existing data in a table, you use the following UPDATE statement:
UPDATE
table_name
SET
c1 = v1,
c2 = v2,
...,
cn = vn
[WHERE condition]
In this syntax:
First, specify the name of the table you want to update data after the UPDATE keyword.
Second, specify a list of columns c1, c2, …, cn and new values v1, v2, … vn in the SET
clause.
Third, filter the rows to update by specifying a condition in the WHERE clause. The
WHERE clause is optional. If you skip the WHERE clause, the statement will update all
rows in the table.
4
Examples:
DELETE Statement
To remove one or more rows from a table completely, you use the DELETE
statement. The following illustrates its syntax:
Examples
1. The following statement will delete all rows from the COMPANY table.
DELETE FROM COMPANY
2. The following statement will one row from the COMPANY table.
The SELECT statement is used to query the database (one or more tables from the database) and
retrieve selected data that match the criteria that you specify. The SELECT statement has five main
clauses to choose from, although, FROM is the only required clause. Each of the clauses has a vast
selection of options, parameters, etc. The clauses will be listed and discussed below:
USE database_name
[WHERE "conditions"]
[GROUP BY "column-list"]
[HAVING "conditions]
ALL and DISTINCT are keywords used to select either ALL (default) or the "distinct" or unique
records in your query results. If you would like to retrieve just the unique records in specified
columns, you can use the "DISTINCT" keyword. DISTINCT will discard the duplicate records for
the columns you specified after the "SELECT" statement.
7
Retrieving data from a single table
To retrieve data from a table, you use the SELECT statement with the following syntax:
SELECT
select_list
FROM
schema_name.table_name
Example:
1. Write a SELECT statement to retrieve the first and last names of all customers
SELECT FirstName,LastName
FROM customer;
Ouput:
The column names that follow the SELECT keyword determine which columns will be returned
in the results. You can select as many column names that you'd like, or you can use a "*" to
select all columns.
The table name that follows the keyword FROM specifies the table that will be queried to
retrieve the desired results.
The WHERE clause (optional) specifies which data values or rows will be returned or
displayed, based on the criteria described after the keyword WHERE. Comparison Operators
used in the WHERE clause are the following:
8
= Equal
*Note: LIKE is a very powerful operator that allows you to select only rows that are "like" what
you specify. The percent sign "%" can be used as a wild card to match any possible character
that might appear before or after the characters specified.
2. Write a SELECT statement to retrieve the FirstName,LastName and phone of all customers.
select FirstName,LastName,Phone
from customer
To retrieve data from all table columns, you can specify all the columns in the SELECT list.
Alternatively, you can also use SELECT * as a shorthand to select all columns:
select *
from customer
Output:
9
Exercises
When processing the SELECT statement, SQL Server first processes the FROM clause, followed
by the SELECT clause, even though the SELECT clause appears before the FROM clause:
Syntax:
SELECT TOP (expression) [PERCENT]
FROM
table_name
Example:
1. Write a query that returns Id,ProductName and UnitPrice of the 10 top records from products
table.
10
Write a query that returns 5 percent of the whole records from the products table.
Column Alias
A column alias allows you to assign a column or an expression in the select list of a SELECT
statement a temporary name. The column alias exists temporarily during the execution of the
query.
Syntax of using a column alias:
SELECT column_name AS alias_name FROM table_name
Or
SELECT column_name alias_name FROM table_name;
Note: The AS keyword is optional
Syntax:
The basic syntax of SELECT statement with WHERE clause is as follows:
The WHERE clause (optional) specifies which data values or rows will be returned or
displayed, based on the criteria described after the keyword WHERE.
11
o The SQL WHERE clause filters data that meet some criteria.
o WHERE only returns the rows you're interested in.
o A WHERE condition returns either true or false
Note: The WHERE clause is not only used in SELECT statements, it is also used in UPDATE,
DELETE, etc.!
12
Order of Evaluation:
• Evaluates the WHERE clause after the FROM clause and before the SELECT and
ORDER BY clause:
Examples:
1. List all customers in Sweden.
13
WHERE Country = 'Sweden'
The SQL AND and OR operators are used to combine multiple conditions to narrow data in an
SQL statement. These two operators are called conjunctive operators.
These operators provide a means to make multiple comparisons with different operators in the
same SQL statement.
14
You can combine N number of conditions using AND operator. For an action to be taken by the
SQL statement, whether it be a transaction or query, all conditions separated by the AND must
be TRUE.
Example:
1. Select all customers with id greater than 80 and who are from ‘USA”
SELECT Id, FirstName, LastName, City, Country, Phone
FROM Customer
Where Id>80 and Country='USA'
The OR Operator:
The OR operator is used to combine multiple conditions in an SQL statement's WHERE clause.
Syntax:
The basic syntax of OR operator with WHERE clause is as follows:
You can combine N number of conditions using OR operator. For an action to be taken by the
SQL statement, whether it be a transaction or query, only any ONE of the conditions separated
by the OR must be TRUE.
Example:
1. Select all customers with id greater than 80 or who are from ‘USA”
SELECT Id, FirstName, LastName, City, Country, Phone
FROM Customer
Where Id>80 or Country='USA'
15
Using WHERE clause with the IN operator
• If you want to match a string with any string in a list, you can use the IN operator.
• You use IN operator in the WHERE clause to check if a value matches any value in a list
of values.
• The syntax of the IN operator is as follows:
value IN (value1,value2,...)
Example:
1. The following statement returns customers whose first name is Howard, or John, or Mary:
SELECT Id, FirstName, LastName, City, Country, Phone
FROM Customer
Where FirstName in ('Howard', 'John','Mary')
16
Using WHERE clause with the NOT IN operator
You can combine the IN operator with the NOT operator to select rows whose values do not
match the values in the list.
Syntax:
value IN (value1,value2,...)
Example:
To find a string that matches a specified pattern, you use the LIKE operator.
There are two wildcards used in conjunction with the LIKE operator.
Syntax:
17
You can combine N number of conditions using AND or OR operators. Here, XXXX could be
any numeric or string value.
Statement Description
WHERE SALARY LIKE '200%' Finds any values that start with 200
WHERE SALARY LIKE '%200%' Finds any values that have 200 in any position
WHERE SALARY LIKE '_00%' Finds any values that have 00 in the second and third
positions
WHERE SALARY LIKE '2_%_%' Finds any values that start with 2 and are at least 3
characters in length
WHERE SALARY LIKE '%2' Finds any values that end with 2
WHERE SALARY LIKE '_2%3' Finds any values that have a 2 in the second position
and end with a 3
WHERE SALARY LIKE '2___3' Finds any values in a five-digit number that start with 2
and end with 3
Example:
1. List of customers whose names are starting with the letter ‘A’:
SELECT Id, FirstName, LastName, City, Country, Phone
FROM Customer
Where FirstName like 'A%'
2. List of customers whose names are starting with the letter ‘Ann’.
SELECT Id, FirstName, LastName, City, Country, Phone
FROM Customer
Where FirstName like 'Ann%'
Example:
18
SELECT Id, FirstName, LastName, City, Country, Phone
FROM Customer
Where FirstName not like 'Ann%'
Using the WHERE clause with the not equal operator (<>)
Example:
Finds customers whose first names start with Yoshi and last names are not Latimer.
• Note that you can use the != operator and <> operator interchangeably because they are
equivalent.
19
Using the WHERE clause with the IS NULL operator
Example:
Select FirstName,LastName,Phone
From Customer
Where Phone IS NULL
Table aliases
• Table aliases temporarily assign tables new names during the execution of a query.
table_name AS alias_name;
or
table_name alias_name;
Syntax:
The basic syntax of ORDER BY clause is as follows:
SELECT column-list
FROM table_name
[WHERE condition]
[ORDER BY column1 [ASC | DESC], column2, .. columnN] [ASC | DESC];
You can use more than one column in the ORDER BY clause. Make sure whatever column you
are using to sort, that column should be in column-list.
20
Order of Evaluation
Example:
1. The following query uses the ORDER BY clause to sort customers by their first names in
ascending order:
SELECT Id, FirstName, LastName, City, Country, Phone
FROM Customer
order by FirstName
2. The following query uses the ORDER BY clause to sort customers by their first names in
descending order:
SELECT Id, FirstName, LastName, City, Country, Phone
FROM Customer
order by FirstName desc
SELECT SELECT
FROM FROM
table_name; table_name;
21
CREATE TABLE distinct_demo (
id serial NOT NULL PRIMARY KEY,
bcolor VARCHAR,
fcolor VARCHAR
);
1.
SELECT
id,
bcolor,
fcolor
FROM distinct_demo ;
2.
SELECT DISTINCT bcolor
FROM distinct_demo
ORDER BY bcolor;
• The query returns the unique combination of bcolor and fcolor from the distinct_demo
table
22
Aggregate functions
• An aggregate function is a function that performs a calculation on a set of values, and returns
a single value.
• Are used to summarize the results of a particular column
• Aggregate functions are often used with the GROUP BY clause of the SELECT statement.
The GROUP BY clause splits the result-set into groups of values and the aggregate function
can be used to return a single value for each group.
• These are:
– MIN():returns the smallest value within the selected column
– MAX():returns the largest value within the selected column
– SUM():returns the total sum of a numerical column
– AVG():returns the average value of a numerical column
– COUNT():returns the number of rows in a set
COUNT Function
SQL COUNT function is the simplest function and very useful in counting the number of
records, which are expected to be returned by a SELECT statement.
Example:
1. Count total number of rows in the Customer’s table, then you can do it as follows:
23
1. Find the largest order amount.
SQL GROUP BY
The GROUP BY clause will gather all of the rows together that contain data in the specified
column(s) and will allow aggregate functions to be performed on the one or more columns.
SELECT column-names
FROM table-name
WHERE condition
GROUP BY column-names
ORDER BY column-names
24
Example:
List the number of customers in each country.
Table Joins
All of the queries up until this point have been useful with the exception of one major limitation -
that is, you've been selecting from only one table at a time with your SELECT statement. It is time
to introduce you to one of the most beneficial features of SQL & relational database systems - the
"Join". To put it simply, the "Join" makes relational database systems "relational".
Joins allow you to link data from two or more tables together into a single query result--from one
single SELECT statement.
A "Join" can be recognized in a SQL SELECT statement if it has more than one table after the
FROM keyword.
Syntax:
SELECT list-of-columns
WHERE search-condition(s)
26
The following queries are based the schema shown below.
GO
USE JoinExamples;
GO
Location VARCHAR(50)
);
27
-- Create Employees table
Email VARCHAR(100),
HireDate DATE,
Salary DECIMAL(10,2),
);
Budget DECIMAL(12,2),
StartDate DATE,
EndDate DATE
);
28
-- Create junction table for many-to-many relationship
HoursWorked INT,
);
29
(5, 5, 60),
(6, 2, 130),
(7, 5, 85);
Employees Table
Departments-Table
30
Projects Table
EmployeeProjects-Table
31
SQL JOIN Types
• Joins clause is used to combine records from two or more tables in a database.
• A JOIN is a means for combining fields from two tables by using values common to each
• A CROSS JOIN matches every row of the first table with every row of the second table
• If the input tables have x and y columns, respectively, the resulting table will have x+y
columns
Solution
--- - Create all possible combinations of employees and departments
-- (Not typically useful for business queries, but demonstrates the concept)
select *
from Employees
cross join Departments
32
Query Output:
• An INNER JOIN creates a new result table by combining column values of two tables (table1
and table2) based upon the join-predicate.
• The query compares each row of table1 with each row of table2 to find all pairs of rows, which
satisfy the join-predicate.
• When the join-predicate is satisfied, column values for each matched pair of rows of table1
and table2 are combined into a result row.
33
• INNER JOIN statement returns only those records or rows that have matching values and is
used to retrieve data that appears in both tables.
• An INNER JOIN is the most common type of join and is the default type of join. You can
use INNER keyword optionally.
• The following is the syntax of INNER JOIN –
select [Link],[Link],[Link],[Link],[Link]
from Employees e
inner join Departments d
on [Link]=[Link]
where [Link]='IT'
34
5. Three-Table Join (All Assignments)
SELECT
[Link] + ' ' + [Link] AS EmployeeName,
[Link],
[Link]
FROM
Employees e
INNER JOIN
EmployeeProjects ep ON [Link] = [Link]
INNER JOIN
Projects p ON [Link] = [Link]
ORDER BY
[Link], [Link];
• In LEFT OUTER JOIN, an inner join is performed first. Then, for each row in table T1
that does not satisfy the join condition with any row in table T2, a joined row is added
with null values in columns of T2.
• Thus, the joined table always has at least one row for each row in T1.
• The following is the syntax of LEFT OUTER JOIN −
SELECT ...
FROM table1 LEFT OUTER JOIN table2
ON conditional_expression ...
6. LEFT JOIN (or LEFT OUTER JOIN)
- -Get all employees and their departments (including employees without departments)
SELECT *
FROM Employees e
LEFT JOIN Departments d ON [Link] = [Link];
• In RIGHT OUTER JOIN, an inner join is performed first. Then, for each row in
table T2 that does not satisfy the join condition with any row in table T1, a joined
row is added with null values in columns of T1.
• Thus, the joined table always has at least one row for each row in T2.
35
• The following is the syntax of RIGHT OUTER JOIN −
SELECT ...
FROM table1 RIGHT OUTER JOIN table2
ON conditional_expression ...
SELECT *
FROM Employees e
RIGHT JOIN Departments d ON [Link] = [Link];
• First, an inner join is performed. Then, for each row in table T1 that does not satisfy
the join condition with any row in table T2, a joined row is added with null values
in columns of T2. In addition, for each row of T2 that does not satisfy the join
condition with any row in T1, a joined row with null values in the columns of T1 is
added.
36
8. Non-Equi Join (join condition not using equals)
-- Find projects that started after the employee was hired
Subqueries
A subquery (or inner query/nested query) is a SQL query nested inside another SQL query
(typically in the WHERE, FROM, or SELECT clause). Subqueries allow you to break down
complex problems into logical parts.
Types of Subqueries
37
Subquery Examples Using the Employee Database
select *
from Employees
where salary > (
select avg(Salary)
from EMployees
A view is a virtual table based on the result set of a SQL statement. Views allow you to:
38
Basic Syntax for Creating Views
Examples:
from Employees e
inner join Departments d on [Link]=[Link]
39
Addition examples on joins
Select *
40
Output of the cross join
Solution:
select a,fruit_a,b,fruit_b
from basket_a inner join basket_b
on fruit_a=fruit_b
41
Output:
Solution:
select a,fruit_a,b,fruit_b
from basket_a left outer join basket_b
on fruit_a=fruit_b
Output:
42
4. Find the right out join between fruit_a and fruit_b
Solution:
select a,fruit_a,b,fruit_b
from basket_a right outer join basket_b
on fruit_a=fruit_b
Output:
Solution:
select a,fruit_a,b,fruit_b
from basket_a full outer join basket_b
on fruit_a=fruit_b
43
Additional Examples
2. List the number of customers in each country. Only include countries with more than 10
customers
3. List the number of customers in each country, except the USA, sorted high to low. Only
include countries with 9 or more customers.
44
4. Select the distinct items in the items_ordered table. In other words, display a listing of each
of the unique items from the items_ordered table.
FROM items_ordered
WHERE customerid=10339;
2.
3.
FROM items_ordered
4.
FROM items_ordered;
45
Review Exercises
1. Select the maximum price of any item ordered in the items_ordered table. Hint: Select the
maximum price only.
2. Select the average price of all of the items ordered that were purchased in the month of Dec.
4. For all of the flashlight that were ordered in the items_ordered table, what is the price of the
lowest flashlight? Hint: Your query should return the price only.
Exercise #1
FROM items_ordered;
Exercise #2
FROM items_ordered
Exercise #3
FROM items_ordered;
Exercise #4
46
Use empInfo table for the exercises that follow:
FROM empInfo
GROUP BY dept;
Answer:
OR
FROM empInfo
GROUP BY dept;
47
Review Exercises
1. How many people are in each unique city in the customers table?
Select the city and display the number of people in each. Hint:
COUNT is used to count rows in a column, SUM works on numeric data only.
2. From the items_ordered table, select the item, maximum price, and minimum price for each
specific item in the table. Hint: The items will need to be broken up into separate groups.
3. How many orders did each customer make? Use the items_ordered table. Select the
customerid, number of orders they made, and the sum of their orders.
Exercise #1
FROM customers
GROUP BY city;
Exercise #2
FROM items_ordered
GROUP BY item;
Exercise #3
FROM items_ordered
GROUP BY customerid;
48
Examples:
FROM employee
GROUP BY dept;
FROM employee
GROUP BY dept
Use items_ordered and customers table for the exercises that follow:
Review Exercises (note: yes, they are similar to the group by exercises, but these contain
the HAVING clause requirements
1. How many peoples are in each unique city in the customers table that has more than one
person in the city? Select the city and display the number of how many people are in each if
it's greater than 1.
2. From the items_ordered table, select the item, maximum price, and minimum price for each
specific item in the table. Only display the results if the maximum price for one of the items
is greater than 190.00.
3. How many orders did each customer make? Use the items_ordered table. Select the
customerid, number of orders they made, and the sum of their orders if they purchased more
than 1 item.
49
Answers for the Review Exercises
Exercise #1
FROM customers
GROUP BY city
Exercise #2
FROM items_ordered
GROUP BY item
Exercise #3
FROM items_ordered
GROUP BY customerid
50
Example:
The following statement will select the empID, dept, FirstName, age, and salary from the
empInfo table where the dept equals 'Sales' and will list the results in Ascending (default) order
based on their Salary.
FROM empInfo
ORDER BY salary
If you would like to order based on multiple columns, you must separate the columns with
commas. For example:
FROM EmpInfo
Use items_ordered and customers table for the exercises that follow:
Review Exercises
1. Select the lastname, firstname, and city for all customers in the customers table. Display the
results in Ascending Order based on the lastname.
2. Same thing as exercise #1, but display the results in Descending order.
3. Select the item and price for all of the items in the items_ordered table that the price is
greater than 10.00. Display the results in Ascending order based on the price.
51
Answers for the Review Exercises
Exercise #1
FROM customers
ORDER BY lastname;
Exercise #2
FROM customers
Exercise #3
FROM items_ordered
52
Examples:
FROM EmpInfo
2.
FROM EmpInfo
Review Exercises
1. Select the customerid, order_date, and item from the items_ordered table for all items unless
they are 'Shoes' or if they are ‘Sharpner’. Display the rows as long as they are not either of these
two items.
2. Select the item and price of all items that start with the letters 'S', 'P', or 'F'.
Exercise #1
FROM items_ordered
Note: Yes, that is correct, you do want to use an AND here. If you were to use an OR here, then
either side of the OR will be true, and EVERY row will be displayed. For example, when it
encounters 'Sharpener', it will evaluate to True since 'Sharpener' are not equal to 'Shoes'.
53
Exercise #2
FROM items_ordered
WHERE (item LIKE 'S%') OR (item LIKE 'P%') OR (item LIKE 'F%');
Exercise 1: Write a SQL statement that could retrieve any first names that start with ‘A’ and
show only the FirstName, LastName and city columns.
Answer:
USE mydatabase
FROM empinfo
Exercise 2: Write a SQL statement that could retrieve any last names that end in a ‘T’ and show
only the FirstName and LastName columns.
Answer:
USE mydatabase
FROM empinfo
54
Exercise 3: Write a SQL statement that could retrieve a row (rows) with first name equals
‘Lydia’.
Answer:
USE mydatabase
Example
FROM EmpInfo
The IN conditional operator can be rewritten by using compound conditions using the equals (=)
operator and combining it with
OR -
FROM EmpInfo
55
.
FROM EmpInfo
This statement will select the EmpID, age, lastname, and salary from the EmpInfo table where
the age is between 30 and 40 (including 30 and 40).
FROM EmpInfo
You can also use NOT BETWEEN to exclude the values between your ranges.
Use items_ordered and customers table for the exercises that follow:
Review Exercises
1. Select the date, item, and price from the items_ordered table for all of the rows that have a
price value ranging from 10.00 to 80.00.
2. Select the firstname, lastname and city from the customers table for all of the rows where the
city value is either: Addis Ababa, Durame, Semera, Assosa, or Mettu.
56
Answers for the Review Exercises
Exercise #1
FROM items_ordered
Exercise #2
FROM customers
‘Mettu’);
57
Use the following three tables to answer the following questions.
“CustomerInfo” table
Examples:
[Link]
This is the most common type of "Join" that you will see or use.
58
Notice that each of the columns is always preceded with the table name and a period. This isn't
always required; however, it is good practice so that you won’t confuse which columns go with
what tables.
It is required if the name column names are the same between the two tables. I recommend
preceding all of your columns with the table names when using joins.
Note: The syntax described above will work with most Database Systems. However, in the
event that this doesn't work with yours, please check your specific database documentation.
Although the above will probably work, here is the ANSI SQL-92 syntax specification for an
Inner Join using the preceding statement above that you might want to try:
ON customer_info.customerid = [Link]
Use items_ordered and customers table for the exercises that follow:
Review Exercises
1. Write a query using a join to determine which items were ordered by each of the customers in
the customers table. Select the customerid, firstname, lastname, order_date, item, and price for
everything each customer purchased in the items_ordered table.
2. Repeat exercise #1, however display the results sorted by city in descending order.
Exercise #1
Option One:
59
items_ordered.order_date, items_ordered.item, items_ordered.price
Option Two:
ON [Link] = items_ordered.customerid;
Exercise #2
Option One:
items_ordered.item
Option Two:
items_ordered.item
ON [Link] = items_ordered.customerid
60
)
Example 1(Subqueries(Nested Queries): Suppose you have the Branch and Staff Tables shown
below; List the staffs who work in the Branch at ‘163 Main St’.
Answer:
FROM Staff
FROM Branch
61
The inner SELECT statement (SELECT branchNo FROM Branch WHERE street = ‘163 Main
St) finds the branch number that corresponds to the branch with street name ‘163 Main St’.
Having obtained this branch number, the outer SELECT statement then retrieves the details of all
staff who work at this branch. In other words, the inner SELECT returns a result table containing
a single value ‘B003’, corresponding to the branch at ‘163 Main St’, and the outer SELECT
becomes:
FROM Staff
We can think of the subquery as producing a temporary table with results that can be accessed
and used by the outer statement. A subquery can be used immediately following a relational
operator (=, <, >, <=, >=, <>) in a WHERE clause, or a HAVING clause. The subquery itself is
always enclosed in parentheses.
Example2:- Suppose you have the Branch and Staff Tables shown above and another table
named PropertyForRent; List the properties that are handled by staff who work in the branch at
‘163 Main St’? PropertyForRent
62
Answer:
FROM propertForRent
FROM Staff
FROM Branch
Working from the innermost query outwards, the first query selects the number of the branch at
‘163 Main St’. The second query then selects those staffs who work at this branch number. In
this case, there may be more than one such row found, and so we can’t use the equality condition
(=) in the outermost query. Instead, we use the IN keyword. The outermost query then retrieves
the details of the properties that are managed by each member of staff identified in
the middle query. The result table is shown below:
63
Using a subquery with an aggregate function
Example3:- List all staff whose salary is greater than the average salary, and show by how much
their salary is greater than the average.
Answer:
FROM Staff
First, note that we can’t write ‘WHERE salary > AVG(salary)’ because aggregate functions
can’t be used in the WHERE clause. Instead, we use a subquery to find the average salary, and
then use the outer SELECT statement to find those staff with a salary greater than this average.
In other words, the subquery returns the average salary as 17000. Note also the use of the scalar
subquery in the SELECT list, to determine the difference from the average salary. The outer
query is reduced then to:
FROM Staff
64
Note: When a subquery is one of the two operands involved in a
comparison, the subquery must appear on the right-hand side of the comparison. For example, it
would be incorrect to express the last example as:
FROM Staff
SELECT LastName, city, age FROM empinfo WHERE age > 30;
65
Select statement exercises (Assume you are using mydatabase database)
1. Display everyone's first name and their age for everyone that's in table.
2. Display the first name, last name, and city for everyone that's not from A/A.
'A/A';
4. Display the first and last names for everyone whose last name ends in an "an".
'%an';
"Aster".
"Mar".
66
Example[ Views] Run the following
SELECT * FROM v;
However, after a view has been created, it is possible to drop a table or view that the definition
refers to. To check a view definition for problems of this kind, use the CHECK TABLE
statement.
ORDER BY is allowed in a view definition, but it is ignored if you select from a view using a
statement that has its own ORDER BY.
Some views are updatable. That is, you can use them in statements such as UPDATE, DELETE,
or INSERT to update the contents of the underlying table. For a view to be updatable, there must
be a one-to relationship between the rows in the view and the rows in the underlying table. There
67
are also certain other constructs that make a view non-updatable. To be more specific, a view is
not updatable if it contains any of the following:
DISTINCT
GROUP BY
HAVING
Subquery in the select list
Join
A subquery in the WHERE clause that refers to a table in the
FROM clause With respect to insertability (being updatable with INSERT statements), an
updatable view is insertable if it also satisfies these additional requirements for the view columns:
The view must contain all columns in the base table that do not have a default value.
The view columns must be simple column references and not derived columns. A derived column
is one that is not a simple column reference but is derived from an expression. These are examples
of derived columns: col1 + 3, col3 / col4, etc
A view that has a mix of simple column references and derived columns is not insertable, but it
can be updatable if you update only those columns that are not derived. Consider this view:
This view is not insertable because col2 is derived from an expression. But it is updatable if the
update does not try to update col2. This update is allowable:
68
ALTER VIEW Syntax
AS select_statement
This statement changes the definition of an existing view. The syntax is similar to that for
CREATE VIEW. This statement requires the
CREATE VIEW and DELETE privileges for the view, and some privilege for each column
referred to in the SELECT statement.
[RESTRICT | CASCADE]
DROP VIEW removes one or more views. You must have the DROP privilege for each view.
You can use the keywords IF EXISTS to prevent an error from occurring for views that don't
exist. When this clause is given, a NOTE is generated for each non-existent view. RESTRICT
and CASCADE, if given, are parsed and ignored.
69
The Schema shown below used in this document.
Customer: Stores information about customers (e.g., customer ID, name, email,
address).
o Includes:
Id
FirstName
LastName
City
Country
Phone
Product: Stores details about products (e.g., product ID, name, price).
Includes:
Id
ProductName
SupplierId
UnitPrice
Package
IsDicontinued
70
Order: Represents a transaction where a customer purchases one or more products
(e.g., order ID, date, total amount).
Includes:
Id
OrderDate
CustomerId
TotalAmount
Supplier: One supplier can provide multiple products, but each product is supplied by only one
supplier
Includes:
Id
ComapnyName
ContactName
City
Country
Phone
Fax
Relationships
Customer to Order:
Relationship: One-to-many.
One customer can place multiple orders, but each order is linked to only one customer.
Keys: CustomerID (primary key in Customer) is a foreign key in the Order table.
Order to OrderDetails:
Relationship: One-to-many.
One order can contain multiple line items (products), but each line item belongs to only
one order.
71
Keys: OrderID (primary key in Order) is a foreign key in the OrderDetails table.
Product to OrderDetails:
Relationship: One-to-many.
One product can appear in multiple order line items, but each line item references only
one product.
Keys: ProductID (primary key in Product) is a foreign key in the OrderDetails table
Order ↔ Product:
Supplier to Product:
Relationship: One-to-many.
One supplier can provide multiple products, but each product is supplied by only
one supplier (assuming a single-supplier model for simplicity; this could be many-to-
many with a junction table if multiple suppliers per product are allowed).
Keys: SupplierID (primary key in Supplier) is a foreign key in the Product table.
Customer table
72
Order table
Supplier table
73
Product table
OrderItem table
74