SQL Notes
SQL Notes
1
DATA DEFINITION LANGUAGE
DATA DEFINITION LANGUAGE:
DDL is Auto Commit, it is Data Definition Language which is used to define the data structures.
It is used to create and modify the structure of database objects in a database. These database objects
include views, schemas, tables, indexes, etc.
A schema is the collection of multiple database objects, which are known as schema objects. These objects
have direct access by their owner schema
DDL STATEMENTS:
CREATE
ALTER
RENAME
DROP
TRUNCATE
CREATE:
It is used to create tables in the database.
CREATE TABLE STUDENTS (SID NUMBER (4), SNAME VARCHAR2 (30), RESUME LONG, EMAIL VARCHAR2(30),
DOB DATE);
ALTER:
It is used to add, drop, rename and modify a column in a table.
ADD COLUMN:
ALTER TABLE STUDENTS ADD ADDRESS VARCHAR (100);
2
RENAME TABLE:
RENAME COURSES TO SUBJECT;
A datatype associates a fixed set of properties with the values that can be used in a column of a table or in
an argument of a procedure or function. It also specifies the possible values for that type, the operations
that can be performed on that type and the way the values of that type are stored.
Number
Char
Varchar
Long
Clob
Blob
Date
Timestamp
Bfile
XML type
Number:
Maximum length up to 38 spaces (Default length)
Char:
Maximum length up to 2000 spaces (Alpha, Numbers, Special characters), Unused spaces will not get
released.
Varchar:
Maximum length up to 4000, Unused spaces will get released.
3
Long:
Maximum length up to 2 GB. In a table only one Long datatype can be used
Clob:
Character large object, Maximum length up to 4 GB.
Blob:
Binary large object, Maximum capacity up to 8 GB.
Date:
Date can be stored in this datatype in the format ‘DD-MON-YY’.
Timestamp:
Both Date & Time can be stored in this datatype.
Bfile:
To store the file path in the server
Xml type:
To store the XML type of files
4
DATA MANIPULATION LANGUAGE
Data manipulation Language:
DML is Manual Commit. A data manipulation language (DML) is a computer programming language used for
adding inserting, deleting, and modifying (updating) data in a database and permitting users to manipulate
data in a database.
Insert
Update
Delete
Merge
INSERT:
UPDATE:
UPDATE statement updates (changes the values of) a set of existing table rows.
DELETE:
Insert:
Insert into course(cid,cname) values(10,’SQL’);
To check:
Select * from course;
Insert ALL:
Insert all into course(cid,cname) values(20,’PLSQL’)
Into course(cid,cname) values(30,’SAS’)
5
Delete the row:
Delete from course where cid=40;
6
TRANSACTION CONTROL LANGUAGE
TCL stands for Transaction Control Languages. These commands are used for maintaining consistency of
the database and for the management of transactions made by the DML commands.
Commit
Rollback
Save point
COMMIT, which ends the current transaction, makes its changes permanent, erases its savepoints,
and releases its locks.
ROLLBACK, which rolls back (undoes) either the entire current transaction or only the changes
made after the specified savepoint.
Commit:
Committing a transaction makes its changes permanent, erases its savepoints, and releases its locks.
Syntax : Commit;
Rollback:
Rolling back a transaction undoes its changes. We can roll back the entire current transaction, or you can
roll it back only to a specified savepoint.
Syntax : Rollback;
Savepoint:
The SAVEPOINT statement marks a savepoint in a transaction—a point to which you can later roll back.
Savepoints are optional, and a transaction can have multiple savepoints.
Savepoint is a marker
Partial rollback
Syntax : Savepoint X;
7
Table T1
Column A
1
2
Savepoint x;
3
4
Savepoint y;
5
6
Rollback to y;
Commit;
8
SINGLE ROW FUNCTIONS
Single-row functions return a single result row for every row of a queried table or view.
UPPER CASE
LOWER CASE
INITIAL CHARACTER UPPERCASE
Lower – Lowercase
Initcap - 1st character capital
CHARACTER MANIPULATION FUNCTIONS
Length:
To find LENGTH Of the string
SELECT FIRST_NAME, LENGTH(FIRST_NAME) FROM EMPLOYEES;
Length displays no of characters in each row for that column
Sub string:
FIRST 3 CHARACTERS IN O/P, STARTING POSITION, LENGTH
SELECT FIRST_NAME, SUBSTR(FIRST_NAME,1,3) FROM EMPLOYEES;
10
TRIM:
TRIM function trims the string input from the start or end.
ROUND
TRUNC
MOD
SIGN
ABS
ROUND:
TO ROUNDOFF THE GIVEN VALUE
0.5 and above .5 rounded to next digit
SELECT ROUND(1.9) FROM DUAL;
Returns : 2
TRUNC:
TO REMOVE THE VALUES AFTER DECIMAL
SELECT TRUNC(1.9) FROM DUAL;
MOD:
TO FIND THE REMINDER
SELECT MOD(5,2) FROM DUAL;
11
SIGN:
It gives -1 for less than 0 value, It gives 1 for greater than 0 value
Months_between
Add_months
Next_day
Last_day
12
NEXT DAY:
TO FIND SOME NEXT DAY
13
TO FIND LEAST VALUE
SELECT LEAST (4,1,2) FROM DUAL;
14
For example, examine the below SELECT queries. Both the queries will give the same result because Oracle
internally treats 15000 and '15000' as same.
Query-1
SELECT employee_id,first_name,salary
FROM employees
WHERE salary > 15000;
Query-2
SELECT employee_id,first_name,salary FROM employees WHERE salary > '15000';
Explicit conversions
You can explicitly specify datatype conversions using SQL conversion functions. SQL functions that
explicitly convert a value from one datatype to another.
Oracle provides three functions to covert from one data type to another.
1. To_CHAR ( number | date, [fmt], [nlsparams] )
The TO_CHAR function converts the number or date to VARCHAR2 data type in the specified format (fmt).
The nlsparams parameter is used for number conversions. The nlsparams specifies the following number
format elements decimal character
Group separator
If the parameters are omitted, then it uses the default formats specified in the session.
15
DY: Three letter representation of the day of the week
9: Specifies numeric position. The number of 9's determine the display width.
.: Decimal position
16
GROUP FUNCTIONS
Group Functions:
Group functions are also known as multiple row functions or aggregate functions. It performs the calculation
on set of values and return a single value.
Commonly used functions:
MIN
MAX
AVG
SUM
COUNT
Conditions to use group functions:
Group function accepts only one argument, Error occurs if we give more than one argument
Group function ignores null values
MIN, MAX & COUNT - These functions accept all data types like string, number & date
AVG & SUM – These functions accept numbers only
We can use (*) symbol with count function only, so that the result will come with all null values
Group by clause need to used when using multiple columns with group function
Having clause need to be used when using conditions with group function
Basic Syntax:
To find max, min, avg, sum, count salary in a table
SELECT MAX(SALARY), MIN(SALARY), AVG(SALARY), SUM(SALARY), COUNT(SALARY) FROM EMPLOYEES;
17
Total Count:
SELECT COUNT(*) FROM T1;
18
SET OPERATORS
Set Operators:
Set operators are used to join the results of two or more SELECT statements.
Union
Union all
Intersect
Minus
Conditions for using set operators:
Column data type must be same in queries, otherwise result will be in error.
Number of columns used in query must be same.
Order by columns must be used in last select statement only.
It can't be used in SELECT statements containing TABLE collection expressions.
Column heading can be change using alias ‘AS’.
The LONG, BLOB, CLOB, BFILE, VARRAY or nested table are not permitted for use in Set operators.
For update clause is not allowed with the set operators.
We can use more than 2 select statements, Then the order of execution will be from top to bottom
only. We can use parentheses to change the order of execution.
UNION:
When multiple SELECT queries are joined using UNION operator, It displays the data from the both queries
and eliminates the duplicate rows and display data in ascending order by default.
Syntax:
SELECT A FROM T1
UNION
SELECT B FROM T2;
If A column contains values 1,2,3,4 in T1 table and B column contains values 1,2,3,5.
Returns output 1,2,3,4,5 and displays under the column A.
UNION ALL:
When multiple SELECT queries are joined using UNION ALL operator, It displays the data from the both
queries and including the duplicate rows and display data in same order as like in the table.
Syntax:
SELECT A FROM T1
UNION ALL
SELECT B FROM T2;
If A column contains values 1,2,3,4 in T1 table and B column contains values 1,2,3,5.
Returns output 1,2,3,4,1,2,3,5 and displays under the column A.
19
INTERSECT:
Using INTERSECT operator, It displays the common rows from both the SELECT statements, Eliminating the
duplicate rows and data arranged in ascending order by default.
Syntax:
SELECT A FROM T1
UNION ALL
SELECT B FROM T2;
If A column contains values 1,2,3,4 in T1 table and B column contains values 1,2,3,5.
Returns output 1,2,3 and displays under the column A.
MINUS:
Using MINUS operator, It displays all values from first query which is not in second query and eliminates the
duplicate rows and display the data in ascending order.
Syntax:
SELECT A FROM T1
UNION ALL
SELECT B FROM T2;
If A column contains values 1,2,3,4 in T1 table and B column contains values 1,2,3,5.
Returns output 4 and displays under the column A.
20
ANALYTICAL FUNCTIONS
Analytical Functions:
Analytic functions calculate an aggregate value based on a group of rows and it return multiple rows for
each group.
List of Analytical Function:
Rank
Dense Rank
Row_Number
Lead
Lag
Listagg()
RANK:
It is used to calculate the rank of a value in an ordered set of values.
SELECT FIRST_NAME, SALARY, RANK () OVER (ORDER BY SALARY DESC) FROM EMPLOYEES;
DENSE_RANK:
It is used to calculate the rank of a row. Unlike the RANK function this function returns rank as consecutive
integers.
SELECT FIRST_NAME, SALARY, DENSE_RANK () OVER (ORDER BY SALARY DESC) FROM EMPLOYEES;
ROW NUMBER:
SELECT FIRST_NAME, ROW_NUMBER () OVER (ORDER BY FIRST_NAME ASC) FROM EMPLOYEES;
LEAD:
To pick next row data
Select first_name, lead(first_name,1,'B') over(order by first_name asc) from employees;
LISTAGG():
22
PSEUDO COLUMNS
PSEUDO COLUMNS:
ROWNUM:
SELECT FIRST_NAME, SALARY, DEPARTMENT_ID, ROWNUM
FROM EMPLOYEES
WHERE DEPARTMENT_ID = 60;
23
NEXTVAL:
It increments the value in sequence and returns the next value.
CURRVAL:
It returns the current value in a specified sequence
To Create Sequence
CREATE SEQUENCE S1
START WITH 5
INCREMENT BY 1
MAXVALUE 10;
To Generate The Nextval For Sequence
SELECT S1.NEXTVAL FROM DUAL;
INCREMENT BY 2
MAXVALUE 30;
SELECT S1.NEXTVAL FROM DUAL;
10
SELECT S1.CURRVAL FROM DUAL;
12
24
INSERT INTO T1(A) VALUES (1);
1 row created
It returns the level number of a node in a tree structure, to organize rows from a database table
into a tree structure.
To Find The Hierarchy Levels:
SELECT EMPLOYEE_ID, FIRST_NAME, MANAGER_ID, LEVEL
FROM EMP
START WITH MANAGER_ID IS NULL
CONNECT BY PRIOR EMPLOYEE_ID = MANAGER_ID;
25
JOINS
Joins:
Join statement basically used for selecting data from two or more tables.
It performs a join whenever multiple tables appear in the FROM clause of the query. The select list of the
query can select any columns from any of these tables
Join condition:
Most join queries contain at least one join condition, either in the FROM clause or in the WHERE clause.
The join condition compares two columns, each from a different table.
Where s.cid=c.cid
Types
Equi Join
Outer join
-Left Outer Joins
-Right outer Join
- Full outer Join
Cross Join
Self-join
To write a query that performs an outer join of tables A and B and returns all rows from B (a right
outer join), use the RIGHT [OUTER] JOIN syntax in the FROM clause, or apply the outer join operator
(+) to all columns of A in the join condition in the WHERE clause
26
Select s.sname, c.cname from students s, course c where s.cid(+)=c.cid;
Returns unmatched records of right-side table
Select s.name, c.name from students full outer join course c on s.cid=c.cid;
-Returns all values with Null value
-Returns match and unmatched records.
Cross Join:
Self join:
Joining a table with itself.
Select e1.first_name as ename, e2.first_name as mname
From emp e1, emp e2
Where e1.manager_id=e2.employee_id(+);
Considering 1 table as two tables self joining
+ symbol returns employee id without manager_id or manager
27
SUB QUERIES
Subquery is a query within a query, we can create subqueries within the SQL statements. These subqueries
can reside in the WHERE clause, the FROM clause, or the SELECT clause.
28
TO FIND WHO GETTING THE MNIMUM SALARY
SELECT FIRST_NAME, SALARY
SELECT FIRST_NAME, SALARY FROM EMPLOYEE WHERE SALARY> ALL (SELECT SALARYFROM EMPLOYEE
WHERE FIRST_NAME =’DAVID’;
Any
Select first_name, salary from employees where salary>any (select salary from employees
Whwre first_name=’David’;
Choose least among Davis salary
Then returns all greatest from main query
30
WHERE DEPARTMENT_ID IN (SELECT D.DEPARTMENT_ID FROM DEPARTMENTS D
WHERE E.DEPARTMENT_ID = D.DEPARTMENT_ID);
31
INDEX
Index:
Index Creating:
CREATE INDEX IDEX1 ON EMPLOYEES(FIRST_NAME ASC);
B * Tree Index
Bitmap Index
B Tree index:
B Tree index created on High cardinality column
Columns that contain large number of unique values
Composite Index:
It is created with multiple columns
Function based Index:
It is created with based upon the functions
Unique Index:
32
SYNONYM
Synonym:
33
VIEWS
View is a virtual table that does not physically exist, it is stored in Oracle data dictionary and do not store
any data.
It can be executed when called, A view is created by a query joining one or more tables.
Types of views:
Simple View - Simple views can only contain a single base table
Complex View - Complex views can be constructed on more than one base table
Advantages:
To make complex query looks simply,
To restrict data access
Basic Syntax:
To save the query result in view:
CREATE OR REPLACE VIEW V1
AS
SELECT FIRST_NAME, SALARY, DEPARTMENT_ID
FROM EMPLOYEES
WHERE DEPARTMENT_ID = 60;
To check the views created by the user:
SELECT * FROM USER_VIEWS;
To call the created views:
SELECT * FROM V1;
To drop the created views:
DROP VIEW V1;
34
MATERIALIZED VIEWS
MATERIALIZED VIEWS:
Materialized view is a database object that stores query output and precomputed result
It is used to maintain a local copy for remote database object.
It is used to improve the performance of complex group by & complex aggregate operations.
Select statement output will be stored in MV1.
If base table data is modified, we need to update the materialized view, which means it need to get
refresh.
MV can be refreshed in different ways. REFRESH ON DEMAND, REFRESH ON COMMIT & REFRESH
PERIOICALLY
BASIC SYNTAX:
TO CREATE MV:
CREATE MATERIALIZED VIEW MV1
AS
SELECT STATEMENT<> ;
TO REFRESH MV:
EXECUTE DBMS_MVIEW.REFRESH(‘MV1);
TO VIEW MV:
SELECT * FROM MV1;
View is a virtual table that does not physically Materialized view is a database object that
exist stores query output and precomputed result
35
SQL LOADER
SQL Loader is a bulk loader utility to load data from a flat file to an oracle table.
It is used for high performance data loads.
Example:
Explanation:
Load – Specifies the location of the file
Append – To add up with the existing rows
Into – table name
Fields- Separated by ‘,’
Columns - (CID,CNAME)
Saved in Desktop as course.ctl - control file
Next Step
Open cmd
Sqlldr hr
C:\users\raj\desktop\course.ctl
36
SQL*loader
Commit point reached – Logical record count 4
Commit point reached-Logical record count 5
C:\USERS\DINESH\SQLLDR HR/ADMIN
CONTROL = C:\USERS\RAJ\DESTOP\COURSE.CTL
37
BAD = C:\USERS\RAJ\DESKTOP\1.BAD
LOG= C:\USERS\RAJ\DESKTOP\2.LOG
SKIP = 1
.Bad file stores missing data or data that are not loaded
.Log stores the reason for not loading the data and rows that are not loaded.
Skip 1 refers to 1st row of .csv file which skips the column name so that only data are uploaded.
38