0% found this document useful (0 votes)
81 views

What Is SQL?

SQL is a standard language for accessing and manipulating databases that allows users to execute queries against a database to retrieve, insert, update, and delete data. Key statements in SQL include SELECT to retrieve data, CREATE TABLE to define a table structure, INSERT to add data to a table, UPDATE to modify data in a table, and DELETE to remove data from a table. SQL is an ANSI standard but different database systems may have their own proprietary extensions in addition to the standard.

Uploaded by

Subhankar Dutta
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
81 views

What Is SQL?

SQL is a standard language for accessing and manipulating databases that allows users to execute queries against a database to retrieve, insert, update, and delete data. Key statements in SQL include SELECT to retrieve data, CREATE TABLE to define a table structure, INSERT to add data to a table, UPDATE to modify data in a table, and DELETE to remove data from a table. SQL is an ANSI standard but different database systems may have their own proprietary extensions in addition to the standard.

Uploaded by

Subhankar Dutta
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 37

What is SQL?

 SQL stands for Structured Query Language

 SQL allows you to access a database

 SQL is an ANSI standard computer language

 SQL can execute queries against a database

 SQL can retrieve data from a database

 SQL can insert new records in a database

 SQL can delete records from a database

 SQL can update records in a database

 SQL is easy to learn

SQL Syntax
Statement Syntax
AND / OR SELECT column_name(s)
FROM table_name
WHERE condition
AND|OR condition
ALTER TABLE (add column) ALTER TABLE table_name
ADD column_name datatype
ALTER TABLE (drop column) ALTER TABLE table_name
DROP COLUMN column_name
AS (alias for column) SELECT column_name AS column_alias
FROM table_name
AS (alias for table) SELECT column_name
FROM table_name AS table_alias
BETWEEN SELECT column_name(s)
FROM table_name
WHERE column_name
BETWEEN value1 AND value2
CREATE DATABASE CREATE DATABASE database_name
CREATE INDEX CREATE INDEX index_name
ON table_name (column_name)
CREATE TABLE CREATE TABLE table_name
(
column_name1 data_type,
column_name2 data_type,
.......
)
CREATE UNIQUE INDEX CREATE UNIQUE INDEX index_name
ON table_name (column_name)
CREATE VIEW CREATE VIEW view_name AS
SELECT column_name(s)
FROM table_name
WHERE condition
DELETE FROM DELETE FROM table_name
(Note: Deletes the entire table!!)
or

DELETE FROM table_name


WHERE condition
DROP DATABASE DROP DATABASE database_name
DROP INDEX DROP INDEX table_name.index_name
DROP TABLE DROP TABLE table_name
GROUP BY SELECT column_name1,SUM(column_name2)
FROM table_name
Select Statement
SELECT "column_name" FROM "table_name"

Distinct
SELECT DISTINCT "column_name"
FROM "table_name"

Where
SELECT "column_name"
FROM "table_name"
WHERE "condition"

And/Or
SELECT "column_name"
FROM "table_name"
WHERE "simple condition"
{[AND|OR] "simple condition"}+

In
SELECT "column_name"
FROM "table_name"
WHERE "column_name" IN ('value1', 'value2', ...)

Between
SELECT "column_name"
FROM "table_name"
WHERE "column_name" BETWEEN 'value1' AND 'value2'

Like
SELECT "column_name"
FROM "table_name"
WHERE "column_name" LIKE {PATTERN}

Order By
SELECT "column_name"
FROM "table_name"
[WHERE "condition"]
ORDER BY "column_name" [ASC, DESC]

Count
SELECT COUNT("column_name")
FROM "table_name"

Group By
SELECT "column_name1", SUM("column_name2")
FROM "table_name"
GROUP BY "column_name1"

Having
SELECT "column_name1", SUM("column_name2")
FROM "table_name"
GROUP BY "column_name1"
HAVING (arithematic function condition)

Create Table Statement


CREATE TABLE "table_name"
("column 1" "data_type_for_column_1",
"column 2" "data_type_for_column_2",
... )

Drop Table Statement


DROP TABLE "table_name"

Truncate Table Statement


TRUNCATE TABLE "table_name"

Insert Into Statement


INSERT INTO "table_name" ("column1", "column2", ...)
VALUES ("value1", "value2", ...)

Update Statement
UPDATE "table_name"
SET "column_1" = [new value]
WHERE {condition}

Delete From Statement


DELETE FROM "table_name"
WHERE {condition}

SQL is a Standard - BUT....


SQL is an ANSI (American National Standards Institute) standard computer language for accessing and manipulating
database systems. SQL statements are used to retrieve and update data in a database. SQL works with database programs like
MS Access, DB2, Informix, MS SQL Server, Oracle, Sybase, etc.

Unfortunately, there are many different versions of the SQL language, but to be in compliance with the ANSI standard, they
must support the same major keywords in a similar manner (such as SELECT, UPDATE, DELETE, INSERT, WHERE, and
others).

Note: Most of the SQL database programs also have their own proprietary extensions in addition to the SQL standard!

SQL Database Tables


A database most often contains one or more tables. Each table is identified by a name (e.g. "Customers" or "Orders"). Tables
contain records (rows) with data.

Below is an example of a table called "Persons":


LastName FirstName Address City
Hansen Ola Timoteivn 10 Sandnes
Svendson Tove Borgvn 23 Sandnes
Pettersen Kari Storgt 20 Stavanger
The table above contains three records (one for each person) and four columns (LastName, FirstName, Address, and City).

SQL Queries
With SQL, we can query a database and have a result set returned.

A query like this:


SELECT LastName FROM Persons
Gives a result set like this:
LastName
Hansen
Svendson
Pettersen
Note: Some database systems require a semicolon at the end of the SQL statement. We
don't use the semicolon in our tutorials.

SQL Data Definition Language (DDL)


The Data Definition Language (DDL) part of SQL permits database tables to be created or deleted. We can also define
indexes (keys), specify links between tables, and impose constraints between database tables.

The most important DDL statements in SQL are:

 CREATE TABLE - creates a new database table

 ALTER TABLE - alters (changes) a database table

 DROP TABLE - deletes a database table

 CREATE INDEX - creates an index (search key)

 DROP INDEX - deletes an index

CREATE TABLE
Tables are the basic structure where data is stored in the database. Given that in most cases,
there is no way for the database vendor to know ahead of time what your data storage needs are,
chances are that you will need to create tables in the database yourself. Many database tools
allow you to create tables without writing SQL, but given that tables are the container of all the
data, it is important to include the CREATE TABLE syntax in this tutorial.

Before we dive into the SQL syntax for CREATE TABLE, it is a good idea to understand what
goes into a table. Tables are divided into rows and columns. Each row represents one piece of
data, and each column can be thought of as representing a component of that piece of data. So,
for example, if we have a table for recording customer information, then the columns may include
information such as First Name, Last Name, Address, City, Country, Birth Date, and so on. As a
result, when we specify a table, we include the column headers and the data types for that
particular column.

So what are data types? Typically, data comes in a variety of forms. It could be an integer (such
as 1), a real number (such as 0.55), a string (such as 'sql'), a date/time expression (such as
'2000-JAN-25 03:22:22'), or even in binary format. When we specify a table, we need to specify
the data type associated with each column (i.e., we will specify that 'First Name' is of type char
(50) - meaning it is a string with 50 characters). One thing to note is that different relational
databases allow for different data types, so it is wise to consult with a database-specific reference
first.

The SQL syntax for CREATE TABLE is

CREATE TABLE "table_name"


("column 1" "data_type_for_column_1",
"column 2" "data_type_for_column_2",
... )
The data type specifies what type of data the column can hold. The table below contains the most common data types in SQL:
Data Type Description
integer(size) Hold integers only. The maximum number of digits are specified in parenthesis.
int(size)
smallint(size)
tinyint(size)
decimal(size,d) Hold numbers with fractions. The maximum number of digits are specified in "size".
numeric(size,d) The maximum number of digits to the right of the decimal is specified in "d".
char(size) Holds a fixed length string (can contain letters, numbers, and special characters).
The fixed size is specified in parenthesis.
varchar(size) Holds a variable length string (can contain letters, numbers, and special
characters). The maximum size is specified in parenthesis.
date(yyyymmdd) Holds a date
What is the difference between VARCHAR, VARCHAR2 and CHAR data types?
1. VARCHAR is going to be replaced by VARCHAR2 in next version. So, Oracle suggests the use VARCHAR2
instead of VARCHAR while declaring datatype.
2. VARCHAR can store up to 2000 bytes of characters while VARCHAR2 can store up to 4000 bytes of
characters.
3. If we declare datatype as VARCHAR then it will occupy space for NULL values, In case of VARCHAR2
datatype it will not occupy any space
So, if we are to create the customer table specified as above, we would type in

CREATE TABLE customer


(First_Name char(50),
Last_Name char(50),
Address char(50),
City char(50),
Country char(25),
Birth_Date date)

Sometimes, we want to provide a default value for each column. A default value is used when
you do not specify a column's value when inserting data into the table. To specify a default value,
add "Default [value]" after the data type declaration. In the above example, if we want to default
column "Address" to "Unknown" and City to "Mumbai", we would type in

CREATE TABLE customer


(First_Name char(50),
Last_Name char(50),
Address char(50) default 'Unknown',
City char(50) default 'Mumbai',
Country char(25),
Birth_Date date)

You can also limit the type of information a table / a column can hold. This is done through the
CONSTRAINT keyword, which is discussed next.

CONSTRAIN
NOT NULL

By default, a column can hold NULL. If you not want to allow NULL value in a column, you will
want to place a constraint on this column specifying that NULL is now not an allowable value.

For example, in the following statement,

CREATE TABLE Customer


(SID integer NOT NULL,
Last_Name varchar (30) NOT NULL,
First_Name varchar(30));

Columns "SID" and "Last_Name" cannot include NULL, while "First_Name" can include NULL.

UNIQUE

The UNIQUE constraint ensures that all values in a column are distinct.

For example, in the following statement,


CREATE TABLE Customer
(SID integer Unique,
Last_Name varchar (30),
First_Name varchar(30));

Column "SID" cannot include duplicate values, while such constraint does not hold for columns
"Last_Name" and "First_Name".

Please note that a column that is specified as a primary key must also be unique. At the same
time, a column that's unique may or may not be a primary key.

CHECK

The CHECK constraint ensures that all values in a column satisfy certain conditions.

For example, in the following statement,

CREATE TABLE Customer


(SID integer CHECK (SID > 0),
Last_Name varchar (30),
First_Name varchar(30));

Column "SID" must only include integers greater than 0

Create a Database
To create a database:
CREATE DATABASE database_name

