0% found this document useful (0 votes)
8 views42 pages

ADBS

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)
8 views42 pages

ADBS

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/ 42

Advanced Database System Lab notes

Lab Lecture

SQL

The easiest way to manipulate a relational database is to submit Structured


Query Language (SQL) statements to it. It is a simple programming language.
2.1 SQL Basics:

SQL SELECT: -

What is the SQL SELECT Statement?


The SQL SELECT statement is the SQL command that retrieves data from an SQL
database. This operation is also known as a query and is the key to the use of SQL for
analysis and reporting.

Why Use the SQL SELECT Statement?


Anytime you want to retrieve information from a SQL database use the SQL SELECT
statement to request the information.

How to Use SQL SELECT Statement?


The SQL SELECT command is used as follows. The asterisk can be used to SELECT all
columns of a table. SQL SELECT Statement Syntax: -

SELECT <columnlist>
FROM <tablename>

SQL SELECT Statement Example 1

The following example retrieves the columns product_nbr and product_name from all
rows of the product table.

SELECT product_nbr, product_name


FROM product

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

SQL SELECT Statement Example 2

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.

product_nbr product_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

SQL WHERE: -

What is the SQL WHERE clause?

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.

Why Use the SQL WHERE clause?

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.

How To Use the SQL WHERE Clause?

The SQL WHERE clause is used as follows.

SQL WHERE Clause Syntax

<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

Alphanumeric literals are enclosed in single quotes ('XXX').

SQL WHERE Clause Example 1

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

SELECT product_nbr, product_name, product_status_code


FROM product
WHERE product_status_code = 'Active'

Results from the execution of the SQL SELECT statement with the WHERE clause are as
follows:

product_nbr product_name product_status_code


2001 SQL Tool 2.0 Light Active
2002 SQL Tool 2.0 Professional Active
2003 SQL Tool 2.0 Enterprise Active

SQL WHERE Clause Example 2

______________________________________________________________________
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:

customer_nbr customer_name credit_limit_amt credit_balance_amt


200-8889 Sandy Shores 7000.00 2100.00
301-7772 Pat Portabello 1000.00 1020.00
305-9999 Douglas Donovan 1000.00 999.00
400-1234 Edward Engle 2000.00 2000.00
500-1234 Fran Farckle 2000.00 2001.00

SELECT customer_nbr, customer_name, credit_limit_amt, credit_balance_amt


FROM customer
WHERE credit_balance_amt > credit_limit_amt

Results from the execution of the SQL SELECT statement with the WHERE clause are as
follows:

customer_nbr customer_name credit_limit_amt credit_balance_amt


301-7772 Pat Portabello 1000.00 1020.00
500-1234 Fran Farckle 2000.00 2001.00

SQL INSERT: -

What is the SQL INSERT Statement?

The SQL INSERT statement is the SQL command that adds new rows to an SQL table.

Why Use the SQL INSERT Statement?

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.

How To Use the SQL INSERT Statement?

SQL INSERT Statement Syntax:

INSERT INTO <table_name> ( <column_list> )


VALUES (<value_list>)
______________________________________________________________________
Computer Science Department Advanced SQL
4
Advanced Database System Lab notes

SQL INSERT Statement Example 1

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

This INSERT Statement is executed:

INSERT INTO product (product_nbr, product_name)

Results from the execution of the SQL INSERT statement are:

product_nbrproduct_name
1001 SQL Tool Light
1002 SQL Tool Professional
1003 SQL Tool Enterprise
2001 Data Modeling Tool Professional

SQL UPDATE: -

What is the SQL UPDATE Statement?

The SQL UPDATE statement is the SQL command that makes changes to data that exists
in a SQL database.

Why Use the SQL UPDATE Statement?

Anytime you want to change information in a SQL database use the SQL UPDATE
statement to cause the change.

How To Use the SQL UPDATE Statement?

SQL UPDATE Statement Syntax:

______________________________________________________________________
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

The following example updates the product_name to 'SQL Tool UltraLight'


where product_nbr equals '1001'.

Before executing the UPDATE the table contains:

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'

After executing the UPDATE the table contains:

product_nbr product_name
1001 SQL Tool Light
1002 SQL Tool Professional
1003 SQL Tool Enterprise

SQL DELETE: -

What is the SQL DELETE Statement?

The SQL DELETE statement is the SQL command that removes data from an SQL
database.

Why Use the SQL DELETE Statement?

Anytime you want to remove rows from a SQL table use the SQL DELETE statement to
remove the information.

How To Use the SQL DELETE Statement?

SQL DELETE Statement Syntax:

______________________________________________________________________
DELETE
Computer Science FROM <table_name>
Department Advanced SQL
6
WHERE <where_conditions>
Advanced Database System Lab notes

SQL DELETE Statement Example

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

2.2 SQL Administration:

SQL CREATE DATABASE: -

What is the SQL CREATE DATABASE Statement?

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.

Why Use the SQL CREATE DATABASE Statement?

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.

How To Use the SQL CREATE DATABASE Statement?


______________________________________________________________________
Computer Science Department Advanced SQL
7
Advanced Database System Lab notes

SQL CREATE DATABASE Statement Syntax:

CREATE DATABASE <database_name>

SQL CREATE DATABASE Statement Example

The following example creates a new database named CUSTOMER_DB.

CREATE DATABASE customer_db

SQL DROP DATABASE: -

What is the SQL DROP DATABASE Statement?

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.

Why Use the SQL DROP DATABASE Statement?

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.

How To Use the SQL DROP DATABASE Statement

SQL DROP DATABASE Statement Syntax

DROP DATABASE <database_name>

SQL DROP DATABASE Statement Example

The following example drops an existing database named CUSTOMER_DB_DEV.

DROP DATABASE customer_db_dev

SQL CREATE TABLE: -

______________________________________________________________________
Computer Science Department Advanced SQL
8
Advanced Database System Lab notes

What is the SQL CREATE TABLE Statement?

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.

Why Use the SQL CREATE TABLE Statement?

Anytime you want to add a new table to the database you would use the SQL CREATE
TABLE statement.

How To Use the SQL CREATE TABLE Statement

SQL CREATE TABLE Statement Syntax

CREATE TABLE <table_name> (


<column_name1> <datatype1> <constraint1>
<column_name2> <datatype2> <constraint2>
<constraint-list>
)
T
he number of characters that can make up SQL table names and column names 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 table can not duplicate
the name of an existing table and should not be the same as a SQL reserved word. The
underscore character can be used to improve readability. The same column name can not be
repeated within a table. List elements are separated by commas.

Here are some example datatypes:

SQL Datatype Description


integer(size)
int(size)
Integers
smallint(size)
tinyint(size)
decimal(size,decimals)
Numbers with decimals
numeric(size,decimals)

______________________________________________________________________
Computer Science Department Advanced SQL
9
Advanced Database System Lab notes

char(size) Fixed length character string


varchar(size) Variable length character string
date A date in yyyymmdd format

SQL CREATE TABLE Statement Example

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.

This SQL CREATE TABLE Statement is executed:

CREATE TABLE product ( product_nbr int NOT NULL,


product_name varchar(40) NOT NULL,
product_status_code char(10) NOT NULL,
start_date date NULL,
end_date date NULL,
raw_material_cost decimal(12,2) NULL,
primary key (product_nbr)
)

SQL ALTER TABLE: -

What is the SQL ALTER TABLE Statement?


The SQL ALTER TABLE statement is the SQL command that makes changes to the
definition of an SQL table.

Why Use the SQL ALTER TABLE Statement?

Anytime you want to change the definition of an SQL table. For example, you could:

 Add a column to a table


 Change the definition of an existing column in a table
 Drop a column from a table

How To Use the SQL ALTER TABLE Statement

SQL ALTER TABLE Statement Syntax

ALTER TABLE <table_name>


ADD <column_name1> <datatype1> <constraint1>
______________________________________________________________________
Computer Science Department Advanced SQL
10
ALTER TABLE <table_name>
ALTER COLUMN <column_name1> <datatype1> <constraint1>
Advanced Database System Lab notes

SQL ALTER TABLE Statement Example 1 - Add a Column

The following example adds a new column into the person table. Before the operation
takes place the following columns exists in the table:

Column Name Datatype Nullability


person_id INT NOT NULL
person_name VARCHAR(20) NOT NULL
gender_code CHAR(1) NULL
line_1_addr VARCHAR(50) NULL
line_2_addr VARCHAR(50) NULL
apartment_nbr VARCHAR(50) NULL
city_name VARCHAR(50) NOT NULL
state_code CHAR(2) NOT NULL
zip_code CHAR(9) NOT NULL

This ALTER TABLE Statement is executed:

ALTER TABLE PERSON


ADD marital_status_code CHAR(1) NULL

Results from the execution of the SQL ALTER TABLE statement are:

Column Name Datatype Nullability


