Upload
chetan-belagali
View
239
Download
0
Embed Size (px)
Citation preview
8/8/2019 Chetan SQL Learns
1/21
Session: Each connected User with Oracle Instance is considered
as one Session.
Instance: All users interact with Instance to retrieve or store
information.
Database: Is like the notebook where Oracle Instance writes theinformation and is encrypted.
SQL commands are used to store and retrieveinformation.SQL is the language that
we will be using to communicate with the Instance.
PL/SQL is the
superset of SQL i.e. we use PL/SQL instead of SQL when our
target/goal requires multiple SQL commands to be executed
based on certain logic, event or condition then we take the
benefit of this language
SQL*Plus is basically the environment where we write SQL or
PL/SQL commands. In other words its a front end tool we use
to communicate with Oracle Instance.
iSQL*Plus is the exact same product as that of SQL*Plus
except that its the web version of SQL*Plus.
It can be accessed
with a URL having following pattern
http://machine_name:5560/isqlplus
Before accessing this URL, execute the following command
which will start the iSQL*Plus application server.
Isqlplusctl start
What are SQL Statements/Commands?
SQL is nothing but a set of statements (commands) and are
categorized into following five groups viz., DQL: Data Query
Language, DML: Data Manipulation Language, DDL: Data
Definition Language, TCL: Transaction Control Language,
DCL: Data Control Language.
The commands falling in each of these categories are shown in
the following table.DQL SELECT
DML DELETE, INSERT, UPDATEDDL CREATE, DROP, TRUNCATE, ALTER
TCL COMMIT, ROLLBACK, SAVEPOINT
DCL GRANT, REVOKE
8/8/2019 Chetan SQL Learns
2/21
SQL Operators grouped together into four groups.
NULL is a special value and
just keep in mind that its not Zero. It can be visualized as empty
field occupying zero byte.
Single Row function
as the name states gets implemented on single records whereas
Group functions get implemented on the multiple records. These
functions will get clarified in your mind once we start discussing
one by one.
8/8/2019 Chetan SQL Learns
3/21
What are SQL Joins?
Joins help in extracting data from two or more tables based on
some condition specified in the WHERE clause
There are following
different kinds of Joins and each having its own application. Outof these, two are having extremely high importance viz., Equi-
Join and Outer-Join.
Self Joins
Cartesian Products
Equijoins
Outer Joins
Self Join
A self join is a join of a table to itself.
Cartesian Product
If in the Join statement you forget to put the WHERE condition
or intentionally dont write the WHERE clause at all, the result
will be Cartesian product. Such type of output will be very rarel
8/8/2019 Chetan SQL Learns
4/21
useful. If one table had five records and other one had six
records; in the output you will get thirty records (5x6=30).
Thats why we use the word product with such type of join.
8/8/2019 Chetan SQL Learns
5/21
Constraints also known as Data Integrity Constraints
NOT NULL is a type of constraint once implemented on any
column; you would not be able to insert NULL values in it.
Similarly with UNIQUE, once defined on any column we wouldnot be able to insert any record in the table with a value that was
already there in UNIQUE constraint column
On the other hand, CHECK constraint is called customconstraint. You have given the liberty to create or define the
constraint according to your needs.
Example:
CREATE TABLE suppliers
( supplier_id numeric(4),
supplier_name varchar2(50),
CONSTRAINT check_supplier_id
CHECK (supplier_id BETWEEN 100 and 9999));
Similarly in this case too Oracle Instance will make sure that
before inserting or updating any information into this suppliers
table, the supplier_id lies between 100 and 9999. If it doesnt
then the user will get a constraint violation error and the
request will not get processed.
8/8/2019 Chetan SQL Learns
6/21
Lets now talk about Primary Key constraint. Once you
implement this constraint on any column, you will not be able to
insert duplicate and NULL value i.e. each value in that column
68
will be a unique identifier for that whole record/row. MoreoverOracle creates an implicit index on that column
Figure 2-18: Difference between Joining and Linking. Joining is at thequery level whereas linking is a physical link between tables. Joins
statements can be executed on tables having Referential Integrity
constraint or not. The word Join should not be confused with as I if
you are joining the two tables permanently.
8/8/2019 Chetan SQL Learns
7/21
------------------------------------------------------------------------------------------------
SELECT identifies the columns to bedisplayed.
FROM identifies the table containing thosecolumns.
Defining a Null Value A null is a value that is unavailable,unassigned, unknown,or inapplicable. A null is not the same as a zero or a blankspace.
8/8/2019 Chetan SQL Learns
8/21
Defining a Column AliasA column alias: Renames a column heading Requires double quotation marks if itcontains spaces orspecial characters, or if it is case-sensitive
Character Strings and Dates Character strings and date values areenclosed in singlequotation marks. Character values are case sensitive, and
date values areformat sensitive. The default date format is DD-MON-RR.
Comparison Conditions
Operator Meaning
Not equal toBETWEEN Between two values (inclusive)...AND...
8/8/2019 Chetan SQL Learns
9/21
IN(set) Match any of a list of valuesLIKE Match a character patternIS NULL Is a null value
< Less than= Greater than or equal to> Greater than= Equal to
.
Logical Conditions
NOT
Returns TRUE if the following condition isfalse
ORReturns TRUE ifeithercomponent conditionis true
AND
Returns TRUE ifboth component conditionsare true
Using the ORDER BYClause Sort retrieved rows with the ORDER BYclause:
8/8/2019 Chetan SQL Learns
10/21
ASC: ascending order, default DESC: descending order
The ORDER BY clause comes last in theSELECT
statement:
3 - 11 Copyright 2009, Oracle. All rights reserved.
Character-Manipulation FunctionsThese functions manipulate characterstrings:REPLACE BLACK and BLUE
('JACK and JUE','J','BL')
LENGTH('HelloWorld') 10
INSTR('HelloWorld', 'W') 6
LPAD(salary,10,'*') *****24000RPAD(salary, 10, '*') 24000*****
CONCAT('Hello', 'World') HelloWorld
TRIM('H' FROM 'HelloWorld') elloWorld
SUBSTR('HelloWorld',1,5) Hello
Function Result
Pageno 107
NVL FunctionConverts a null value to an actual value:
8/8/2019 Chetan SQL Learns
11/21
Types of Group Functions AVG
COUNT MAX MIN STDDEV SUM VARIANCE
The UNION operator returns resultsfrom bothqueries after eliminating duplications.
The UNION ALL operator returnsresults from bothqueries, including all duplications.
The INTERSECT operator returns rowsthat are
common to both queries.
The MINUS operator returns rows in thefirst query
8/8/2019 Chetan SQL Learns
12/21
that are not present in the second query.
Pageno 236
DELETE Statement
8/8/2019 Chetan SQL Learns
13/21
You can remove existing rows from a tableby using theDELETE statement:Specific rows are deleted if you specify theWHERE clause All rows in the table are deleted if you omitthe WHEREclause:
TRUNCATE Statement Removes all rows from a table, leaving thetable emptyand the table structure intact Is a data definition language (DDL)
statement rather than aDML statement; cannot easily be undone
State of the Data AfterCOMMIT Data changes are made permanent in thedatabase.
The previous state of the data ispermanently lost. All users can view the results. Locks on the affected rows are released;those rows are
8/8/2019 Chetan SQL Learns
14/21
available for other users to manipulate. All savepoints are erased.
Database ObjectsTable:- Basic unit of storage; composed of rows
View:- Logically represents subsets of data from one ormore tables
Sequence:- Generates numeric values
Index:- Improves the performance of some queries
Synonym:- Gives alternative names to objects
Naming RulesTable names and column names: Must begin with a letter Must be 130 characters long Must contain only AZ, az, 09, _, $, and#
Must not duplicate the name of anotherobject owned bythe same user
8/8/2019 Chetan SQL Learns
15/21
Must not be an Oracle serverreservedword
FOREIGN KEYConstraint:Keywords FOREIGN KEY: Defines the column in thechild table at thetable-constraint level
REFERENCES: Identifies the table andcolumn in the parenttable ON DELETE CASCADE: Deletes thedependent rows in thechild table when a row in the parent table is
deleted ON DELETE SET NULL: Convertsdependent foreign keyvalues to null
Dropping a Table
8/8/2019 Chetan SQL Learns
16/21
All data and structure in the table aredeleted. Any pending transactions are committed. All indexes are dropped. All constraints are dropped. You cannotroll back the DROP TABLEstatement.
Advantages of ViewsTo restrict data accessTo make complex queries easyTo provide data independenceTo provide data independence
IndexesAn index: Is a schema object Can be used by the Oracle server to
speed up the retrievalof rows by using a pointer Can reduce disk I/O by using a rapid pathaccess method
8/8/2019 Chetan SQL Learns
17/21
to locate data quickly Is independent of the table that it indexes Is used and maintained automatically bythe Oracle server
How Are Indexes Created? Automatically: A unique index is createdautomaticallywhen you define a PRIMARY KEY orUNIQUE constraint ina table definition. Manually: Users can create nonuniqueindexes oncolumns to speed up access to the rows.
Pageno 375
Cartesian Products A Cartesian product is formed when:
8/8/2019 Chetan SQL Learns
18/21
A join condition is omitted A join condition is invalid All rows in the first table are joined to all rows
in the secondtable
To avoid a Cartesian product, alwaysinclude a valid joincondition in a WHERE clause.
Pageno 52(2)
Cascading Constraints The CASCADE CONSTRAINTS clause isused along withthe DROP COLUMN clause. The CASCADE CONSTRAINTS clausedrops all referential
integrity constraints that refer to the primaryand uniquekeys defined on the dropped columns.
8/8/2019 Chetan SQL Learns
19/21
The CASCADE CONSTRAINTS clause alsodrops allmulticolumn constraints defined on thedropped columns.
Pageno 44(2)
{Copying Rows from AnotherTable Write yourINSERT statement with asubquery.
INSERT INTO sales_reps(id, name, salary,commission_pct)
SELECT employee_id, last_name, salary,commission_pctFROM employeesWHERE job_id LIKE '%REP%';33 rows inserted.
Do not use the VALUES clause.
Match the number of columns in theINSERT clause withthat in the subquery.}
8/8/2019 Chetan SQL Learns
20/21
Overview of Multitable INSERTStatements
INSERT ALLINTO table_a VALUES(,,)INTO table_b VALUES(,,)INTO table_c VALUES(,,)
{MERGE Statement Syntax
You can conditionally insert or update rowsin a table by usingthe MERGE statement.
^Pageno 85(2) ^}
8/8/2019 Chetan SQL Learns
21/21