Example
This example demonstrates how you can create a table named "Person", with four columns. The column names will be
"LastName", "FirstName", "Address", and "Age":
CREATE TABLE Person
(
LastName varchar,
FirstName varchar,
Address varchar,
Age int
)
This example demonstrates how you can specify a maximum length for some columns:
CREATE TABLE Person
(
LastName varchar(30),
FirstName varchar,
Address varchar,
Age int(3)
)
Schema for Relation S: (S#,SNAME,CITY,STATUS)

SQL> CREATE TABLE S


(
S# CHAR(5) PRIMARY KEY,
SNAME VARCHAR2(20) NOT NULL
CITY VARCHAR(10) NOT NULL,
STATUS INTEGER
);

Arity or Degree of the relation: 4


('S1','SMITH','LONDON',20);
INSERT INTO S(S#,SNAME,CITY,STATUS) VALUES
('S2','SIMONDS','SYDENY',40);
INSERT INTO S(S#,SNAME,CITY,STATUS) VALUES
('S3','JHONES','NEWYORK',50);
INSERT INTO S(S#,SNAME,CITY,STATUS) VALUES
('S4','AGARWAL','DELHI',50);
INSERT INTO S(S#,SNAME,CITY,STATUS) VALUES
('S5','GUPTA','KOLKATA',45);
INSERT INTO S(S#,SNAME,CITY,STATUS) VALUES ('S6','DAS','RANCHI',20);
INSERT INTO S(S#,SNAME,CITY,STATUS) VALUES
('S7','PATTANAYAK','KATAK',26);
INSERT INTO S(S#,SNAME,CITY,STATUS) VALUES ('S8','RAI','MUMBAI',50);
INSERT INTO S(S#,SNAME,CITY,STATUS) VALUES
('S9','ULLMAN','LONDON',20);
INSERT INTO S(S#,SNAME,CITY,STATUS) VALUES
('S0','HAYES','NEWYORK',50);
INSERT INTO S(S#,SNAME,CITY,STATUS) VALUES ('S11','SMITH','DELHI',50);
INSERT INTO S(S#,SNAME,CITY,STATUS) VALUES
('S10','SMITH','KOLKATA',45);

SQL> @e:\studymat\sqlcomm.sql;

Instance of Relation S:

SQL> SELECT * FROM S;

S# SNAME CITY STATUS


----- -------------------- ---------- ----------
S1 SMITH LONDON 20
S2 SIMONDS SYDENY 40
S3 JHONES NEWYORK 50
S4 AGARWAL DELHI 50
S5 GUPTA KOLKATA 45
S6 DAS RANCHI 20
S7 PATTANAYAK KATAK 26
S8 RAI MUMBAI 50
S9 ULLMAN LONDON 20
S0 HAYES NEWYORK 50
S11 SMITH DELHI 50
S10 SMITH KOLKATA 45

12 rows selected.

SQL>

Cardinality of the relation S: 12


Schema for Relation P: (P#,PNAME,COLOR,CITY,WEIGHT)

SQL> CREATE TABLE P


(
P# CHAR(5) UNIQUE,
PNAME VARCHAR2(20) NOT NULL,
COLOR VARCHAR(10),
CITY VARCHAR(10) DEFAULT 'DELHI',
WEIGHT NUMERIC(10,2) CHECK (WEIGHT>0),
PRIMARY KEY (P#)
);
Arity or Degree of the relation: 5

P is a 5-tuple Table

INSERT INTO P(P#,PNAME,COLOR,CITY,WEIGHT) VALUES


('P0','NUT','RED','ATHENS',45);
INSERT INTO P(P#,PNAME,COLOR,CITY,WEIGHT) VALUES
('P1','NUT','RED','ATHENS',30.5);
INSERT INTO P(P#,PNAME,COLOR,CITY,WEIGHT) VALUES
('P2','NUT','BLUE','DELHI',15);
INSERT INTO P(P#,PNAME,COLOR,CITY,WEIGHT) VALUES
('P3','BOLT','RED','ATHENS',120);
INSERT INTO P(P#,PNAME,COLOR,CITY,WEIGHT) VALUES
('P4','BOLT','RED','LONDON',45);
INSERT INTO P(P#,PNAME,COLOR,CITY,WEIGHT) VALUES
('P5','NUT','RED','KOLKATA',45);
INSERT INTO P(P#,PNAME,COLOR,CITY,WEIGHT) VALUES
('P6','SCREW','GREEN','MUMBAI',20.4);
INSERT INTO P(P#,PNAME,COLOR,CITY,WEIGHT) VALUES
('P7','SPOON','GREY','KOLKATA',100);
INSERT INTO P(P#,PNAME,COLOR,CITY,WEIGHT) VALUES
('P8','SPOON','GREY','MUMBAI',100);
INSERT INTO P(P#,PNAME,COLOR,CITY,WEIGHT) VALUES
('P9','SPOON','GREY','NEWYORK',100);
INSERT INTO P(P#,PNAME,COLOR,CITY,WEIGHT) VALUES
('P10','COFFEE','BROWN','BANGLORE',200);

SQL> @e:\sqlcomm.sql;

Instance of Relation P:
SQL> SELECT * FROM P;

P# PNAME COLOR CITY WEIGHT


----- -------------------- ---------- ---------- ----------
P0 NUT RED ATHENS 45
P1 NUT RED ATHENS 30.5
P2 NUT BLUE DELHI 15
P3 BOLT RED ATHENS 120
P4 BOLT RED LONDON 45
P5 NUT RED KOLKATA 45
P6 SCREW GREEN MUMBAI 20.4
P7 SPOON GREY KOLKATA 100
P8 SPOON GREY MUMBAI 100
P9 SPOON GREY NEWYORK 100
P10 COFFEE BROWN BANGLORE 200

11 rows selected.

SQL>

Cardinality of the relation P: 11

Schema for Relation P: (S#, P#, QTY)

CREATE TABLE SP
(
S# CHAR(5) NOT NULL,
P# CHAR(5) NOT NULL,
QTY DEC(10,2) CHECK (QTY>0),
FOREIGN KEY (S#) REFERENCES S ON DELETE
CASCADE,
FOREIGN KEY (P#) REFERENCES P ON DELETE
CASCADE,
PRIMARY KEY(S#,P#)
);

Arity or Degree of the relation: 3

SP is a 3-tuple Table

INSERT INTO SP(S#,P#,QTY) VALUES ('S1','P1',200);


INSERT INTO SP(S#,P#,QTY) VALUES ('S1','P2',300);
INSERT INTO SP(S#,P#,QTY) VALUES ('S1','P3',100);
INSERT INTO SP(S#,P#,QTY) VALUES ('S1','P0',400);
INSERT INTO SP(S#,P#,QTY) VALUES ('S1','P4',600);
INSERT INTO SP(S#,P#,QTY) VALUES ('S1','P5',200);
INSERT INTO SP(S#,P#,QTY) VALUES ('S1','P6',700);
INSERT INTO SP(S#,P#,QTY) VALUES ('S2','P1',200);
INSERT INTO SP(S#,P#,QTY) VALUES ('S3','P1',400);
INSERT INTO SP(S#,P#,QTY) VALUES ('S4','P2',100);
INSERT INTO SP(S#,P#,QTY) VALUES ('S20','P1',200);
SQL> @e:\sqlcomm.sql;

INSERT INTO SP(S#,P#,QTY) VALUES ('S20','P1',200)


*
ERROR at line 1:
ORA-02291: integrity constraint (SCOTT.SYS_C002750) violated - parent key not
found

SQL>

Instance of Relation SP:


SQL> SELECT * FROM SP;

S# P# QTY
----- ----- ----------
S1 P1 200
S1 P2 300
S1 P3 100
S1 P0 400
S1 P4 600
S1 P5 200
S1 P6 700
S2 P1 200
S3 P1 400
S4 P2 100

10 rows selected.

SQL>

Cardinality of the relation SP:10


Create Index
Indices are created in an existing table to locate rows more quickly and efficiently. It is possible to create an index on one or
more columns of a table, and each index is given a name. The users cannot see the indexes, they are just used to speed up
queries.
Note: Updating a table containing indexes takes more time than updating a table without, this is
because the indexes also need an update. So, it is a good idea to create indexes only on columns
that are often used for a search.
A Unique Index

Creates a unique index on a table. A unique index means that two rows cannot have the same index value.
CREATE UNIQUE INDEX index_name
ON table_name (column_name)
The "column_name" specifies the column you want indexed.

A Simple Index

Creates a simple index on a table. When the UNIQUE keyword is omitted, duplicate values are allowed.
CREATE INDEX index_name
ON table_name (column_name)
The "column_name" specifies the column you want indexed.

Example
This example creates a simple index, named "PersonIndex", on the LastName field of the Person table:
CREATE INDEX PersonIndex
ON Person (LastName)
If you want to index the values in a column in descending order, you can add the reserved word DESC after the column
name:
CREATE INDEX PersonIndex
ON Person (LastName DESC)
If you want to index more than one column you can list the column names within the parentheses, separated by commas:
CREATE INDEX PersonIndex
ON Person (LastName, FirstName)

Drop Index
You can delete an existing index in a table with the DROP INDEX statement.

Syntax for Microsoft SQLJet (and Microsoft Access):


DROP INDEX index_name ON table_name
Syntax for MS SQL Server:
DROP INDEX table_name.index_name
Syntax for IBM DB2 and Oracle:
DROP INDEX index_name
Syntax for MySQL:
ALTER TABLE table_name DROP INDEX index_name

Delete a Table or Database


To delete a table (the table structure, attributes, and indexes will also be deleted):
DROP TABLE table_name
To delete a database:
DROP DATABASE database_name

Truncate a Table
What if we only want to get rid of the data inside a table, and not the table itself? Use the TRUNCATE TABLE command
(deletes only the data inside the table):
TRUNCATE TABLE table_name

ALTER TABLE
The SQL syntax for ALTER TABLE is

ALTER TABLE "table_name"


[alter specification]

[alter specification] is dependent on the type of alteration we wish to perform. For the uses cited
above, the [alter specification] statements are:
 Add a column: ADD "column 1" "data type for column 1"

 Drop a column: DROP "column 1"

 Change a column name: CHANGE "old column name" "new column name" "data type for
new column name"

 Change the data type for a column: MODIFY "column 1" "new data type"
The ALTER TABLE statement is used to add or drop columns in an existing table.
ALTER TABLE table_name
ADD column_name datatype
ALTER TABLE table_name
DROP COLUMN column_name
Note: Some database systems don't allow the dropping of a column in a database table (DROP COLUMN column_name).

Person:
LastName FirstName Address
Pettersen Kari Storgt 20

Example
To add a column named "City" in the "Person" table:
ALTER TABLE Person ADD City varchar(30)
Result:
LastName FirstName Address City
Pettersen Kari Storgt 20

Example
To drop the "Address" column in the "Person" table:
ALTER TABLE Person DROP COLUMN Address
Result:
LastName FirstName City
Pettersen Kari

ALTER TABLE Customer ADD PRIMARY KEY (SID);

ALTER TABLE ORDERS


ADD (CONSTRAINT fk_orders1) FOREIGN KEY (customer_sid) REFERENCES
CUSTOMER(SID);

SQL Data Manipulation Language (DML)


SQL (Structured Query Language) is a syntax for executing queries. But the SQL language also includes a syntax to update,
insert, and delete records.

These query and update commands together form the Data Manipulation Language (DML) part of SQL:

 SELECT - extracts data from a database table

 UPDATE - updates data in a database table

 DELETE - deletes data from a database table


 INSERT INTO - inserts new data into a database table
Syntax:
SELECT [ALL | DISTINCT] columnname1 [,columnname2]
FROM tablename1 [,tablename2]
[WHERE condition] [ and|or condition...]
[GROUP BY column-list]
[HAVING "conditions]
[ORDER BY "column-list" [ASC | DESC] ]

Select */fieldname ...


from tablename
where fieldname =/!=/<>/>/>=/</<=/in/not in/between/not between/begins
with/contains/not contains/ is null/is not null/like/not/like value/exists/not exists
order by fieldname <desc>...
With the WHERE clause, the following operators can be used:
Operato
Description
r
= Equal
<> Not equal
> Greater than
< Less than
>= Greater than or equal
<= Less than or equal
BETWEEN Between an inclusive range
LIKE Search for a pattern
IN If you know the exact value you want to return for at least
one of the columns
Note: In some versions of SQL the <> operator may be written as !=

The SELECT DISTINCT Statement


The DISTINCT keyword is used to return only distinct (different) values.
The SELECT statement returns information from table columns. But what if we only
want to select distinct elements?
With SQL, all we need to do is to add a DISTINCT keyword to the SELECT statemen
The GROUP BY Clause
This "GROUP BY" clause allows multiple columns to be grouped so aggregate functions
(listed below) may be performed on multiple columns with one command.
Aggregate function keywords:
 AVG - Get the average of a specified column.
 COUNT - Get the quantity of values in the column.
 MAX - Return the maximum value in a specified column.
 MIN - Return the minimum value in a specified column.
 SUM - Return the sum of all numeric values in the specified column.
Example:
SELECT MAX(population)
FROM citylist;
WHERE state = 'Indiana';
Example using the GROUP BY clause which gets the smallest population of each city in
every state:
SELECT MIN(population)
FROM citylist;
GROUP BY state;

The HAVING Clause


Allows selection of set test criteria on rows. You can display average size of towns
whose population is less than 100.

The ORDER BY Clause


This clause lets results be displayed in ascending or descending order. Keywords:
 ASC - Ascending order.
 DESC - Descending order.

Other Keywords
 ALL - Used to select all records.
 DISTINCT - Used to select unique records. Only unique values are returned.
The ORDER BY keyword is used to sort the result.

Sort the Rows


The ORDER BY clause is used to sort the rows.

Orders:
Company OrderNumber
Sega 3412
ABC Shop 5678
W3Schools 6798
W3Schools 2312

Example
To display the company names in alphabetical order:
SELECT Company, OrderNumber FROM Orders
ORDER BY Company
Result:
Company OrderNumber
ABC Shop 5678
Sega 3412
W3Schools 6798
W3Schools 2312
Example
To display the company names in alphabetical order AND the OrderNumber in numerical order:
SELECT Company, OrderNumber FROM Orders
ORDER BY Company, OrderNumber
Result:
Company OrderNumber
ABC Shop 5678
Sega 3412
W3Schools 2312
W3Schools 6798

Example
To display the company names in reverse alphabetical order:
SELECT Company, OrderNumber FROM Orders
ORDER BY Company DESC
Result:
Company OrderNumber
W3Schools 6798
W3Schools 2312
Sega 3412
ABC Shop 5678

Example
To display the company names in reverse alphabetical order AND the OrderNumber in numerical order:
SELECT Company, OrderNumber FROM Orders
ORDER BY Company DESC, OrderNumber ASC
Result:
Company OrderNumber
W3Schools 2312
W3Schools 6798
Sega 3412
ABC Shop 5678
Notice that there are two equal company names (W3Schools) in the result above. The only time you will see the second
column in ASC order would be when there are duplicated values in the first sort column, or a handful of nulls.

CONCAT

Sometimes it is necessary to combine together (concatenate) the results from several different
fields. Each database provides a way to do this:

 MySQL: CONCAT()

 Oracle: CONCAT(), ||

 SQL Server: +

The syntax for CONCAT() is as follows:

CONCAT(str1, str2, str3, ...): Concatenate str1, str2, str3, and any other strings together. Please
note the Oracle CONCAT() function only allows two arguments -- only two strings can be put
together at a time using this function. However, it is possible to concatenate more than two
strings at a time in Oracle using '||'.
Let's look at some examples. Assume we have the following table:

Table Geography
region_name store_name
East Boston
East New York
West Los Angeles
West San Diego
Example 1:

MySQL/Oracle:
SELECT CONCAT(region_name,store_name) FROM Geography
WHERE store_name = 'Boston';

Result:

'EastBoston'

Example 2:

Oracle:
SELECT region_name || ' ' || store_name FROM Geography
WHERE store_name = 'Boston';

Result:

'East Boston'

Example 3:

SQL Server:
SELECT region_name + ' ' + store_name FROM Geography
WHERE store_name = 'Boston';

Result:

'East Boston'

SUBSTR

The Substring function in SQL is used to grab a portion of the stored data. This function is called
differently for the different databases:

 MySQL: SUBSTR(), SUBSTRING()

 Oracle: SUBSTR()

 SQL Server: SUBSTRING()


The most frequent uses are as follows (we will use SUBSTR() here):
SUBSTR(str,pos): Select all characters from <str> starting with position <pos>. Note that this
syntax is not supported in SQL Server.

SUBSTR(str,pos,len): Starting with the <pos>th character in string <str> and select the next
<len> characters.

Assume we have the following table:


Table Geography
region_name store_name
East Boston
East New York
West Los Angeles
West San Diego
Example 1:

SELECT SUBSTR(store_name, 3)
FROM Geography
WHERE store_name = 'Los Angeles';

Result:

's Angeles'

Example 2:

SELECT SUBSTR(store_name,2,4)
FROM Geography
WHERE store_name = 'San Diego';

Result:

'an D'
Retrieve all vendors with a current balance between 500 and 1000 dollars.
Select VendId, Name, CurrBal [ZZ,ZZZ.99]
from TrnVendor
where CurrBal between 500 and 1000
order by CurrBal;

Retrieve all vendors who are not located in Chicago. Order the results by city.
Select City, Name, VendId
from TrnVendor
where City <> 'Chicago'
order by City;

Retrieve all vendors in Mercer, New York, or Park Ridge.


Select City, Name, VendId
from TrnVendor
where City in ( 'Mercer', 'New York', 'Park Ridge')
order by City;

Retrieve all vendors whose names begin with "Co."


Select Name, City, VendId
from TrnVendor
where Name begins with 'Co'
order by Name;

Retrieve all vendors whose city ends with the letters "do."
Select Name, City, VendId
from TrnVendor
where City like '%do'
order by City;

Retrieve all vendors whose expense account is 4110 or who have a current balance over
1200. The vendor must be located in Chicago.

Select City, CurrBal [-ZZZ,ZZZ.99], ExpAcct


from Vendor
where City = 'Chicago'
and (ExpAcct = '4110'
or CurrBal > 1200)
order by City, ExpAcct;

It is possible to embed a SQL statement within another. When this is done on the WHERE or the
HAVING statements, we have a subquery construct.

The syntax is as follows:

SELECT "column_name1"
FROM "table_name1"
WHERE "column_name2" [Comparison Operator]
(SELECT "column_name3"
FROM "table_name2"
WHERE [Condition])

[Comparison Operator] could be equality operators such as =, >, <, >=, <=. It can also be a text
operator such as "LIKE". The portion in red is considered as the "inner query", while the portion
in green is considered as the "outer query".

Let's use the same example as we did to illustrate SQL joins:

Table Store_Information
store_name Sales Date
Los Angeles $1500 Jan-05-1999
San Diego $250 Jan-07-1999
Los Angeles $300 Jan-08-1999
Boston $700 Jan-08-1999
Table Geography
region_name store_name
East Boston
East New York
West Los Angeles
West San Diego
and we want to use a subquery to find the sales of all stores in the West region. To do so, we use
the following SQL statement:

SELECT SUM(Sales) FROM Store_Information


WHERE Store_name IN
(SELECT store_name FROM Geography
WHERE region_name = 'West')
Result:
SUM(Sales)
2050
In this example, instead of joining the two tables directly and then adding up only the sales
amount for stores in the West region, we first use the subquery to find out which stores are in the
West region, and then we sum up the sales amount for these stores.

In the above example, the inner query is first executed, and the result is then fed into the outer
query. This type of subquery is called a simple subquery. If the inner query is dependent on the
outer query, we will have a correlated subquery. An example of a correlated subquery is
shown below:

SELECT SUM(a1.Sales) FROM Store_Information a1


WHERE a1.Store_name IN
(SELECT store_name FROM Geography a2
WHERE a2.store_name = a1.store_name)

Notice the WHERE clause in the inner query, where the condition involves a table from the outer
query

EXISTS
In the previous section, we used IN to link the inner query and the outer query in a subquery
statement. IN is not the only way to do so -- one can use many operators such as >, <, or =.
EXISTS is a special operator that we will discuss in this section.

EXISTS simply tests whether the inner query returns any row. If it does, then the outer query
proceeds. If not, the outer query does not execute, and the entire SQL statement returns nothing.

The syntax for EXISTS is:

SELECT "column_name1"
FROM "table_name1"
WHERE EXISTS
(SELECT *
FROM "table_name2"
WHERE [Condition])

Please note that instead of *, you can select one or more columns in the inner query. The effect
will be identical.

Let's use the same example tables:

Table Store_Information
store_name Sales Date
Los Angeles $1500 Jan-05-1999
San Diego $250 Jan-07-1999
Los Angeles $300 Jan-08-1999
Boston $700 Jan-08-1999
Table Geography
region_name store_name
East Boston
East New York
West Los Angeles
West San Diego
and we issue the following SQL query:

SELECT SUM(Sales) FROM Store_Information


WHERE EXISTS
(SELECT * FROM Geography
WHERE region_name = 'West')

We'll get the following result:


SUM(Sales)
2750
At first, this may appear confusing, because the subquery includes the [region_name = 'West']
condition, yet the query summed up stores for all regions. Upon closer inspection, we find that
since the subquery returns more than 0 row, the EXISTS condition is true, and the condition
placed inside the inner query does not influence how the outer query is run

CASE:
CASE is used to provide if-then-else type of logic to SQL. Its syntax is:

SELECT CASE ("column_name")


WHEN "condition1" THEN "result1"
WHEN "condition2" THEN "result2"
...
[ELSE "resultN"]
END
FROM "table_name"

"condition" can be a static value or an expression. The ELSE clause is optional.

In our Table Store_Information example,

Table Store_Information
store_name Sales Date
Los Angeles $1500 Jan-05-1999
San Diego $250 Jan-07-1999
San Francisco $300 Jan-08-1999
Boston $700 Jan-08-1999

if we want to multiply the sales amount from 'Los Angeles' by 2 and the sales amount from 'San
Diego' by 1.5, we key in,

SELECT store_name, CASE store_name


WHEN 'Los Angeles' THEN Sales * 2
WHEN 'San Diego' THEN Sales * 1.5
ELSE Sales
END
"New Sales",
Date
FROM Store_Information

"New Sales" is the name given to the column with the CASE statement.
Result:
store_name New Sales Date
Los Angeles $3000 Jan-05-1999
San Diego $375 Jan-07-1999
San Francisco $300 Jan-08-1999
Boston $700 Jan-08-1999

RUNNING TOTALS
Displaying running totals is a common request, and there is no straightforward way to do so in
SQL. The idea for using SQL to display running totals similar to that for displaying rank: first do a
self-join, then, list out the results in order. Where as finding the rank requires doing a count on
the number of records that's listed ahead of (and including) the record of interest, finding the
running total requires summing the values for the records that's listed ahead of (and including)
the record of interest.

Let's use an example to illustrate. Say we have the following table,

Table Total_Sales
Name Sales
John 10
Jennifer 15
Stella 20
Sophia 40
Greg 50
Jeff 20

we would type,

SELECT a1.Name, a1.Sales, SUM(a2.Sales) Running_Total


FROM Total_Sales a1, Total_Sales a2
WHERE a1.Sales <= a2.sales or (a1.Sales=a2.Sales and a1.Name = a2.Name)
GROUP BY a1.Name, a1.Sales
ORDER BY a1.Sales DESC, a1.Name DESC;

Result:
Name Sales Running_Total
Greg 50 50
Sophia 40 90
Stella 20 110
Jeff 20 130
Jennifer 15 145
John 10 155
The combination of the WHERE clause and the ORDER BY clause ensure that the proper
running totals are tabulated when there are duplicate values.

RANK
Displaying the rank associated with each row is a common request, and there is no
straightforward way to do so in SQL. To display rank in SQL, the idea is to do a self-join, list out
the results in order, and do a count on the number of records that's listed ahead of (and
including) the record of interest. Let's use an example to illustrate. Say we have the following
table,
Table Total_Sales
Name Sales
John 10
Jennifer 15
Stella 20
Sophia 40
Greg 50
Jeff 20

we would type,

SELECT a1.Name, a1.Sales, COUNT(a2.sales) Sales_Rank


FROM Total_Sales a1, Total_Sales a2
WHERE a1.Sales <= a2.Sales or (a1.Sales=a2.Sales and a1.Name = a2.Name)
GROUP BY a1.Name, a1.Sales
ORDER BY a1.Sales DESC, a1.Name DESC;

Result:
Name Sales Sales_Rank
Greg 50 1
Sophia 40 2
Stella 20 3
Jeff 20 3
Jennifer 15 5
John 10 6

PERCENTAGE
To display percent to total in SQL, we want to leverage the ideas we used for rank/running total
plus subquery. Different from what we saw in the SQL Subquery section, here we want to use
the subquery as part of the SELECT. Let's use an example to illustrate. Say we have the
following table,

Table Total_Sales
Name Sales
John 10
Jennifer 15
Stella 20
Sophia 40
Greg 50
Jeff 20

we would type,

SELECT a1.Name, a1.Sales, a1.Sales/(SELECT SUM(Sales) FROM Total_Sales)


Pct_To_Total
FROM Total_Sales a1, Total_Sales a2
WHERE a1.Sales <= a2.sales or (a1.Sales=a2.Sales and a1.Name = a2.Name)
GROUP BY a1.Name, a1.Sales
ORDER BY a1.Sales DESC, a1.Name DESC;

Result:
Name Sales Pct_To_Total
Greg 50 0.3226
Sophia 40 0.2581
Stella 20 0.1290
Jeff 20 0.1290
Jennifer 15 0.0968
John 10 0.0645
The subquery "SELECT SUM(Sales) FROM Total_Sales" calculates the sum. We can then divide
the individual values by this sum to obtain the percent to total for each row.

CUMULATIVE PERCENT
To display cumulative percent to total in SQL, we use the same idea as we saw in the Percent
To Total section. The difference is that we want the cumulative percent to total, not the
percentage contribution of each individual row. Let's use the following example to illuatrate:

Table Total_Sales
Name Sales
John 10
Jennifer 15
Stella 20
Sophia 40
Greg 50
Jeff 20

we would type,

SELECT a1.Name, a1.Sales, SUM(a2.Sales)/(SELECT SUM(Sales) FROM Total_Sales)


Pct_To_Total
FROM Total_Sales a1, Total_Sales a2
WHERE a1.Sales <= a2.sales or (a1.Sales=a2.Sales and a1.Name = a2.Name)
GROUP BY a1.Name, a1.Sales
ORDER BY a1.Sales DESC, a1.Name DESC;

Result:
Name Sales Pct_To_Total
Greg 50 0.3226
Sophia 40 0.5806
Stella 20 0.7097
Jeff 20 0.8387
Jennifer 15 0.9355
John 10 1.0000
The subquery "SELECT SUM(Sales) FROM Total_Sales" calculates the sum. We can then divide
the running total, "SUM(a2.Sales)", by this sum to obtain the cumulative percent to total for each
row.

MEDIAN
To get the median, we need to be able to accomplish the following:

 Sort the rows in order and find the rank for each row.

 Determine what is the "middle" rank. For example, if there are 9 rows, the middle rank
would be 5.

 Obtain the value for the middle-ranked row.

Let's use an example to illustrate. Say we have the following table,

Table Total_Sales
Name Sales
John 10
Jennifer 15
Stella 20
Sophia 40
Greg 50
Jeff 20

we would type,

SELECT Sales Median FROM


(SELECT a1.Name, a1.Sales, COUNT(a1.Sales) Rank
FROM Total_Sales a1, Total_Sales a2
WHERE a1.Sales < a2.Sales OR (a1.Sales=a2.Sales AND a1.Name <= a2.Name)
group by a1.Name, a1.Sales
order by a1.Sales desc) a3
WHERE Rank = (SELECT (COUNT(*)+1) DIV 2 FROM Total_Sales);

Result:
Median
20
You will find that Lines 2-6 are the same as how we find the rank of each row. Line 7 finds the
"middle" rank. DIV is the way to find the quotient in MySQL, the exact way to obtain the quotient
may be different with other databases. Finally, Line 1 obtains the value for the middle-ranked row.

Joining Tables

Select */tablename.fieldname<mask> ...


from tablename <alias>, tablename <alias>, tablename <alias>
where tablename.fieldname = tablename.fieldname
and
tablename.fieldname = tablename.fieldname
and
tablename.fieldname = tablename.fieldname
order by fieldname <desc>...

Explanation:
When you join two or more tables, a good idea is to precede the field names with the
table names. This is not mandatory unless the same field name is found in more than one
table.
If you precede the field name with a table name, place a period between the two names.
For example, tablename.fieldname.
You must specify which fields are being joined.
If you do not specify which fields are being joined, the result is what is commonly
referred to as a "Cartesian join" in which all rows in the first table are joined with all
rows in the second table.
You can give each table name an alias, or alternative table name. When you assign an
alias, you can then refer to the table by using its alias.

Joins and Keys


Sometimes we have to select data from two or more tables to make our result complete.
We have to perform a join.
Tables in a database can be related to each other with keys. A primary key is a column
with a unique value for each row. Each primary key value must be unique within the
table. The purpose is to bind data together, across tables, without repeating all of the data
in every table.
In the "Employees" table below, the "Employee_ID" column is the primary key, meaning
that no two rows can have the same Employee_ID. The Employee_ID distinguishes two
persons even if they have the same name.
When you look at the example tables below, notice that:
The "Employee_ID" column is the primary key of the "Employees"
table
The "Prod_ID" column is the primary key of the "Orders" table
The "Employee_ID" column in the "Orders" table is used to refer to the
persons in the "Employees" table without using their names

Employees:
Employee_ID Name
01 Hansen, Ola
02 Svendson, Tove
03 Svendson, Stephen
04 Pettersen, Kari
Orders:
Prod_ID Product Employee_ID
234 Printer 01
657 Table 03
865 Chair 03

Referring to Two Tables


We can select data from two tables by referring to two tables, like this:
Example
Who has ordered a product, and what did they order?

SELECT Employees.Name, Orders.Product


FROM Employees, Orders
WHERE Employees.Employee_ID=Orders.Employee_ID
Result
Name Product
Hansen, Ola Printer
Svendson, Stephen Table
Svendson, Stephen Chair

Example
Who ordered a printer?
SELECT Employees.Name
FROM Employees, Orders
WHERE Employees.Employee_ID=Orders.Employee_ID
AND Orders.Product='Printer'
Result
Name
Hansen, Ola

Using Joins
OR we can select data from two tables with the JOIN keyword, like this:

Example INNER JOIN


Syntax
SELECT field1, field2, field3
FROM first_table
INNER JOIN second_table
ON first_table.keyfield = second_table.foreign_keyfield
Who has ordered a product, and what did they order?
SELECT Employees.Name, Orders.Product
FROM Employees
INNER JOIN Orders
ON Employees.Employee_ID=Orders.Employee_ID
The INNER JOIN returns all rows from both tables where there is a match. If there are rows in Employees that do not have
matches in Orders, those rows will not be listed.

Result
Name Product
Hansen, Ola Printer
Svendson, Stephen Table
Svendson, Stephen Chair

Example LEFT JOIN


Syntax
SELECT field1, field2, field3
FROM first_table
LEFT JOIN second_table
ON first_table.keyfield = second_table.foreign_keyfield
List all employees, and their orders - if any.
SELECT Employees.Name, Orders.Product
FROM Employees
LEFT JOIN Orders
ON Employees.Employee_ID=Orders.Employee_ID
The LEFT JOIN returns all the rows from the first table (Employees), even if there are no matches in the second table
(Orders). If there are rows in Employees that do not have matches in Orders, those rows also will be listed.

Result
Name Product
Hansen, Ola Printer
Svendson, Tove
Svendson, Stephen Table
Svendson, Stephen Chair
Pettersen, Kari

Example RIGHT JOIN


Syntax
SELECT field1, field2, field3
FROM first_table
RIGHT JOIN second_table
ON first_table.keyfield = second_table.foreign_keyfield
List all orders, and who has ordered - if any.
SELECT Employees.Name, Orders.Product
Example
Who ordered a printer?
SELECT Employees.Name
FROM Employees
INNER JOIN Orders
ON Employees.Employee_ID=Orders.Employee_ID
WHERE Orders.Product = 'Printer'
Result
Name
Hansen, Ola

OUTER JOIN
Previously, we had looked at left join, or inner join, where we select rows common to the
participating tables to a join. What about the cases where we are interested in selecting elements
in a table regardless of whether they are present in the second table? We will now need to use
the SQL OUTER JOIN command.

The syntax for performing an outer join in SQL is database-dependent. For example, in Oracle,
we will place an "(+)" in the WHERE clause on the other side of the table for which we want to
include all the rows.

Let's assume that we have the following two tables,

Table Store_Information
store_name Sales Date
Los Angeles $1500 Jan-05-1999
San Diego $250 Jan-07-1999
Los Angeles $300 Jan-08-1999
Boston $700 Jan-08-1999
Table Geography
region_name store_name
East Boston
East New York
West Los Angeles
West San Diego
and we want to find out the sales amount for all of the stores. If we do a regular join, we will not
be able to get what we want because we will have missed "New York," since it does not appear
in the Store_Information table. Therefore, we need to perform an outer join on the two tables
above:

SELECT A1.store_name, SUM(A2.Sales) SALES


FROM Geography A1, Store_Information A2
WHERE A1.store_name = A2.store_name (+)
GROUP BY A1.store_name

Note that in this case, we are using the Oracle syntax for outer join.

Result:
store_name SALES
Boston $700
New York
Los Angeles $1800
San Diego $250
Note: NULL is returned when there is no match on the second table. In this case, "New York"
does not appear in the table Store_Information, thus its corresponding "SALES" column is
NULL.

Examples:
Retrieve the vendor ID, the vendor name, and the original document amount from the
TrnAPDoc and TrnVendor tables.

Select TrnAPDoc.VendId, TrnVendor.Name,


TrnAPDoc.OrigDocAmt [-ZZZZZZ.99]
from TrnAPDoc, TrnVendor
where TrnAPDoc.VendId = TrnVendor.VendId

Retrieve the vendor ID, vendor name, and the original document amount from the
TrnAPDoc and TrnVendor tables, using a table alias.

Select a.VendId, b.Name,


a.OrigDocAmt [-ZZZZZZ.99]
from TrnAPDoc a, TrnVendor b
where a.VendId = b.VendId;

Retrieve the vendor ID, vendor name, reference number, and original document amount
from the APDoc and Vendor tables for Vendor V00104. Order the results by RefNbr.

Select TrnAPDoc.VendId, TrnVendor.Name, TrnAPDoc.RefNbr,


TrnAPDoc.OrigDocAmt [-ZZZZZZ.99]
from TrnAPDoc, TrnVendor
where TrnAPDoc.VendId = TrnVendor.VendId
and
TrnAPdoc.VendId = 'TV004'
order by TrnAPDoc.RefNbr;

Updating Tables
The UPDATE statement is used to modify the data in a table.
Syntax:
Start transaction;
UPDATE table_name
SET column_name = new_value
WHERE column_name = some_value
Rollback work;
Commit work;
Explanation:
Issue a Start Transaction command before updating your table. This will allow you to roll
back the changes, if necessary. If you do not issue a Start Transaction command, you will
not be able the roll back your work.
If you find that you have updated a row in error, execute the Rollback Work command.
When you are satisfied with your changes, issue the Commit Work command.
Use a Where clause to specify which rows will be updated. If you do not include a Where
clause, all rows will be updated.
Remember to end each command with a semicolon.
Person:
LastName FirstName Address City
Nilsen Fred Kirkegt 56 Stavanger
Rasmussen Storgt 67

Update one Column in a Row


We want to add a first name to the person with a last name of "Rasmussen":
UPDATE Person SET FirstName = 'Nina'
WHERE LastName = 'Rasmussen'
Result:
LastName FirstName Address City
Nilsen Fred Kirkegt 56 Stavanger
Rasmussen Nina Storgt 67

Update several Columns in a Row


We want to change the address and add the name of the city:
UPDATE Person
SET Address = 'Stien 12', City = 'Stavanger'
WHERE LastName = 'Rasmussen'
Result:
LastName FirstName Address City
Nilsen Fred Kirkegt 56 Stavanger
Rasmussen Nina Stien 12 Stavanger

Example:
Change the name of vendor "TV001" to Genie R. Corp., and then roll back the change.
Then change the name of vendor "TV001" to Vanix and commit your work.

To start the transaction, type:


Start transaction;
Note the current vendor name, and type:
Select VendId, Name
from TrnVendor
where VendId = 'TV001';

To update the vendor name, type:


Update TrnVendor
Set Name = 'Genie R Corp.'
Where VendId = 'TV001';

To check the vendor name to see that it has changed, type:


Select VendId, Name
from TrnVendor
where VendId = 'TV001';
To roll back the change, type:
Rollback work;

To check the vendor name to see that it has reverted to the original, type:
Select VendId, Name
from TrnVendor
where VendId = 'TV001';

To update the vendor name, type:


Update TrnVendor
Set Name = 'Vanix'
Where VendId = 'TV001';

To check the vendor name to see that it has changed, type:


Select VendId, Name
from TrnVendor
where VendId = 'TV001';

To commit the change, type:


Commit work;

Deleting Rows
The DELETE statement is used to delete rows in a table.
Syntax:
Delete from tablename
where fieldname =/<>/ ... value
and/or ...
fieldname =/<>/ ... value
and/or
fieldname =/<>/ ... value
Explanation:
 If you do not include a Where clause, all of the rows in the table will be
deleted.
 Every table has a primary key -- a field or combination of fields that uniquely
identify each row in the table. VendId is the primary key for the vendor table.
Each vendor is uniquely identified by the vendor Id. RefNbr is the primary key
for APDoc.
 If you want to delete a single row of data, you can refer to the row in the Where
clause by using the primary key.
 When deleting data, use the Start Transaction command so that any errors can be
rolled back.
 Use the Rollback Work command to undo changes.
 Use the Commit Work command to finalize changes.

Syntax
DELETE FROM table_name
WHERE column_name = some_value

Person:
LastName FirstName Address City
Nilsen Fred Kirkegt 56 Stavanger
Rasmussen Nina Stien 12 Stavanger

Delete a Row
"Nina Rasmussen" is going to be deleted:
DELETE FROM Person WHERE LastName = 'Rasmussen'
Result
LastName FirstName Address City
Nilsen Fred Kirkegt 56 Stavanger

Delete All Rows


It is possible to delete all rows in a table without deleting the table. This means that the table structure, attributes, and indexes
will be intact:
DELETE FROM table_name
or
DELETE * FROM table_name

Examples:
Delete vendor TV011 by executing the following commands.
1. To view the record, type:
Select *
from TrnVendor
where VendId = 'TV011';
2. To start the transaction, type:
Start transaction;
3. To delete the record, type:
Delete from TrnVendor
where VendId = 'TV011 ';
4. To check to make sure the records have been deleted, type:
Select *
from TrnVendor
where VendId = 'TV011';
5. To roll back the deletion, type:
Rollback work;
Delete all vendors with a current balance over 2000 dollars.
1. To view the records, type:
Select Name, CurrBal [-ZZZ,ZZZ.99]
from TrnVendor
where CurrBal > 2000;
2. To start the transaction, type:
Start transaction;
3. To delete the records, type:
Delete from TrnVendor
where CurrBal > 2000;
4. To check to make sure the records have been deleted, type:
Select Name, CurrBal [-ZZZ,ZZZ.99]
from TrnVendor
where CurrBal > 2000;
5. To roll back the deletion, type:
Rollback work;

Inserting Rows
You can insert new rows into a table by using Scalable SQL.
Syntax:

Insert into tablename ( fieldname, fieldname, fieldname)


values ( value, value, value);
Explanation:
 When inserting data, use the Start Transaction command so that any errors can be
rolled back.
 You must specify the values to be inserted.
 When performing an insert, enclose character values in single quotes.
 Do not enclose numeric values in single quotes.
 Use the Rollback Work command to undo changes.
 Use the Commit Work command to finalize changes.

The INSERT INTO Statement


The INSERT INTO statement is used to insert new rows into a table.

Syntax
INSERT INTO table_name
VALUES (value1, value2,....)
You can also specify the columns for which you want to insert data:
INSERT INTO table_name (column1, column2,...)
VALUES (value1, value2,....)

Insert a New Row


This "Persons" table:
LastName FirstName Address City
Pettersen Kari Storgt 20 Stavanger
And this SQL statement:
INSERT INTO Persons
VALUES ('Hetland', 'Camilla', 'Hagabakka 24', 'Sandnes')
Will give this result:
LastName FirstName Address City
Pettersen Kari Storgt 20 Stavanger
Hetland Camilla Hagabakka 24 Sandnes

Insert Data in Specified Columns


This "Persons" table:
LastName FirstName Address City
Pettersen Kari Storgt 20 Stavanger
Hetland Camilla Hagabakka 24 Sandnes
And This SQL statement:
INSERT INTO Persons (LastName, Address)
VALUES ('Rasmussen', 'Storgt 67')
Will give this result:
LastName FirstName Address City
Pettersen Kari Storgt 20 Stavanger
Hetland Camilla Hagabakka 24 Sandnes
Rasmussen Storgt 67

Example:
Insert the following vendor into the TrnVendor table.
Vendor Id: TV055
Name: Party Games
Address: PO Box 136
City: Chicago
State: IL
Current Balance: 2498.62
1. To start the transaction, type:
Start transaction;
2. To insert the records, type:
Insert into TrnVendor (VendId, Name, Addr1, City, State,
CurrBal )
values ( 'TV055', 'Party Games', 'PO Box 136', 'Chicago', 'IL',
2498.62);
3. To view the record, type:
Select VendId, Name, Addr1, City, State, CurrBal [-ZZZ,ZZZ.99]
from TrnVendor
where VendId = 'TV055';
4. To roll back your work, type:
Rollback work;

UNION
The UNION command is used to select related information from two tables, much like the JOIN command. However, when
using the UNION command all selected columns need to be of the same data type.

Note: With UNION, only distinct values are selected.


SQL Statement 1
UNION
SQL Statement 2

Employees_Norway:
E_ID E_Name
01 Hansen, Ola
02 Svendson, Tove
03 Svendson, Stephen
04 Pettersen, Kari
Employees_USA:
E_ID E_Name
01 Turner, Sally
02 Kent, Clark
03 Svendson, Stephen
04 Scott, Stephen
Using the UNION Command

Example
List all different employee names in Norway and USA:
SELECT E_Name FROM Employees_Norway
UNION
SELECT E_Name FROM Employees_USA
Result
E_Name
Hansen, Ola
Svendson, Tove
Svendson, Stephen
Pettersen, Kari
Turner, Sally
Kent, Clark
Scott, Stephen
Note: This command cannot be used to list all employees in Norway and USA. In the example above we have two employees
with equal names, and only one of them is listed. The UNION command only selects distinct values.

UNION ALL
The UNION ALL command is equal to the UNION command, except that UNION ALL selects all values.
SQL Statement 1
UNION ALL
SQL Statement 2

Using the UNION ALL Command

Example
List all employees in Norway and USA:
SELECT E_Name FROM Employees_Norway
UNION ALL
SELECT E_Name FROM Employees_USA

INTERSECT
Similar to the UNION command, INTERSECT also operates on two SQL statements. The
difference is that, while UNION essentially acts as an OR operator (value is selected if it appears
in either the first or the second statement), the INTERSECT command acts as an AND operator
(value is selected only if it appears in both statements).

The syntax is as follows:

[SQL Statement 1]
INTERSECT
[SQL Statement 2]

Let's assume that we have the following two tables,

Table Store_Information
store_name Sales Date
Los Angeles $1500 Jan-05-1999
San Diego $250 Jan-07-1999
Los Angeles $300 Jan-08-1999
Boston $700 Jan-08-1999
Table Internet_Sales
Date Sales
Jan-07-1999 $250
Jan-10-1999 $535
Jan-11-1999 $320
Jan-12-1999 $750
and we want to find out all the dates where there are both store sales and internet sales. To do
so, we use the following SQL statement:

SELECT Date FROM Store_Information


INTERSECT
SELECT Date FROM Internet_Sales

Result:
Date
Jan-07-1999
Please note that the INTERSECT command will only return distinct values.

MINUS
The MINUS operates on two SQL statements. It takes all the results from the first SQL statement,
and then subtract out the ones that are present in the second SQL statement to get the final
answer. If the second SQL statement includes results not present in the first SQL statement,
such results are ignored.

The syntax is as follows:

[SQL Statement 1]
MINUS
[SQL Statement 2]

Let's continue with the same example:

Table Store_Information
store_name Sales Date
Los Angeles $1500 Jan-05-1999
San Diego $250 Jan-07-1999
Los Angeles $300 Jan-08-1999
Boston $700 Jan-08-1999
Table Internet_Sales
Date Sales
Jan-07-1999 $250
Jan-10-1999 $535
Jan-11-1999 $320
Jan-12-1999 $750
and we want to find out all the dates where there are store sales, but no internet sales. To do so,
we use the following SQL statement:

SELECT Date FROM Store_Information


MINUS
SELECT Date FROM Internet_Sales

Result:
Date
Jan-05-1999
Jan-08-1999
"Jan-05-1999", "Jan-07-1999", and "Jan-08-1999" are the distinct values returned from "SELECT
Date FROM Store_Information." "Jan-07-1999" is also returned from the second SQL
statement, "SELECT Date FROM Internet_Sales," so it is excluded from the final result set.

Please note that the MINUS command will only return distinct values.

Some databases may use EXCEPT instead of MINUS. Please check the documentation
for your specific database for the correct usage.

What is a View?
In SQL, a VIEW is a virtual table based on the result-set of a SELECT statement.

A view contains rows and columns, just like a real table. The fields in a view are fields from one or more real tables in the
database. You can add SQL functions, WHERE, and JOIN statements to a view and present the data as if the data were
coming from a single table.

Note: The database design and structure will NOT be affected by the functions, where, or join statements in a view.

Syntax
CREATE VIEW view_name AS
SELECT column_name(s)
FROM table_name
WHERE condition
Note: The database does not store the view data! The database engine recreates the data, using the view's SELECT statement,
every time a user queries a view.

Using Views
A view could be used from inside a query, a stored procedure, or from inside another view. By adding functions, joins, etc., to
a view, it allows you to present exactly the data you want to the user.

The sample database Northwind has some views installed by default. The view "Current Product List" lists all active products
(products that are not discontinued) from the Products table. The view is created with the following SQL:
CREATE VIEW [Current Product List] AS
SELECT ProductID,ProductName
FROM Products
WHERE Discontinued=No
We can query the view above as follows:
SELECT * FROM [Current Product List]
Another view from the Northwind sample database selects every product in the Products table that has a unit price that is
higher than the average unit price:
CREATE VIEW [Products Above Average Price] AS
SELECT ProductName,UnitPrice
FROM Products
WHERE UnitPrice>(SELECT AVG(UnitPrice) FROM Products)
We can query the view above as follows:
SELECT * FROM [Products Above Average Price]
Another example view from the Northwind database calculates the total sale for each category in 1997. Note that this view
selects its data from another view called "Product Sales for 1997":
CREATE VIEW [Category Sales For 1997] AS
SELECT DISTINCT CategoryName,Sum(ProductSales) AS CategorySales
FROM [Product Sales for 1997]
GROUP BY CategoryName
We can query the view above as follows:
SELECT * FROM [Category Sales For 1997]

You might also like