person_id INT NOT NULL
person_name VARCHAR(20) NOT NULL
gender_code CHAR(1) NULL
line_1_addr VARCHAR(50) NULL
line_2_addr VARCHAR(50) NULL
apartment_nbr VARCHAR(50) NULL
city_name VARCHAR(50) NOT NULL
state_code CHAR(2) NOT NULL
zip_code CHAR(9) NOT NULL
marital_status_code CHAR(1) NULL

______________________________________________________________________
Computer Science Department Advanced SQL
11
Advanced Database System Lab notes

SQL ALTER TABLE Statement Example 2 - Alter a Column Datatype

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:

Column Name Datatype Nullability


person_id INT NOT NULL
person_name VARCHAR(20) NOT NULL
gender_code CHAR(1) NULL
line_1_addr VARCHAR(50) NULL
line_2_addr VARCHAR(50) NULL
apartment_nbr VARCHAR(50) NULL
city_name VARCHAR(50) NOT NULL
state_code CHAR(2) NOT NULL
zip_code CHAR(9) NOT NULL

This ALTER TABLE Statement is executed:

ALTER TABLE PERSON


ALTER COLUMN person_name VARCHAR(50) NOT NULL

Results from the execution of the SQL ALTER TABLE statement are:

Column Name Datatype Nullability


person_id INT NOT NULL
person_name VARCHAR(50) NOT NULL
gender_code CHAR(1) NULL
line_1_addr VARCHAR(50) NULL
line_2_addr VARCHAR(50) NULL
apartment_nbr VARCHAR(50) NULL
city_name VARCHAR(50) NOT NULL
state_code CHAR(2) NOT NULL
zip_code CHAR(9) NOT NULL
marital_status_code CHAR(1) NULL

SQL ALTER TABLE Statement Example 3 - Drop a column

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

Column Name Datatype Nullability


person_id INT NOT NULL
person_name VARCHAR(50) NOT NULL
gender_code CHAR(1) NULL
line_1_addr VARCHAR(50) NULL
line_2_addr VARCHAR(50) NULL
apartment_nbr VARCHAR(50) NULL
city_name VARCHAR(50) NOT NULL
state_code CHAR(2) NOT NULL
zip_code CHAR(9) NOT NULL

This ALTER TABLE Statement is executed

ALTER TABLE dbo.PERSON


DROP COLUMN apartment_nbr

Results from the execution of the SQL ALTER TABLE statement are:

Column Name Datatype Nullability


person_id INT NOT NULL
person_name VARCHAR(50) NOT NULL
gender_code CHAR(1) NULL
line_1_addr VARCHAR(50) NULL
line_2_addr VARCHAR(50) NULL
city_name VARCHAR(50) NOT NULL
state_code CHAR(2) NOT NULL
zip_code CHAR(9) NOT NULL

SQL DROP TABLE: -

What is the SQL DROP TABLE Statement?

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.

Dropping tables have the benefit of:

 reducing confusion
 reducing disk space and resource requirements

BEWARE! Dropping a table results in losing data.

How To Use the SQL DROP TABLE Statement

SQL DROP TABLE Statement Syntax

