SQL Notes
SQL Notes
SQL NOTES
2
INTRODUCTION TO DBMS
Why DBMS: Human needs have increased tremendously. Now people are
doing much more composite tasks than ever before. The society has become very
complex. a person has to work with huge amount of information every day. In
order to work with the enormous information, we must have a system where we
can store, manipulate and share the information all over the world. It is one of the
core reasons for introducing Database Management Systems (DBMS) as well as
Relational Database Management Systems (RDBMS) now-a-days.
So, one thing is clear to us that we store and manipulate data / information into
a database, where the database contains various types of tables for storing
various types of data / information.
Data:
Whatever we are inputting from the keyboard is known as Data. It can
also be called as RAWFACTS / FIGURES
Data never provides any meaning for us
Information:
Processed Data is known as Information
Information always gives meaning for us
Database:
Collection of information belongs to a particular topic (an organization)
written in a predetermined manner stored at a particular place is called
as database.
Types of DBMS:
1) FMS / FDMS (File Management System /File Management Database
System):
This is first model released into the market in 1950‟s. In this model there is
always arranged in a continue stream of character (or) in a sequential
fashion (or) manner.
Disadvantages:
ROOT
Child Child
4
Drawback:
Only one person can share the database simultaneously
No security
Disadvantage:
There is no proper security for the centralized database
Redundancy of the database is increased
It occupies lot of memory and it leads to decrease system performance
and increase the inconsistency.
EMP EMPID
STUDENT HALL-NO
5
SQL
.Net
PHP Java
Vendor 1
P1
Vendor 2
P2
Vendor 3
P3
All information in the database is to be represented in one and only one way. This
is achieved by values in column positions within rows of tables.
All data must be accessible with no ambiguity, that is, Each and every datum
(atomic value) is guaranteed to be logically accessible by resorting to a
combination of table name, primary key value and column name.
Null values (distinct from empty character string or a string of blank characters and
distinct from zero or any other number) are supported in the fully relational DBMS
for representing missing information in a systematic way, independent of data
type.
The database description is represented at the logical level in the same way as
ordinary data, so authorized users can apply the same relational language to its
interrogation as they apply to regular data. The authorized users can access the
database structure by using common language i.e. SQL.
A relational system may support several languages and various modes of terminal
use. However, there must be at least one language whose statements are
expressible, per some well-defined syntax, as character strings and whose ability to
support all of the following is comprehensible:
7
a. data definition
b. view definition
c. data manipulation (interactive and by program)
d. integrity constraints
e. authorization
f. Transaction boundaries (begin, commit, and rollback).
All views that are theoretically updateable are also updateable by the system.
The system is able to insert, update and delete operations fully. It can also perform
the operations on multiple rows simultaneously.
Note that based on these rules there is no fully relational database management
system available today. In particular rules 6, 9, 10, 11 and 12 are difficult to
satisfy.
Features of RDBMS
Whenever we design ERD‟s the user has to follow the following symbols
Mb no P-ID
EID
Store s
Products Warehouse
Sales Representative
PName
Salary EName
Cost
Servi
ces
CID
MbNo
Customer Plac
es
OrderId
Features of SQL:
SQL is not a case sensitive language it means that all the commands of
Sql are not case sensitive
Every command of sql should ends with a semicolon (;) (It is exemption
for SQL Server)
SQL can be pronounced as Sequel (Structured English Query Language)
SQL can be called as Common Language Interface, which is used to
communicate with any type of database
SQL can be called as NLI (Natural Language Interface). It means that all
the SQL Commands are almost similar to normal English language
Structured query language is mainly divided into 4 sub languages
1. DDL (Data Definition Language)
2. DML (Data Manipulation Language)
3. TCL (Transaction Control Language)
4. DCL(Data Control Language)
SQL
1. Create:
This command is used to create the database objects within the database
Syntax: CREATE TABLE <TABLE NAME>
(COL 1 DATA TYPE (size),
COL2 DATA TYPE (size),
:
:
:
COLN DATA TYPE (size));
Ex: CREATE TABLE EMP (EID number, ENAME Varchar2
(15), SAL DECIMAL (6, 2));
2. ALTER:
a. ALTER-ALTER COLUMN:
3. RENAME:
This command is used to change the table name from old table name to
new table name
Syntax: Rename „old table name‟,‟ New table name‟
Ex: Rename „EMP‟,‟EMP1‟
4. TRUNCATE:
This command is used for to delete all the records from existing
table permanently
Syntax: TRUNCATE TABLE <TABLE NAME>
Ex: TRUNCATE TABLE EMP;
5. DROP:
This command is used to remove the table permanently from the database
Syntax: DROP TABLE <TABLE NAME>
Ex: DROP TABLE EMP;
Note: SP_help: This command is used to see the structure of table
1. Insert
2. Update
3. Delete
4. Select
1. INSERT:
Using this command we can Insert the records into the existing table
We can insert the records into the table in two methods
Explicit method
Implicit method
Explicit method:
In this method user has to enter all the values into all the columns
without anything omitting (or) left any column data
Syntax: INSERT INTO <TABLE NAME> VALUES <VAL1, VAL2,
….VALN>;
(OR)
INSERT <TABLE NAME> VALUES <VAL1, VAL2, .VALN>;
(Here “INTO” Keyword is optional)
Implicit method:
In this method we can enter the values into the required columns in the
table, so that user can omit (or) left some columns data while he enters the
records into the table
If the user omit any column data in the table then it automatically
takes NULL
Syntax: INSERT INTO <TABLE NAME> (COL1, COL2….COLN)
VALUES (VAL1, VAL2… VALN);
Ex: INSERT INTO EMP (EID, SAL) VALUES (106,9999);
2. UPDATE:
3. DELETE:
06 Truncate will reset the identity Delete will not reset the identity
Values value
4. SELECT:
Projection:
Selection:
WHERE CLAUSE:
ALIAS:
ALIAS is a duplicate name (or) alternate name for the original column
name (or) Table name (or) an expression name.
Ex: CREATE TABLE EMP (EID INT IDENTITY (100, 1), ENAME VARCHAR
(50));
19
ABS (): Returns the absolute, positive value of the given numeric expression.
CEILING (): Returns the smallest integer greater than, or equal to, the given
numeric expression.
Ex: select ceiling(15.000)- - -15
select ceiling(15.0001)- - -16
select ceiling(-12.34)-----(-12)
FLOOR (): Returns the largest integer less than or equal to the given numeric
expression.
SIGN (): Returns the positive (+1), zero (0), or negative (-1) sign of the given
expression.
SIN (): Returns the trigonometric sine of the given angle (in radians) in an
approximate numeric expression.
COS (): A mathematic function that returns the trigonometric cosine of the given
angle (in radians) in the given expression.
ASCII (): Returns the ASCII code value of the leftmost character of a character
expression.
CHAR (): A string function that converts an int ASCII code to a character.
LEFT (): Returns the left part of a character string with the specified number of
characters.
RIGHT (): Returns the right part of a character string with the specified number of
characters.
LEN (): Returns the number of characters, rather than the number of bytes, of the
given string expression.
UPPER (): Returns a character expression with lowercase character data converted
to uppercase.
RTRIM (): Returns a character string after truncating all trailing blanks.
REPLACE (): Replaces all occurrences of the second given string expression in
the first string expression with a third expression.
Ex: Select REPLACE („JACK AND JUE‟, „J‟, „BL‟) ------BLACK AND BLUE
22
SUM (): Returns the sum of all the values .Sum can be used with numeric columns
only. Null values are ignored.
AVG (): Returns the average of the values in a group. Null values are ignored.
COUNT (): Returns the number of records in a table. This function again use in
three ways.
Distinct Key: If we use this key word on a column with in a query then it will
retrieve the values of the column without duplicates.
24
1. Assignment operator
2. Arithmetic operator
3. Comparison operator
4. Logical operator
5. Set operator
Ex1: Write a Query to display the employee details whose salary is equal to10000
Select 245-400
Select 20*20
Select 25/5
Select 37%6
25
Select 20/5+20/5
Select 35.50+20
Step1: Create table student (Sid int, sname varchar (50), math‟s int, phy int, che
int, total int, average int, class varchar (max))
Case
Else
'Fail'
End
CASE (): This function is used to execute list of conditions and returns a value.
Syntax: Case
Else
<Statement>
End
26
Examples:
Logical operator: Logical operators test for the truth of some condition.
Logical operators, like comparison operators, return a Boolean data type with a
value of TRUE or FALSE. Logical operators are AND , OR , NOT, BETWEEN,
NOT BETWEEN, LIKE, NOT LIKE, IN, NOT IN, EXISTS,NOT EXISTS, ANY,
ALL, SOME.
Examples:
Write a Query to display the employee details whose salary is greater than
or equal to 9000 and less than 15000
SELECT * FROM EMP WHERE SAL>=9000 AND SAL<=15000
(OR)
SELECT * FROM EMP WHERE SAL BETWEEN 9000 AND 15000
Write a Query to display the employee details whose salary is not
between 9000 and 15000
SELECT * FROM EMP WHERE SAL NOT BETWEEN 9000 AND15000
Write a Query to display the employee details whose name starts with „r‟
SELECT * FROM EMP WHERE ENAME LIKE „r%‟
Write a Query to display the employee details whose name ends with „y‟
SELECT * FROM EMP WHERE ENAME LIKE „%Y‟
Write a Query to display the employee details whose names contain „r‟
and salary greater than 9000
SELECT * FROM EMP WHERE ENAME LIKE „%R%‟ AND SAL>9000
Write a Query to display the employee details whose greater than ram
SELECT * FROM EMP WHERE ENAME>‟RAM‟
Write a Query to display the employee details whose employee id starts
with 1 and ends with 1
SELECT * FROM EMP WHERE EID LIKE „1%1‟
(SQL commands are not case sensitive and also data available in SQL also not case
sensitive, in oracle Data available is case sensitive)
28
Write a query to change the deptno as 20 who does not have deptno
UPDATE EMPSET DEPTNO=20 WHERE DEPTNO IS NULL
Write a query to change the employee salaries as 8500 who are working
under 10 and 20 deptno
UPDATE EMPSET SAL=8500 WHERE DEPTNO=10 OR DEPTNO=20
(OR)
UPDATE EMPSET SAL=8500 WHERE DEPTNO IN(10,20)
Write a query to change the employee salaries as 8500 who are not working
under 10 and 20 deptno
UPDATE EMPSET SAL=8500 WHERE DEPTNO NOT IN (10,20)
Set Operators: Set operators combine results from two or more queries into a
single result set. SQL Server provides the following set operators.
UNION
UNION ALL
INTERSECT
minus
To combine the results of two queries we need to follow the below basic rules.
The number and the order of the columns must be the same in all queries.
The data types must be compatible(Well-Matched)
Example:
EMP_HYD
------------------------------------------------
EMP_CHENNAI
EID ENAME
101 SAI
105 POOJA
106 JASMIN
UNION: it combines the result of two or more select statements into a single result
set that includes all the records belongs to all queries except duplicate values.
Union
OUTPUT: ENAME
JASMIN
KAMAL
NEETHU
POOJA
SAI
SIDDHU
31
Union ALL
OUTPUT: ENAME
SAI
SIDDHU
KAMAL
NEETHU
SAI
POOJA
JASMIN
INTERSECT: INTERSECT returns any distinct values that are common in left
and right tables.
Intersect
OUTPUT: ENAME
SAI
32
Minus: Minus returns any distinct values from the left query that are not found
on the right query.
Except
OUTPUT: ENAME
KAMAL
NEETHU
SIDDHU
Except
OUTPUT: ENAME
JASMIN
POOJA
WHERE: This clause is used for filter or restricts the records from the table.
Ex: SELECT * FROM EMP WHERE SAL=10000
ORDER BY: The order by clause is used to sort or arrange the data in
ascending or descending order with in table. By default order by
clause arrange or sort the data in ascending order only.
33
Ex: SELECT * FROM EMP ORDER BY ENAME DESC (For Descending Order)
TOP N CLAUSE: This clause is used to fetch a top n number of records from a
table.
GROUP BY: Group by clause will use for to arrange similar data into groups.
when we apply group by clause in the query then we use group functions like
count(),sum(),max(),min(),avg().
If we use group by clause in the query, first the data in the table will be divided
into different groups based on the columns and then execute the group function on
each group to get the result.
Ex1: WAQ to find out the number of employees working in the organization
Ex2: WAQ to find out the number of employees working in each group in the
organization.
Ex3: WAQ to find out the total salary of each department in the organization
HAVING CLAUSE: Having clause is also used for filtering and restricting the
records in a table just like where clause.
Ex: WAQ to find out the number of employees in each department only if the
count is greater than 3
Syntax: Select * into <New Table Name> from <Old Table Name>
In this case it creates a table New_Emp by copying all the rows and columns of the
Employee table.
In this case it creates a table Test_Emp with only the specified columns from the
employee table.
In this case it creates the Dummy table without any data in it.
36
Syntax: Insert into <Dummy Table name> select * from <Table Name>
Constraint in SQL
Why Constraint in SQL: Constraint is using to restrict the insertion of
unwanted data in any columns. We can create constraints on single or multiple
columns of any table. It maintains the data integrity i.e. accurate data or original
data of the table. Data integrity rules fall into three categories:
Entity integrity
Referential integrity
Domain integrity
Domain Integrity: Domain integrity ensures the data values inside a database
follow defined rules for values, range, and format. A database can enforce these
rules using CHECK KEY constraints.
1. Unique Key:- Unique key constraint is use to make sure that there is no
duplicate value in that column. Both unique key and primary key both enforces
the uniqueness of column but there is one difference between them unique key
constraint allow null value but primary key does not allow null value.
In a table we create one primary key but we can create more than one unique key
in Sql Server.
2. Not null constraint: - Not null constraint is used to restrict the insertion of
null value at that column but allow duplicate values.
4. Primary Key:- Primary key is a combination of unique and not null which
does not allow duplicate as well as null values into a column. In a table we create
one primary key only.
In order to create a link between two tables we must specify a foreign key in one
table that references a column in another table.
Foreign key constraint is used for relating or binding two tables with each other
and then verifies the existence of one table data in the other.
We require two tables for binding with each other and those two tables must have a
common column for linking the tables.
Example:
When we impose the foreign key constraint and establish relation between the
table,the followiong three rules will come into picture.
Rule1:- Cannot insert a value into the foreign key column provided that value is
not existing under the refernce key column of the parent table.
Rule2:- Cannot update the reference key value of a parent table provided that
value has corresponding child record in the child table with out addressing what
to do with the child record.
Rule3:- Cannot delete a record from the parent table provided that records
reference key value has child record in the child table with out addressing what to
do with the child record.
If we want to delete or update a record in the parent table when they have
corresponding child records in the child table we are provide with a set of rules to
perform delete and update operations knows as cascade rules.
On delete cascade:- It is used to delete a key value in the parent table which is
referenced by foreign key in other table all rows that contains those foreign keys in
child table are also deleted.
40
On Update cascade:- It is used to Update a key value in the parent table which is
referenced by foreign key in other table all rows that contains those foreign keys
in child table are also updated.
If we apply this rule while creating the child table like below
Ex:-
Create table CUSTOMER (CID Int primary key, CNAME Varchar (20),
MAILID Varchar (40))
CASE-2
Create table PRODUCTS (PCODE Int primary key, PNAME varchar (50),
PRICE money)
---------------------------------------------------------------------------
CASE-3
Create table ORDERS (ORID Int primary key, ORDATE date, QUANTITY
int,CID Int foreign key references CUSTOMER(cid) on update cascade on
41
----------------------------------------------------------
Ex: CREATE TABLE EMPLOYEE (EID INT, ENAME VARCHAR (50), SALARY MONEY)
Note: Before adding primary key constraint make the column is not
null later add primary key like below.
Ex: ALTER TABLE EMPLOYEE ALTER COLUMN EID INT NOT NULL
Ex: ALTER TABLE EMPLOYEE ADD CONSTRAINT X PRIMARY KEY (EID) (Here ‘x’ is
constraint variable)
Ex: ALTER TABLE DEPT ADD CONSTRAINT Y FOREIGN KEY (EID) REFERENCES
EMPLOYEE (EID) ON UPDATE CASCADE ON DELETE CASCADE
JOINS IN SQL: Joins are used for retrieving the data from more than one
table at a time. Joins can be classified into the following types.
EQUI JOIN
INNER JOIN
OUTER JOIN
LEFT OUTER JOIN
RIGHT OUTER JOIN
FULL OUTER JOIN
NON EQUI JOIN
SELF JOIN
CROSS JOIN
NATURAL JOIN
EQUI JOIN: If two or more tables are combined using equality condition then
we call as an Equi join.
Ex: WAQ to get the matching records from EMP and DEPT tables
INNER JOIN: Inner join return only those records that match in both table
OUTTER JOIN: It is an extension for the Equi join. In Equi join condition we
will be getting the matching data from the tables only. So we loss UN
matching data from the tables.
To overcome the above problem we use outer join which are used to getting
matching data as well as UN matching data from the tables. This outer join again
classified into three types
LEFT OUTER JOIN: It will retrieve or get matching data from both table as well
as UN matching data from left hand side table
RIGHT OUTER JOIN: It will retrieve or get matching data from both table as
well as UN matching data from right hand side table
FULL OUTER JOIN: It will retrieve or get matching data from both table as well
as UN matching data from left hand side table plus right hand side table also.
NON EQUI JOIN: If we join tables with any condition other than equality
condition then we call as a non Equi join.
SELF JOIN: Joining a table by itself is known as self join. When we have some
relation between the columns within the same table then we use self join.
When we implement self join we should use alias names for a table and a table
contains any no. of alias names.
44
CROSS JOIN: Cross join is used to join more than two tables without any
condition we call as a cross join. In cross join each row of the first table join with
each row of the second table.
So, if the first table contain „m‟ rows and second table contain „n‟ rows then output
will be „m*n‟ rows.
EX: SELECT EID, ENAME, SALARY, DNO, DNAME FROM EMP E, DEPT D
WHERE E.EID=D.DNO
CREATE TABLE COURSES (CID int, CNAME Varchar (20), CFEE decimal (6, 2))
---------------------------------------------------------------------------------------------------------
45
Select * from course c inner join student s on c.cid=s.cid inner join register r on
s.cid=r.cid
Select * from student s left outer join course c on s.cid=c.cid left outer join
register r on c.cid=r.cid
COMMIT
ROLLBACK
SAVE POINT
46
COMMIT: Commit command is used to end the transaction and save the data
permanent part of the database (or) it is used to make the transaction is permanent
so we cannot undo or recall the records.
Commit is used for saving the data that has been changed permanently
because whenever you perform any DML (Data Manipulation Language)
like UPDATE, INSERT OR DELETE then you are required to write
Commit at the end of all or every DML operation in order to save it
permanently.
If you do not write Commit then your data will be restored into its
previous condition.
Ex:
INSERT INTO EMPLOYEE VALUES(105,'KAMAL',62000,'MUMBAI')
INSERT INTO EMPLOYEE VALUES(106,'SUJATHA',82000,'DELHI')
COMMIT
The above records are stored permanently into a table because we commited
that records.so we cannot roll back in to its previous position.
ROLLBACK: Rollback command is used to undo the transactions and gets back
to the initial state where transaction started.
Whereas if you want to restore your data into its previous condition
then you can write Rollback at any time after the DML queries has
been written but remember once Commit has been written then you
cannot rollback the data.
Moreover you can only rollback the DML queries that have been
written after the last commit statement. The concept of commit and
rollback is designed for data consistency because many users
manipulate data of the
47
same table, using the same database so the user must get updated
data. That is why commit and rollback are used.
Ex:
DELETE FROM EMPLOYEE WHERE EID=105
DELETE FROM EMPLOYEE WHERE EID=106
ROLLBACK
The above records we can rollback into a table because those records are not
commited.
SAVEPOINT: Save point is used for dividing (or) breaking a transaction into
multiple units. So that user will have a chance of roll backing a transaction up to a
location.
When a user sets a save point with in a transaction the save point defines
a location to which a transaction can return if part of the transaction
conditionally canceled.
If a transaction is roll back to a save point, it must be proceed to
completion of the transaction with commit statement or it must be
cancelled altogether by rolling the transaction back to its beginning
Syntax:
Save transaction < transaction name>
<Write Statements>
Ex:
UPDATE EMPLOYEE SET SALARY=99000 WHERE EID=101
UPDATE EMPLOYEE SET SALARY=88000 WHERE EID=102
SAVE TRANSACTION S1
UPDATE EMPLOYEE SET SALARY=77000 WHERE EID=103
UPDATE EMPLOYEE SET SALARY=66000 WHERE EID=104
SAVE TRANSACTION S2
UPDATE EMPLOYEE SET SALARY=55000 WHERE EID=105
UPDATE EMPLOYEE SET SALARY=44000 WHERE EID=106
48
In the above case we are dividing or breaking the transaction into three
units.so we have a chance of rollbacking either completely i.e six
statements get roll back (or) roll back save point S1 i.e four statements(103
to 106) (or) rollback save point S2 i.e two records (105,106 ) only
CASE 1: ROLLBACK
All records will roll back i.e complete records(six records)
CASE 2:
ROLLBACK TRANSACTION S1
CASE 3:
ROLLBACK TRANSACTION S2
We can roll back two records only i.e 105 and 106
Sub Query: A select query contains another select query is called sub Query.
In this, there will be two queries those are called as inner query and outer query.
When it is executed, first inner query is executed later outer query will be executed
Examples:
1) WAQ to find the details of employee who is earning the highest salary.
2) WAQ to find the details of employee who is earning second highest salary.
3) WAQ to find the details of employee who is earning third highest salary.
Sol: select * from employee where EID IN (select EID FROM employee where
DNAME='.NET')
Sol: select * from employee where EID IN (select EID FROM employee where
DNAME='.NET' OR DNAME='HR')
Outer query will execute first and value of the outer query will be used
by co- related sub query i.e. inner query.
When outer query is executed then the copy of the table will be stored in
memory, later co related sub query will check the values and will give Ranks
to the outer query rows in the memory ,according to the ranks the result
will be displayed.
Note: - To find Top n salaries list use “n>”.To find nth highest salary use “n-1”.
Examples:
6) WAQ to display top 2 salaries list from employee table.
(Or)
Note: - Here Distinct Key will be used when the table contain duplicate values.
(Or)
Sol: Select * from employee E where 0=(select count( salary) from employee
M where M.salary>E.salary)
least salary
51
9) WAQ to get the details of the department in which employee are working.
Syntax to Delete Duplicate Records from a table contains more than two same
duplicate values:
with duplicates as
(select * ,ROW_NUMBER() over(partition by sid,sname, fee order by
sid,sname,fee) rownum from student)
delete from duplicates where rownum > 1
select the complete above query and execute then we delete all duplicate records
which are greater than 1 i.e.output is like below
52
INDEXES IN SQL:
Why We Need Indexes:
1. Generally a library has a huge collection of books, files, etc... A student
requests the librarian for a book of Microsoft SQL Server 2008, if we think
without an index the librarian had to find this without any help she/he has
to search one by one! This must be time consuming; so with a proper
arrangement, that is with the help of an index, it very much easier and faster
to find out the desired one.
2. One of the most important routes to high performance in a SQL Server
database is the index. Indexes speed up the querying process by providing
quickly access to rows in the data tables, similarly to the way a book‟s index
helps you find information quickly within that book.
What is INDEX:
Index is a database object which is used for the quick retrieving of the
data from the table.
An index contains keys built from one or more columns in the table and
map to the storage location of the specified data.
By using indexes we can save time and can improve the performance
of database queries and applications.
When we create an indexes on any column, SQL server internally maintain a
separate table called index table. So that when ever user trying to retrieve
the data from existing table depends on index table SQL server directly go to
the table and retrieve required data very quickly.
53
In a table we can use max 250 indexes. The index type refers to the way the
index is stored internally by SQL Server. So a table can contain the two
types of indexes.
1. Clustered
2. Non-Clustered
Clustered Index:
The only time the data rows in a table are stored in sorted (ascending order
only) order structure is when the table contains a clustered index. When a
table has a clustered index then is called a clustered table. If a table has no
clustered index, its data rows are stored in an unordered structure.
A table can have only 1 clustered index on it, which will be created when
primary key constraint is used in a table.
Non-Clustered Indexes:
Non-clustered indexes will not have any arrangement order (Unordered
structure) of the data in the table. In a table we can create 249 non-clustered
indexes.
If we don‟t mention clustered indexes in a table then default is stored as
non- clustered indexes.
VIEWS IN SQL: View is database object which is like table but logical.
We can call it as a logical or virtual table because it does not has a physical
existence.
It is a logical table use to get the required information from the table.
View will be created by using select statement and table used for the
creation of the view is called as base table.
View will not store records in it and will not occupy memory space
with help of structure existing in it and records will be displayed from
table.
54
View is created based on a table any changes that are performed on the table
reflects into the view any changes performed on the view reflect into the table also.
View is classified into two types. These are
Simple view: we create a view based on one table is called simple view or
Updatable view.
Complex view: we create a view based on more than one table is called complex
view or Non-Updatable view.
55
SQL SEQUENCES
A sequence is a user defined schema bound object that generates a sequence of numeric
values.
Sequences are frequently used in many databases because many applications require each
row in a table to contain a unique value and sequences provides an easy way to generate them.
The sequence of numeric values is generated in an ascending or descending order at
defined intervals and can be configured to restart when exceeds max_value.
Syntax:
Example 1:
Above query will create a sequence named sequence_1.Sequence will start from 1 and will be incremented by 1 having
maximum value 100. Sequence will repeat itself from start value after exceeding 100.
Example 2:
Following is the sequence query creating sequence in descending order.
Above query will create a sequence named sequence_2.Sequence will start from 100 and should be less than or equal to
maximum value and will be incremented by -1 having minimum value 1.
Example to use sequence : create a table named students with columns as id and name.
Output:
______________________
| ID | NAME |
------------------------
| 1 | Ramesh |
| 2 | Suresh |
Decode:
The Oracle/PLSQL DECODE function has the functionality of an IF-THEN-ELSE statement.
Syntax
The syntax for the DECODE function in Oracle/PLSQL is:
Parameters or Arguments
expression
The value to compare. It is automatically converted to the data type of the first search value before comparing.
search
The value that is compared against expression. All search values are automatically converted to the data type of
the first search value before comparing.
result
The value returned, if expression is equal to search.
default
Optional. If no matches are found, the DECODE function will return default. If default is omitted, then the DECODE
function will return NULL (if no matches are found).
Returns
The DECODE function returns a value that is the same datatype as the first result in the list.
If the first result is NULL, then the return value is converted to VARCHAR2.
If the first result has a datatype of CHAR, then the return value is converted to VARCHAR2.
If no matches are found, the default value is returned.
If default is omitted and no matches are found, then NULL is returned.
59
Applies To
Example
The DECODE function can be used in Oracle/PLSQL.
You could use the DECODE function in a SQL statement as follows:
SELECT supplier_name,
DECODE(supplier_id, 10000, 'IBM',
10001, 'Microsoft',
10002, 'Hewlett Packard',
'Gateway') result
FROM suppliers;
ELSE
result := 'Gateway';
END IF;
The DECODE function will compare each supplier_id value, one by one.
60
In this format, we evaluate one expression against multiple values. In a simple case statement, it evaluates
conditions one by one. Once the condition and expression is matched, it returns the expression mentioned in
THEN clause.
We have following syntax for a case statement in SQL with a simple expression
...
ELSE Result
END
CASE Syntax
CASE
WHEN condition1 THEN result1
WHEN condition2 THEN result2
WHEN conditionN THEN resultN
ELSE result
END;
The following SQL goes through conditions and returns a value when the first condition is met:
SELECT OrderID, Quantity,
CASE
WHEN Quantity > 30 THEN "The quantity is greater than 30"
WHEN Quantity = 30 THEN "The quantity is 30"
ELSE "The quantity is under 30"
END AS QuantityText
FROM OrderDetails;
The following SQL will order the customers by City. However, if City is NULL, then order by Country: