ADBS
ADBS
Lab Lecture
SQL
SQL SELECT: -
SELECT <columnlist>
FROM <tablename>
The following example retrieves the columns product_nbr and product_name from all
rows of the product table.
product_nbr product_name
1001 SQL Tool 1.0
2001 SQL Tool 2.0 Light
2002 SQL Tool 2.0 Professional
2003 SQL Tool 2.0 Enterprise
______________________________________________________________________
Computer Science Department Advanced SQL
1
Advanced Database System Lab notes
The following example retrieves all of the columns from all rows of the product table.
SELECT *
FROM product
Results show the product_status_code column that was not present in Example 1.
SQL WHERE: -
The SQL WHERE clause is that part of SQL statements that specifies which data is to be
accessed. It establishes conditions that control the results of a SQL statements.
Anytime you want to access certain rows within a table use the SQL WHERE clause. You
could use it to:
Show only certain rows (called filtering) with a SQL SELECT Statement.
Update row(s) with a specific condition.
Delete row(s) with a specific condition.
<main-statement>
WHERE <conditions>
Each condition tests column(s) using comparison operator(s). The following basic
comparison operators are supported:
______________________________________________________________________
Computer Science Department Advanced SQL
2
Advanced Database System Lab notes
OperatorDescription
= Equal
<> Not Equal
> Greater Than
< Less Than
>= Greater Than Or Equal
<= Less Than Or Equal
The comparison may involve literal value(s) that are constants like:
10
'Minnesota'
-5006.3
The product table contains four rows, including one row with a product_status_code with
a value of Inactive. We will use the SQL WHERE clause to filter for Active rows:
product_nbrproduct_name product_status_code
1001 SQL Tool 1.0 Inactive
2001 SQL Tool 2.0 Light Active
2002 SQL Tool 2.0 Professional Active
2003 SQL Tool 2.0 Enterprise Active
Results from the execution of the SQL SELECT statement with the WHERE clause are as
follows:
______________________________________________________________________
Computer Science Department Advanced SQL
3
Advanced Database System Lab notes
The customer table contains five rows, including two rows that have credit_balance_amt
greater than credit_limit_amt. We will use the SQL WHERE clause to filter for Active
rows:
Results from the execution of the SQL SELECT statement with the WHERE clause are as
follows:
SQL INSERT: -
The SQL INSERT statement is the SQL command that adds new rows to an SQL table.
Anytime you want to add new rows to an SQL table. For example, if you need to have
another product in the product table, then you would use the INSERT statement to insert
that product.
The following example adds a new row into the product table. Before the INSERT takes
place the folliwng information exists in the table:
product_nbrproduct_name
1001 SQL Tool Light
1002 SQL Tool Professional
1003 SQL Tool Enterprise
product_nbrproduct_name
1001 SQL Tool Light
1002 SQL Tool Professional
1003 SQL Tool Enterprise
2001 Data Modeling Tool Professional
SQL UPDATE: -
The SQL UPDATE statement is the SQL command that makes changes to data that exists
in a SQL database.
Anytime you want to change information in a SQL database use the SQL UPDATE
statement to cause the change.
______________________________________________________________________
Computer Science Department Advanced SQL
5
Advanced Database System Lab notes
UPDATE <table_name>
SET <column_name> = <column_value>
WHERE
SQL UPDATE Statement Example 1
product_nbr product_name
1001 SQL Tool Light
1002 SQL Tool Professional
1003 SQL Tool Enterprise
UPDATE product
SET product_name = 'SQL Tool UltraLight'
WHERE product_nbr = '1001'
product_nbr product_name
1001 SQL Tool Light
1002 SQL Tool Professional
1003 SQL Tool Enterprise
SQL DELETE: -
The SQL DELETE statement is the SQL command that removes data from an SQL
database.
Anytime you want to remove rows from a SQL table use the SQL DELETE statement to
remove the information.
______________________________________________________________________
DELETE
Computer Science FROM <table_name>
Department Advanced SQL
6
WHERE <where_conditions>
Advanced Database System Lab notes
The following example deletes the row in the product table with product_nbr of '1001'.
Before the execution of the SQL DELETE statement, the table contains this data:
product_nbrproduct_name
1001 SQL Tool Light
1002 SQL Tool Professional
1003 SQL Tool Enterprise
DELETE product
WHERE product_nbr = '1003'
After the execution of the SQL DELETE statement, the table contains this data:
product_nbr product_name
1001 SQL Tool Light
1002 SQL Tool Professional
The SQL CREATE DATABASE statement is the SQL command that adds a new database.
A database is the outer container for other SQL objects: tables, columns, views, indexes,
etc.
Anytime you want to start a new database. For example, you may want to start a new
project to integrate customer information and so create a database called
CUSTOMER_DB.
The SQL DROP DATABASE statement is the SQL command that removes an existing
database. A database is the outer container for other SQL objects: tables, columns, views,
indexes, etc.
Anytime you want to remove an existing database. For example, you may want to eliminate
a database called CUSTOMER_DB_DEV that is no longer required for database
development.
______________________________________________________________________
Computer Science Department Advanced SQL
8
Advanced Database System Lab notes
The SQL CREATE TABLE statement is the SQL command that adds a new table to an
SQL database. Tables are a basic unit of organization and storage of data in SQL. Each
table tends to represent an entity such as a customer, product, code or event. A table is
similar to a file in a non-database system.
Tables are organized into rows and columns. For example, a customer table would likely
have a separate row for each customer. Columns are attributes that describe a row. For
example, a row in a customer table would have columns like customer_name,
customer_nbr, account_balance_amt and established_date.
Anytime you want to add a new table to the database you would use the SQL CREATE
TABLE statement.
______________________________________________________________________
Computer Science Department Advanced SQL
9
Advanced Database System Lab notes
The following example creates a table named product with columns named product_nbr,
product_name, product_status_code, start_date, end_date and
raw_material_cost_amt.
Anytime you want to change the definition of an SQL table. For example, you could:
The following example adds a new column into the person table. Before the operation
takes place the following columns exists in the table:
Results from the execution of the SQL ALTER TABLE statement are:
______________________________________________________________________
Computer Science Department Advanced SQL
11
Advanced Database System Lab notes
The following example changes the datatype of an existing column in the person
table. Before the operation takes place the following columns exists in the table:
Results from the execution of the SQL ALTER TABLE statement are:
The following example removes an existing column in the person table. Before the
operation takes place the following columns exists in the table:
______________________________________________________________________
Computer Science Department Advanced SQL
12
Advanced Database System Lab notes
Results from the execution of the SQL ALTER TABLE statement are:
The SQL DROP TABLE statement is the SQL command that removes an entire SQL table.
Why Use the SQL DROP TABLE Statement?
______________________________________________________________________
Computer Science Department Advanced SQL
13
Advanced Database System Lab notes
When a SQL table must be removed, use the SQL DROP TABLE statement.
For example, you may have a created a temporary table to stored a report. When the report
analysis is complete, you may wish the "clean up" the database by removing the table.
reducing confusion
reducing disk space and resource requirements
Backup data
Remove / drop dependent information such as constraints (foreign keys).
An error condition may occur for a DROP TABLE statement if there are existing
constraints such as foreign keys that are dependent on the table.
The SQL INDEX TABLE statement is the SQL command that adds a new index to an
existing table to an SQL database. Indexed enable faster and more efficient retrieval of
information from SQL databases.
______________________________________________________________________
Computer Science Department Advanced SQL
14
Advanced Database System Lab notes
SQL indexes are used because they can provide the following benefits / functions:
Correct use of indexes can make the difference between a top performing database
with high customer satisfaction and a non-performing database with low customer
satisfaction.
The number of characters that can make up SQL names for tables, columns and indexes
varies by DBMS. In many cases the limit is 30 characters. The leading character of the
name must be alphabetic - not a number or special character. The name of a new index can
not duplicate the name of an existing index for the same table and should not be the same
as a SQL reserved word. The underscore character can be used to improve readability. List
elements are seperated by commas.
______________________________________________________________________
Computer Science Department Advanced SQL
15
Advanced Database System Lab notes
The SQL DROP INDEX statement is the SQL command that removes an entire SQL index.
You may drop an index permanently when it is no longer useful or temporarily. If the index
is harming or not helping performance it could be dropped.
Indexes may slow down the loading of data because they must be maintained during the
data load process. For high performance loads, an index could be dropped for the duration
of a load and then recreated.
______________________________________________________________________
Computer Science Department Advanced SQL
16
Advanced Database System Lab notes
A Foreign Key is a constraint that ensures that column(s) in one table match the primary
key column(s) in another table. For example, we may have a table named
SALES_ORDER_LINE that contains orders for products and a table named PRODUCT
that contains product information.
SALES_ORDER_LINE Table:
PRODUCT Table:
The SQL CREATE FOREIGN KEY clause is the SQL capability that adds a new foreign
key an existing table to an SQL database.
SQL foreign keys are used because they can provide the following benefits / functions:
The SQL DROP FOREIGN KEY clause is the SQL clause that removes an entire SQL
foreign key from a table. It is a clause of the SQL ALTER TABLE statement.
You may drop a foreign key permanently when it is no longer useful or temporarily. If the
foreign key is harming performance or not helping referential integrity it could be dropped.
Foreign keys may slow down the loading of data because they must be validated during the
data load process. For high performance loads, a foreign key could be dropped for the
duration of a load and then recreated.
Before dropping a table, it may be necessary to drop foreign keys refering to that table.
A SQL view is a virtual table and the SQL CREATE VIEW statement is the SQL
command that adds a new view to a SQL database.
______________________________________________________________________
Computer Science Department Advanced SQL
19
Advanced Database System Lab notes
A view can be accessed using the SQL SELECT statement like a table. A view is built by
selecting data from one or more tables.
Some views can also support the SQL INSERT, SQL UPDATE and SQL DELETE
statements. In that case, the view must refer to a single table and include all NOT NULL
columns of that table.
SQL views are used because they can provide the following benefits / functions:
The number of characters that can make up SQL names for tables, columns and views
varies by DBMS. In many cases the limit is 30 characters. The leading character of the
name must be alphabetic - not a number or special character. The name of a new view can
not duplicate the name of an existing view or table and should not be the same as a SQL
reserved word. The underscore character can be used to improve readability. List elements
are seperated by commas.
customer_id
customer_name
ytd_sales_amt
______________________________________________________________________
Computer Science Department Advanced SQL
20
Advanced Database System Lab notes
zip_code
The SQL DROP VIEW statement is the SQL command that removes an entire SQL view.
You may drop an view permanently when it is no longer useful or temporarily. If the view
is not useful it could be dropped.
Also, if a view needs to be changed it would be dropped and then created again with
changes in place.
______________________________________________________________________
Computer Science Department Advanced SQL
21
Advanced Database System Lab notes
SQL CONCAT: -
For example, the concatenation of 'John', ' ', 'W', '. ' and 'Smith' is
'John W. Smith'
'212-555-1234'
Concatenation can result in more readable output while maintaining data in separate
columns for greater flexibility.
More than 2 strings can be combined through concatenation. Numbers must be converted
to strings before concatenation.
______________________________________________________________________
Computer Science Department Advanced SQL
22
Advanced Database System Lab notes
<value_1> + <value_2>
The following example concatenates the column branch_name with column region_name
along with spaces and parens for readability.
Table: REGION
region_nbrregion_name
100 East Region
200 Central Region
300 Virtual Region
400 West Region
Table: BRANCH
branch_name (region_name)
New York (East Region)
______________________________________________________________________
Computer Science Department Advanced SQL
23
Advanced Database System Lab notes
SUBSTRING: -
The SQL Substring feature is a function that enables parts of strings to be accessed.
'1234'
This example returns three characters of the region_name column starting in position 2.
Table: REGION
region_nbrregion_name
100 East Region
200 Central Region
300 Virtual Region
400 West Region
______________________________________________________________________
Computer Science Department Advanced SQL
24
Advanced Database System Lab notes
region_name substring_name
East Region ast
Central Region ent
Virtual Region irt
West Region est
SQL TRIM: -
The SQL Trim feature is are functions (LTRIM and RTRIM) that remove leading and
trailing blanks from a string.
'Minnesota'
The SQL Trim functions (LTRIM and RTRIM) are useful in cleansing data that contains
leading and trailing blanks.
SELECT LTRIM(<value_1>)
SELECT RTRIM(<value_1>)
______________________________________________________________________
Computer Science Department Advanced SQL
25
Advanced Database System Lab notes
The LTRIM function removes the leading blanks in the string ' Bob'.
trimmed_string
Bob
The SQL AND & OR operators support compound conditions in the SQL WHERE clause.
Use SQL AND & OR operators in case when a WHERE clause requires multiple
conditions. For example, we may want to select a list of CUSTOMERS whose accounts are
on credit hold and whole credit balance exceeds the credit limit. Such a statement may look
like this:
SQL AND & OR are placed between conditions to create compound conditions.
Parenthesis can be used to group conditions.
SELECT <column_list>
FROM <table_name>
WHERE <condition_1>
AND|OR <condition_2>
______________________________________________________________________
Computer Science Department Advanced SQL
26
Advanced Database System Lab notes
The following example selects a list of rows from the branch table that have an
employee_count less than 4 or greater than 6.
Table: BRANCH
branch_nbrbranch_name employee_count
108 New York 10
415 San Jose 3
SQL IN: -
The SQL IN operator is a clean way to check for inclusion in lists without creating a series
of OR clauses.
SQL IN Syntax
______________________________________________________________________
Computer Science Department Advanced SQL
27
Advanced Database System Lab notes
SELECT <column_list>
FROM <table_name>
WHERE <column_name IN (value_list)>
There must be one or more members of the value_list. Numeric and non-numeric values are
supported.
SQL IN Example
The following example selects information from the BRANCH where the region_nbr is
IN a specified list of region_nbr values.
Table: BRANCH
branch_nbrbranch_name region_nbr
212 Chicago 200
404 San Diego 400
415 San Jose 400
SQL BETWEEN: -
The SQL BETWEEN operator is a clean way to check for inclusion in a range without
requiring an AND operator.
SELECT <column_list>
FROM <table_name>
WHERE <column_name> BETWEEN
<lower_value> AND <higher_value>
The following example lists rows in the branch that have employee_count in range from 4
to 7. Here are the contents of the table:
Table: BRANCH
branch_nbrbranch_name employee_count
110 Boston 6
212 Chicago 5
404 San Diego 6
SQL LIKE: -
______________________________________________________________________
Computer Science Department Advanced SQL
29
Advanced Database System Lab notes
The SQL LIKE operator enables a comparison to a part of a string using the % wild card
character.
The SQL LIKE operator is a powerful way to check for matching strings. It is often used
for interactive display of lists.
SELECT <column_list>
FROM <table_name>
WHERE <column_name> LIKE <like_condition>
The <like_condition> supports the following patterns:
The following example lists rows from the branch table where branch_name begins with
the leading characters 'San'.
Table: BRANCH
______________________________________________________________________
Computer Science Department Advanced SQL
30
Advanced Database System Lab notes
branch_nbrbranch_name employee_count
404 San Diego 6
415 San Jose 3
SQL DISTINCT: -
The SQL DISTINCT keyword specifies that only distinct / non-duplicate results are to be
returned. DISTINCT can apply to single columns or to multiple columns.
The DISTINCT keyword can help to understand information. For example, a query
containing DISTINCT could return a non-duplicated list of cities where a company does
business.
The word DISTINCT can be placed in front of a single column name or a number of
column names. When in front of multiple column names, a distinct combination is returned.
The following example a DISTINCT list of region_nbr referenced in the branch table is
returned.
Table: BRANCH
region_nbr
100
200
400
The SQL GROUP BY clause enables aggregate functions for a grouping of information.
For example, it could support subtotaling by region number in a sales table.
The SQL GROUP BY clause is used whenever aggregate functions by group are required.
This is an aid to understanding and analyzing information.
SQL GROUP BY is used as follows. It must follow the FROM and WHERE clauses. The
columns in a SELECT clause must be either group by columns or aggregate function
columns.
______________________________________________________________________
Computer Science Department Advanced SQL
32
Advanced Database System Lab notes
The following example produces a count of branches by region_nbr from the branch table.
Table: BRANCH
region_nbrcount(*)
100 2
200 1
400 2
SQL AGGREGATE: -
The SQL Aggregate Functions are functions that provide mathematical operations. The
functions include:
______________________________________________________________________
Computer Science Department Advanced SQL
33
Advanced Database System Lab notes
The SQL Aggregate Functions are useful when mathematical operations must be performed
on all or a grouping of values.
SQL Aggregate Functions are used as follows. If a grouping of values is needed also
include the GROUP BY clause.
Use a column name or expression as the parameter to the Aggregate Function. The
parameter, '*', represents all rows.
The following example Aggregate Functions are applied to the employee_count of the
branch table. The region_nbr is the level of grouping.
Table: BRANCH
______________________________________________________________________
Computer Science Department Advanced SQL
34
Advanced Database System Lab notes
SQL HAVING: -
The SQL HAVING clause enables conditions at the aggregate level. It is used instead of
the WHERE clause when Aggregate Functions are used.
The HAVING clause is used to SELECT information based aggregate information. For
example, one may want to list sales representatives that have sales totaling over $10,000.
This is very useful for analytical reporting.
______________________________________________________________________
Computer Science Department Advanced SQL
35
Advanced Database System Lab notes
The following example regions from the branch table that have total employee_count
greater than 5.
Table: BRANCH
region_nbrsum(employee_count)
100 16
400 9
The SQL ORDER BY clause controls the sequence of information returned by the
SELECT statement.
Use the SQL ORDER BY clause whenever it is desirable to control the sequence output
through a SELECT clause. It might be used to alphabetize a report or to print the most
import items at the beginning of a report.
______________________________________________________________________
Computer Science Department Advanced SQL
36
Advanced Database System Lab notes
Multiple columns can be included in the ORDER BY clause. The direction of the sort is
controlled by:
The following example displays rows from the branch in region_nbr and branch_nbr
ascending sequence.
Table: BRANCH
region_nbrbranch_nbr branch_name
100 108 New York
100 110 Boston
200 212 Chicago
400 404 San Diego
400 415 San Jose
SQL JOIN: -
______________________________________________________________________
Computer Science Department Advanced SQL
37
Advanced Database System Lab notes
The SQL JOIN clause enables a SELECT statement to access more than one table. The
JOIN clause controls how tables are linked. It is a qualifier of the SQL FROM clause.
Use the SQL JOIN whenever multiple tables must be accessed through a SQL SELECT
statement and no results should be returned if there is not a match between the JOINed
tables.
SQL JOIN is used as follows. The ON clause describes the conditions of the JOIN.
Important! A "cartesian product" can result if there is no relating the tables for the join. A
row would be included for each combination between the two tables so if one table has
1,000 rows and the second table has 2,000 rows then 2,000,000 rows would be returned.
Important! If there are no matches on the JOIN criteria then no rows will be returned. This
is known an "INNER JOIN". Use the "OUTER JOIN" in cases where rows should be
returned when one side of the join is missing.
The following example JOINs the region and branch tables on the region_nbr column.
Table: REGION
region_nbrregion_name
100 East Region
200 Central Region
300 Virtual Region
400 West Region
______________________________________________________________________
Computer Science Department Advanced SQL
38
Advanced Database System Lab notes
Table: BRANCH
Here is the result. Note that the "Virtual Region" is included in the results even though it
has no rows in the branch table. This is the difference between the INNER JOIN and
OUTER JOIN.
The SQL OUTER JOIN clause is a variation of the SQL JOIN clause enables a SELECT
statement to access more than one table. The JOIN clause controls how tables are linked. It
is a qualifier of the SQL FROM clause.
______________________________________________________________________
Computer Science Department Advanced SQL
39
Advanced Database System Lab notes
The OUTER JOIN clause differs from the standard JOIN clause (also known as the INNER
JOIN clause) in that rows are returned even when there are no matches through the JOIN
criteria on the second table.
Use the SQL OUTER JOIN whenever multiple tables must be accessed through a SQL
SELECT statement and results should be returned if there is not a match between the
JOINed tables.
SQL OUTER JOIN is used as follows. The ON clause describes the conditions of the JOIN.
Important! A "cartesian product" can result if there is no relating the tables for the join. A
row would be included for each combination between the two tables so if one table has
1,000 rows and the second table has 2,000 rows then 2,000,000 rows would be returned.
Important! If there are matches on the JOIN criteria then rows will still be returned. This
is known an "OUTER JOIN". Use the "INNER JOIN" in cases where no rows should be
returned when one side of the join is missing.
The following example JOINs the region and branch tables on the region_nbr column.
Table: REGION
region_nbrregion_name
100 East Region
200 Central Region
300 Virtual Region
400 West Region
______________________________________________________________________
Computer Science Department Advanced SQL
40
Advanced Database System Lab notes
Table: BRANCH
Here is the result. Note that the "Virtual Region" is included in the results even though it
has no rows in the branch table. This is the difference between the INNER JOIN and
OUTER JOIN.
It is all about grammar or sentence structure or language rules of SQL Commands that
discussed above.
______________________________________________________________________
Computer Science Department Advanced SQL
41
Advanced Database System Lab notes
______________________________________________________________________
Computer Science Department
42
Advanced SQL