DROP <table_name> ( <column_list>

Before executing a DROP statement you may need or want to:

 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.

SQL DROP TABLE Statement Example

The following example drops an existing table named PERSON.

DROP TABLE person

SQL CREATE INDEX: -

What is the SQL CREATE INDEX Statement?

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

Why Use the SQL CREATE INDEX Statement?

SQL indexes are used because they can provide the following benefits / functions:

 Rapid access of information


 Efficient access of information
 Enforcement of uniqueness constraints

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.

How To Use the SQL CREATE INDEX Statement

SQL CREATE INDEX Statement Syntax

CREATE INDEX <index_type> <index_name> ON <table_name> (


<column_name1> <index_order>,
<column_name2> <index_order>,
)

CREATE UNIQUE INDEX <index_type> <index_name> ON


<table_name> (
<column_name1> <index_order>,
<column_name2> <index_order>,
)

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.

SQL CREATE INDEX Statement Example 1 - Rapid Access

The following example creates an non-unique index named IDX_PERSON_NAME on


table PERSON with columns named person_name and gender_code in ascending
sequence..

Here are the contents of the table:

______________________________________________________________________
Computer Science Department Advanced SQL
15
Advanced Database System Lab notes

Column Name Datatype Nullability


person_id INT NOT NULL
person_name VARCHAR(20) NOT NULL
social_security_nbr CHAR(9) NULL
gender_code CHAR(1) NULL
line_1_addr VARCHAR(50) NULL
city_name VARCHAR(50) NOT NULL
state_code CHAR(2) NOT NULL
zip_code CHAR(9) NOT NULL

This SQL CREATE VIEW Statement is executed:

CREATE INDEX IDX_PERSON_NAME ON PERSON


(person_name ASC, gender_code ASC)

SQL CREATE INDEX Statement Example 2 - Enforce Uniqueness

The following example creates a unique index named IDX_PERSON_SSN on table


PERSON with the column named social_security_nnbr. This assures that two rows can
not be added to the PERSON table with the same social security number.

This SQL CREATE TABLE Statement is executed:

CREATE UNIQUE INDEX IDX_PERSON_SSN ON PERSON


(social_security_nbr ASC)

SQL DROP INDEX: -

What is the SQL DROP INDEX Statement?

The SQL DROP INDEX statement is the SQL command that removes an entire SQL index.

Why Use the SQL DROP INDEX Statement?

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.

How To Use the SQL DROP INDEX Statement

SQL DROP INDEX Statement Syntax

______________________________________________________________________
Computer Science Department Advanced SQL
16
Advanced Database System Lab notes

DROP INDEX <table_name>.<index_name>

SQL DROP INDEX Statement Example

The following example drops an index named IDX_PERSON_NAME on a table named


PERSON.

DROP INDEX PERSON.IDX_PERSON_NAME

SQL ADD FOREIGN KEY: -

What is the SQL ADD FOREIGN KEY Clause?

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:

Column Name Datatype Constraint


sales_order_line_id INT NOT NULL - PRIMARY KEY
sales_order_id INT NOT NULL
line_nbr INT NOT NULL
product_id INT NOT NULL
line_order_qty INT NOT NULL
line_ship_qty INT NOT NULL
line_status_code CHAR(10) NOT NULL

PRODUCT Table:

Column Name Datatype Constraint


product_id INT NOT NULL - PRIMARY KEY
product_nbr VARCHAR(20) NOT NULL
product_name VARCHAR(100) NOT NULL
inventory_qty INT NOT NULL
______________________________________________________________________
Computer Science Department Advanced SQL
17
Advanced Database System Lab notes

product_status_code CHAR(10) NOT NULL

A foreign key is placed on the product_id column of the SALES_ORDER_LINE table to


the primary key of the PRODUCT table. This establishes "Referential Integrity", RI for
short, that requires a row to exist in the PRODUCT table that matches the row in the
SALES_ORDER_LINE table.

The SQL CREATE FOREIGN KEY clause is the SQL capability that adds a new foreign
key an existing table to an SQL database.

Why Use the SQL ADD FOREIGN KEY Clause?

SQL foreign keys are used because they can provide the following benefits / functions:

 Improve data quality by enforcing Referential Integrity (RI) rules


 Enable understanding of data structures

How To Use the SQL ADD FOREIGN KEY Clause

SQL CREATE FOREIGN KEY Clause Syntax

ALTER TABLE <table_name>


ADD <constraint_name> FOREIGN KEY
(<column_name1> ,
<column_name2> )
REFERENCES <table_name>
(<column_name1> ,
<column_name2>)

SQL ADD FOREIGN KEY Clause Example

The following example creates a foreign key on column product_id on table


SALES_ORDER_LINE with column product_id which is the primary key of table
product.

This SQL ADD FOREIGN KEY class is executed:

ALTER TABLE SALES_ORDER_LINE


ADD CONSTRAINT FK_SALES_ORDER_LINE_PRODUCT FOREIGN KEY
(product_id)
REFERENCES PRODUCT
(product_id
______________________________________________________________________
Computer Science Department Advanced SQL
18
Advanced Database System Lab notes

SQL DROP FOREIGN KEY: -

What is the SQL DROP FOREIGN KEY Clause?

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.

Why Use the SQL DROP FOREIGN KEY Clause?

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.

How To Use the SQL DROP FOREIGN KEY Clause

SQL DROP FOREIGN KEY Clause Syntax

ALTER TABLE <table_name>


DROP FOREIGN KEY <foreignkey_name>

SQL DROP FOREIGN KEY Statement Example

The following example drops a foreign key named

FK_SALES_ORDER_LINE_PRODUCT on a table named SALES_ORDER_LINE.

ALTER TABLE SALES_ORDER_LINE


DROP FOREIGN KEY FK_SALES_ORDER_LINE_PRODUCT

SQL CREATE VIEW: -

What is the SQL CREATE VIEW Statement?

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.

Why Use the SQL CREATE VIEW Statement?

SQL views are used because they can provide the following benefits / functions:

 Database queries are simplified


 Database complexity is hidden
 Flexibility is increased - queries of views may not change when underlying
tables chagne
 Security is increased - sensitive information can be excluded from a view

How To Use the SQL CREATE VIEW Statement

SQL CREATE VIEW Statement Syntax

CREATE VIEW <view_name> (


<column_name1>,
<column_name2>
) AS
<sql_select_statement>

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.

SQL CREATE VIEW Statement Example - Data Filtering

The following example creates a view named V_TOP_CUSTOMER on table


CUSTOMER with the following columns:

 customer_id
 customer_name
 ytd_sales_amt

______________________________________________________________________
Computer Science Department Advanced SQL
20
Advanced Database System Lab notes

 zip_code

Here are the contents of the table:

Column Name Datatype Nullability


customer_id INT NOT NULL
customer_name VARCHAR(20) NOT NULL
ytd_sales_amt MONEY NOT NULL
line_1_addr VARCHAR(50) NULL
city_name VARCHAR(50) NOT NULL
state_code CHAR(2) NOT NULL
zip_code CHAR(9) NOT NULL

This SQL CREATE VIEW Statement is executed:

CREATE VIEW V_TOP_CUSTOMER (


customer_id,
customer_name,
ytd_sales_amt,
zip_code)
AS SELECT customer_id,
customer_name,
ytd_sales_amt,
zip_code
FROM CUSTOMER
WHERE ytd_sales_amt > 1200.00

SQL DROP VIEW: -

What is the SQL DROP VIEW Statement?

The SQL DROP VIEW statement is the SQL command that removes an entire SQL view.

Why Use the SQL DROP VIEW Statement?

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.

How To Use the SQL DROP VIEW Statement

SQL DROP VIEW Statement Syntax

______________________________________________________________________
Computer Science Department Advanced SQL
21
Advanced Database System Lab notes

DROP VIEW <view_name>

SQL DROP VIEW Statement Example

The following example drops a view named V_PERSON.

DROP VIEW V_PERSON

2.3 SQL Advanced: -

SQL CONCAT: -

What is SQL Concatenation?

Concatenation is the process of combining data strings.

For example, the concatenation of 'John', ' ', 'W', '. ' and 'Smith' is

'John W. Smith'

Also, the concatenation of '212', '-', '555', '-' and '1234' is

'212-555-1234'

Why Use SQL Concatenation?

Concatenation can result in more readable output while maintaining data in separate
columns for greater flexibility.

How To Use SQL Concatenation

The means of achieving concatenation differs by database type. for example:

 MySQL uses the CONCAT() function


 Oracle uses the CONCAT() function and the || operator
 SQL Server uses the + operator

More than 2 strings can be combined through concatenation. Numbers must be converted
to strings before concatenation.

SQL Concatenation Syntax

______________________________________________________________________
Computer Science Department Advanced SQL
22
Advanced Database System Lab notes

<value_1> + <value_2>

SQL Concatenation Example

The following example concatenates the column branch_name with column region_name
along with spaces and parens for readability.

Here are the contents of the tables:

Table: REGION

region_nbrregion_name
100 East Region
200 Central Region
300 Virtual Region
400 West Region

Table: BRANCH

branch_nbrbranch_name region_nbr employee_count


108 New York 100 10
110 Boston 100 6
212 Chicago 200 5
404 San Diego 400 6
415 San Jose 400 3

This SQL Statement with concatenation is executed:

SELECT `branch`.branch_name , ' (' , `region`.region_name , ')'


FROM “dbName”.region
JOIN “dbName”.branch
ON branch.region_nbr = region.region_nbr
ORDER BY region.region_nbr

Here is the result.

branch_name (region_name)
New York (East Region)

______________________________________________________________________
Computer Science Department Advanced SQL
23
Advanced Database System Lab notes

Boston (East Region)


Chicago (Central Region)
San Diego (West Region)
San Jose (West Region)

SUBSTRING: -

What is SQL SUBSTRING?

The SQL Substring feature is a function that enables parts of strings to be accessed.

For example, the function SUBSTRING('212-555-1234', 9 , 4) returns:

'1234'

It returns 4 characters starting in position 9.

Why Use SQL SUBSTRING?

Substring is useful when accessing a column that consists of meaningful subcomponents,


such as a telephone number that contains area code, prefix and phone number body.

How To Use SQL SUBSTRING

SQL SUBSTRING Syntax

SELECT SUBSTRING(<column_name>, position, length)


FROM <table_name>

SQL SUBSTRING Example

This example returns three characters of the region_name column starting in position 2.

Here are the contents of the table:

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

This SQL Statement with SUBSTRING is executed:

SELECT region_name, SUBSTRING (region_name, 2, 5) as substring_name


FROM dbo.region
ORDER BY 1

Here is the result.

region_name substring_name
East Region ast
Central Region ent
Virtual Region irt
West Region est

SQL TRIM: -

What is SQL TRIM?

The SQL Trim feature is are functions (LTRIM and RTRIM) that remove leading and
trailing blanks from a string.

For example, the function LTRIM(' Minnesota') returns:

'Minnesota'

Why Use SQL TRIM?

The SQL Trim functions (LTRIM and RTRIM) are useful in cleansing data that contains
leading and trailing blanks.

How To Use SQL TRIM

SQL TRIM Syntax

SELECT LTRIM(<value_1>)

SELECT RTRIM(<value_1>)

SQL TRIM Example

______________________________________________________________________
Computer Science Department Advanced SQL
25
Advanced Database System Lab notes

The LTRIM function removes the leading blanks in the string ' Bob'.

This SQL Statement with LTRIM is executed:

SELECT LTRIM(' Bob ') as trimmed_string

Here is the result.

trimmed_string
Bob

SQL AND & OR: -

What is SQL AND & OR?

The SQL AND & OR operators support compound conditions in the SQL WHERE clause.

Why Use SQL AND & OR?

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:

SELECT customer_nbr, customer_name, credit_limit_amt, credit_balance_amt


FROM CUSTOMER
WHERE credit_hold_ind = 'Y'
AND credit_balance_amt > credit_limit_amt

How To Use SQL AND & OR

SQL AND & OR are placed between conditions to create compound conditions.
Parenthesis can be used to group conditions.

SQL AND & OR Syntax

SELECT <column_list>
FROM <table_name>
WHERE <condition_1>
AND|OR <condition_2>

______________________________________________________________________
Computer Science Department Advanced SQL
26
Advanced Database System Lab notes

SQL AND & OR Example

The following example selects a list of rows from the branch table that have an
employee_count less than 4 or greater than 6.

Here are the contents of the table:

Table: BRANCH

branch_nbrbranch_name region_nbr employee_count


108 New York 100 10
110 Boston 100 6
212 Chicago 200 5
404 San Diego 400 6
415 San Jose 400 3

This SQL Statement with AND & OR is executed:

SELECT branch_nbr, branch_name, employee_count


FROM branch
WHERE employee_count < 4
OR employee_count > 6

Here is the result.

branch_nbrbranch_name employee_count
108 New York 10
415 San Jose 3

SQL IN: -

What is SQL IN?

The SQL IN operator enables a comparison to a list of values or to the results of a


SUBSELECT.

Why Use SQL IN?

The SQL IN operator is a clean way to check for inclusion in lists without creating a series
of OR clauses.

How To Use SQL IN

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.

Here are the contents of the table:

Table: BRANCH

branch_nbrbranch_name region_nbr employee_count


108 New York 100 10
110 Boston 100 6
212 Chicago 200 5
404 San Diego 400 6
415 San Jose 400 3

This SQL Statement with IN is executed:

SELECT branch_nbr, branch_name, region_nbr


FROM branch
WHERE region_nbr IN (200, 400)

Here is the result.

branch_nbrbranch_name region_nbr
212 Chicago 200
404 San Diego 400
415 San Jose 400

SQL BETWEEN: -

What is SQL BETWEEN?

The SQL BETWEEN operator enables a comparison to a range of values.

Why Use SQL BETWEEN?


______________________________________________________________________
Computer Science Department Advanced SQL
28
Advanced Database System Lab notes

The SQL BETWEEN operator is a clean way to check for inclusion in a range without
requiring an AND operator.

How To Use SQL BETWEEN

SQL BETWEEN Syntax

SELECT <column_list>
FROM <table_name>
WHERE <column_name> BETWEEN
<lower_value> AND <higher_value>

SQL BETWEEN Example

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 region_nbr employee_count


108 New York 100 10
110 Boston 100 6
212 Chicago 200 5
404 San Diego 400 6
415 San Jose 400 3

This SQL Statement with BETWEEN is executed:

SELECT branch_nbr, branch_name, employee_count


FROM branch
WHERE employee_count BETWEEN
4 AND 7

Here is the result.

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

What is SQL LIKE?

The SQL LIKE operator enables a comparison to a part of a string using the % wild card
character.

Why Use SQL LIKE?

The SQL LIKE operator is a powerful way to check for matching strings. It is often used
for interactive display of lists.

How To Use SQL LIKE

SQL LIKE Syntax

SELECT <column_list>
FROM <table_name>
WHERE <column_name> LIKE <like_condition>
The <like_condition> supports the following patterns:

 'ABC%' - where a string begins with the letters 'ABC'


 '%XYZ' - where a string ends with the 'XYZ'
 '%TUV%' - where the string contais 'TUV' anywhere

SQL LIKE Example

The following example lists rows from the branch table where branch_name begins with
the leading characters 'San'.

Here are the contents of the table:

Table: BRANCH

branch_nbrbranch_name region_nbr employee_count


108 New York 100 10
110 Boston 100 6
212 Chicago 200 5
404 San Diego 400 6
415 San Jose 400 3

This SQL Statement with LIKE is executed:

SELECT branch_nbr, branch_name, employee_count


FROM branch
WHERE branch_name LIKE 'San%'

______________________________________________________________________
Computer Science Department Advanced SQL
30
Advanced Database System Lab notes

Here is the result.

branch_nbrbranch_name employee_count
404 San Diego 6
415 San Jose 3

SQL DISTINCT: -

What is 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.

Why Use SQL DISTINCT?

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.

How To Use SQL DISTINCT

SQL DISTINCT Syntax

SELECT DISTINCT <column_name>


FROM <table_name>

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.

SQL DISTINCT Example

The following example a DISTINCT list of region_nbr referenced in the branch table is
returned.

Here are the contents of the table:

Table: BRANCH

branch_nbrbranch_name region_nbr employee_count


108 New York 100 10
110 Boston 100 6
212 Chicago 200 5
______________________________________________________________________
Computer Science Department Advanced SQL
31
Advanced Database System Lab notes

404 San Diego 400 6


415 San Jose 400 3

This SQL Statement with DISTINCT is executed:

SELECT DISTINCT region_nbr


FROM branch
ORDER BY region_nbr

Here is the result.

region_nbr
100
200
400

SQL GROUP BY: -

What is SQL GROUP BY?

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.

Why Use SQL GROUP BY?

The SQL GROUP BY clause is used whenever aggregate functions by group are required.
This is an aid to understanding and analyzing information.

How To Use SQL GROUP BY

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.

SQL GROUP BY Syntax

SELECT <column_name1>, <column_name2> <aggregate_function>


FROM <table_name>
GROUP BY <column_name1>, <column_name2>

SQL GROUP BY Example

______________________________________________________________________
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.

Here are the contents of the table:

Table: BRANCH

branch_nbrbranch_name region_nbr employee_count


108 New York 100 10
110 Boston 100 6
212 Chicago 200 5
404 San Diego 400 6
415 San Jose 400 3

This SQL Statement with GROUP BY is executed:

SELECT region_nbr, count(*)


FROM branch
GROUP BY region_nbr
ORDER BY region_nbr

Here is the result.

region_nbrcount(*)
100 2
200 1
400 2

SQL AGGREGATE: -

What are SQL Aggregate Functions?

The SQL Aggregate Functions are functions that provide mathematical operations. The
functions include:

 count() - counts a number of rows


 sum() - compute sum
 avg() - compute average
 min() - compute minimum
 max() - compute maximum

Why Use SQL Aggregate Functions?

______________________________________________________________________
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.

How To Use SQL Aggregate Functions

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.

SQL Aggregate Functions Syntax

SELECT <column_name1>, <column_name2> <aggregate_function(s)>


FROM <table_name>
GROUP BY <column_name1>, <column_name2>

SQL Aggregate Functions Example

The following example Aggregate Functions are applied to the employee_count of the
branch table. The region_nbr is the level of grouping.

Here are the contents of the table:

Table: BRANCH

branch_nbrbranch_name region_nbr employee_count


108 New York 100 10
110 Boston 100 6
212 Chicago 200 5
404 San Diego 400 6
415 San Jose 400 3

This SQL Statement with aggregate functions is executed:

SELECT region_nbr, count(branch_nbr), sum(employee_count),


min(employee_count),
max(employee_count), avg(employee_count)
FROM dbo.branch
GROUP BY region_nbr
ORDER BY region_nbr

______________________________________________________________________
Computer Science Department Advanced SQL
34
Advanced Database System Lab notes

Here is the result.

count sum min max avg


region_n
(branch_nb (employee_cou (employee_cou (employee_cou (employee_cou
br
r) nt) nt) nt) nt)
100 2 16 6 10 8
200 1 5 5 5 5
400 2 9 3 6 4

SQL HAVING: -

What is 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.

Why Use SQL HAVING?

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.

How To Use SQL HAVING

SQL HAVING Syntax

SELECT <column_name1>, <column_nam SELECT <column_name1>,


<column_name2> <aggregate_function>
FROM <table_name>
GROUP BY <column_name1>, <column_name2>
HAVING <having_condition>e2> <aggregate_function>
FROM <table_name>
GROUP BY <column_name1>, <column_name2>
HAVING <having_condition>

SQL HAVING Example

______________________________________________________________________
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.

Here are the contents of the table:

Table: BRANCH

branch_nbrbranch_name region_nbr employee_count


108 New York 100 10
110 Boston 100 6
212 Chicago 200 5
404 San Diego 400 6
415 San Jose 400 3

This SQL Statement with HAVING is executed:

SELECT region_nbr, sum(employee_count)


FROM branch
GROUP BY region_nbr
HAVING sum(employee_count) > 5
ORDER BY region_nbr

Here is the result.

region_nbrsum(employee_count)
100 16
400 9

SQL ORDER BY: -

What is SQL ORDER BY?

The SQL ORDER BY clause controls the sequence of information returned by the
SELECT statement.

Why Use SQL ORDER BY?

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.

How To Use SQL ORDER BY

SQL ORDER BY Syntax

______________________________________________________________________
Computer Science Department Advanced SQL
36
Advanced Database System Lab notes

SELECT <column_name1>, <column_name2>


FROM <table_name>
ORDER BY <column_name1>[ASC|DESC], <column_name2>[ASC|DESC]

Multiple columns can be included in the ORDER BY clause. The direction of the sort is
controlled by:

 ASC - ascending sequence


 DESC - descending sequence

SQL ORDER BY Example

The following example displays rows from the branch in region_nbr and branch_nbr
ascending sequence.

Here are the contents of the table:

Table: BRANCH

branch_nbrbranch_name region_nbr employee_count


108 New York 100 10
110 Boston 100 6
212 Chicago 200 5
404 San Diego 400 6
415 San Jose 400 3

This SQL Statement with ORDER BY is executed:

SELECT region_nbr, branch_nbr, branch_name


FROM branch
ORDER BY region_nbr ASC, branch_nbr ASC

Here is the result.

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

What is SQL JOIN?

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.

Why Use SQL JOIN?

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.

How To Use SQL JOIN

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.

SQL JOIN Syntax

SELECT <column_name1>, <column_name2> <aggregate_function>


FROM <table_name>
JOIN <table_name> ON <join_conditions>

SQL JOIN Example

The following example JOINs the region and branch tables on the region_nbr column.

Here are the contents of the tables:

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

branch_nbrbranch_name region_nbr employee_count


108 New York 100 10
110 Boston 100 6
212 Chicago 200 5
404 San Diego 400 6
415 San Jose 400 3

This SQL Statement with JOIN is executed:

SELECT region.region_nbr, region.region_name, branch.branch_nbr,


branch.branch_name
FROM dbo.region
JOIN dbo.branch
ON branch.region_nbr = region.region_nbr
ORDER BY region.region_nbr

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.

region_nbrregion_name branch_nbr branch_name


100 East Region 108 New York
100 East Region 110 Boston
200 Central Region 212 Chicago
400 West Region 404 San Diego
400 West Region 415 San Jose

SQL OUTER JOIN:-

What is SQL 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.

Why Use SQL OUTER JOIN?

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.

How To Use SQL OUTER JOIN

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.

SQL OUTER JOIN Syntax

SELECT <column_name1>, <column_name2> <aggregate_function>


FROM <table_name>
LEFT OUTER JOIN <table_name> ON <join_conditions>

SQL OUTER JOIN Example

The following example JOINs the region and branch tables on the region_nbr column.

Here are the contents of the tables:

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

branch_nbrbranch_name region_nbr employee_count


108 New York 100 10
110 Boston 100 6
212 Chicago 200 5
404 San Diego 400 6
415 San Jose 400 3

This SQL Statement with OUTER JOIN is executed:

SELECT region.region_nbr, region.region_name, branch.branch_nbr,


branch.branch_name
FROM dbo.region
LEFT OUTER JOIN dbo.branch
ON branch.region_nbr = region.region_nbr
ORDER BY region.region_nbr

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.

region_nbrregion_name branch_nbr branch_name


100 East Region 108 New York
100 East Region 110 Boston
200 Central Region 212 Chicago
300 Virtual Region NULL NULL
400 West Region 404 San Diego
400 West Region 415 San Jose

2.4 SQL Syntax: -

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

You might also like