SQL Notes by Krishna Reddy
SQL Notes by Krishna Reddy
Data:
It is stored representation of OBJECTS and EVENTS that have meaning and importance in user’s environment.
Data can be structure or unstructured.
o StructuredàEmpName, address.
o UnstructuredàEmpPhoto, AddrMap.
Representation of data:
KING 10 5000 15-02-08
JONES 10 4500 02-03-06
BLAKE 20 3500 15-06-05
SCOTT 20 2000 12-05-02
FORD 30 1100 13-04-00
MILLER 10 1200 14-07-99
Logical Structures
In design state the system is represented in the form of Entity relationship model.
In the database state it is representation of the actual metadata of the database management system software which will be in the form of tablespaces , data dictionary
objects etc.
Physical structures
In this the system is represented in the form of tables, indexes etc.
Database should have the ability to provide access to external tables for files outside the database, as if the rows in the files were rows in the table.
Creating structures (Tables & Indexes)
With in the oracle database, the basic structure is a table used to store data.
Table space:
It is logical storage unit within oracle database and is not visible in the file system of the machine on which the database resides.
The table space builds the bridge between the oracle database and the file system in which the table’s or index data is stored.
A data file can be part of one and only one table space.
Data models:
Data models helps in exploring ideas and improve the understanding the database design for both developers
and system designers.
Purpose of data models
Communicate
Describe
Investigate
Analyze
Categories
Page5 to page 20
To Create Table:
Syntax:.
Example:
Conventional INSERT.
Direct-Path INSERT.
In conventional Insert statement, Oracle reuses free space in the table into which the data in being insert and maintains Referential Integrity Constraints.
In Direct-Path Insert, Oracle append the insert data after existing data in the Table, the free space is not reused.
Syntax:
Sql> INSERT INTO <table name> [list of columns] VALUES (list of values);
EX:
Sql> INSERT Into Student_Det Values
(
1001,
‘THOMAS’,
‘SIEBEL’,
’30-DEC-81’
’02-JAN-91’,
30000,
‘M’
);
In this case the values should be provided to all the columns that exist inside the table.
The order of values declared in the Values clause should follow the original order of the columns in the table.
In this case the Order of columns declared in insert need not be the same as that of the original table order.
The data values in the values caluse should match with that of INSERT list of columns.
The columns not supplied with data are filled with NULL values, Until the NOT NULL constraint is declared.
‘SYSDATE’ FUNCTION
SYSDATE is Pseudo-column.
This function return the current date& time.
USER FUNCTION:
This function returns the user name of the user who has logged in.
Example:
Example:
Substitution Variables:
The List file is used to save all information which performed in SQL *Plus .
The SAVE Command is used to store the current contents of the SQL Buffer.
Steps:
1)At SQL prompt type the full name of the path where the file has to be created.
2)Give the name of the file with .sql extension.
3)If the has to be replaced with the same existing name then use
REPLACE ALL clause.
Example:
Sql>SAVE E:\nitdir\ins
Sql> SAVE E:\nitdir\ins REPLACE
To Get Script:
Sql>Get E:\nitdir\ins
To Run Script:
Run is used to display the script and run the file.
Sql>@ E:\nitdir\ins
Sql>ed E:\nitdir\ins
Select used to retrieve data from one or more than table ,view, object tables.
It is for read only purpose.
The select is the most frequently used command as access to information is needed all the time.
PREREQUISTIES:
The user must have the SELECT privileges on the specified object.
PROJECTION:
It chooses the columns in a table that are expected to return by a query.
JOIN :
It chooses the data in from one or more numbers of tables.
Syntax:
1)DEPT
Column Name Data Type
------------------------------- ------ ------
DEPTNO NUMBER(2)
DNAME VARCHAR2(14)
LOC VARCHAR2(13)
2)EMP
3)SALGRADE
Dept:
14 rows selected.
ARITHMETIC OPERATORS:
The Arithmetic operations can be used to create expressions on NUMBER and DATE data.
The Arithmetic operators supported are….
+ Addition
- Subtraction
* Multiplication
/ division.
The Arithmetic operators can be used in any clause of a SQL statement. except the FROM clause.
SQL * Plus ignores Blank Spaces before and after the Arithmetic operator.
Sql> Select empno,ename,sal,sal+500 FROM Emp;
Sql> Select empno,ename,sal,sal-1000 FROM Emp;
Operator Precedence:
General Function:
This functions work with any data type and pertain to using null value.
NVL Function:
Syntax:
NVL(Expr1,Expr2)
Expr1: is the source value or expression that may contain NULL.
Expr2: is the target value for converting NULL.
NVL(Number_column, 0)
NVL(date_column, ’01-JAN-09’)
NVL(Character_column, ‘Unavailable’)
Note : If Expr1 is Character data then Expr2 may any Data type.
Sql>Select NVL(100,200) from dual;
Sql> Select NVL(null,200) from dual;
Sql> Select ename,sal,comm,sal+NVL(comm,0) from emp;
Sql> Select ename,sal,comm,(sal*12)+NVL(comm,0) from emp;
Sql> Select ename,sal,comm,(sal+500)+NVL(comm,0) from emp;
NVL2 Function:
Syntax:
NVL2(expr1,expr2,expr3)
If expr1 is not null,NVL2 returns expr2.if expr1 is null, NVL2 returns expr3.
Expr1 may any data type.
The data type of the return value is always the same as the data type of expr2 , unless Expr2 is character data .
Example:-
1) select nvl2(comm,0,1000) from emp;
2) select sal,comm, sal+nvl2(comm,100,1000) from emp;
>select ename,sal,comm, nvl2(comm,'sal+comm','sal') income
from emp where deptno in(10,30);
NULLIF Function:
Syntax:
NULLIF(expr1,expr2)
Compares two expressions and returns null if they are equal,or the first if there are not equal.
Example:
>SELECT NULLIF(100,200) from dual;
COALESCE:
OCP Questions :
You want to display the name and annual salary multiplied by the commission_pct for all employees. For records that have a NULL commission_pct, a zero must be displayed against the calculated column.
Sql> Select 'The Basic Salary of '||Ename|| 'is Rs '||Sal Employee From
Emp;
LITERALS IN ORACLE:
A Literal and Constant valueare synonyms to one another and refer to a fixed data value.
The types of Literals recognized by Oracle are
Text Literals
Number Literals
Interval Literals
Text Literals:
It specifies a text or character literal.
It is used to specify values whenever ‘text’ or CHAR appear in
Example:
‘Employee Information’
'Manager's Specification'
A literal value is a character, a number, or a date that is included in the SELECT list.
A literal value not a column name or a column alias.
A literal is printed for each row returned, that is retrieved by the SELECT statement.
Literal strings of free-format text can be included in the query.
A free-format text treated the same as a column in the SELECT list.
Date and character literal must be enclosed within the single quotation marks ‘ ‘.
Literal increase the readability of the output.
Sql>Select ‘The Designation of ‘|| Ename ||’ is ’|| job As Designation From Emp;
Sql> Select 'The employee name is: '||Ename||' and '||'Designation is :'||job
from Emp;
Sql> Select Ename||' Joined the Organization on '|| Hiredate From Emp;
Duplicate Rows:
Unless we indicate otherwise, iSQL*Plus displays the results of a query without eliminating duplicate rows.
To eliminate duplicate rows in the result, the DISTINCT keyword used.
We can specify multiple columns after the DISTINCT qualifier.
The DISTINCT qualifier affects all the selected columns, and the result is every distinct combination of the columns.
Filter Of Record:
The number of rows returned by a query can be limited using the WHER clause.
The method of restriction is the basis of the WHERE clause in SQL.
A WHRE Clause contains a condition that must be met and should directly follow the From Clause.
The Character strings and dates should be enclosed in single quotation marks.
Character values are case sensate and Date values are format sensitive
(DD-MON-YY)
The Comparison operator are used in conditions that compare one expression to another.
Logical Operators:
A logical condition combines the result of two component conditions to produce a single result.
Three logical operators are available in Oracle.
AND OR NOT
AND Operator:
The AND operator allows creating an SQL statement based on two or more conditions being met.
It Returns FALSE if either is FALSE, else returns unknown.
Truth Table:
AND
TRUE TRUE TRUE
FALSE TRUE FALSE
TRUE FALSE FALSE
FALSE FALSE FALSE
Example:
OR Operator:
Truth Table:
OR
TRUE TRUE TRUE
TRUE FALSE TRUE
FALSE TRUE TRUE
FALSE FALSE FALSE
NOT Operator:
Sql>Select Empno,Ename,Job,Hiredate
From Emp
Where NOT JOb='CLERK' AND Deptno=20;
Rules of Precedence:
Example:
Sql>Select Ename,Sal,Job From Where Sal NOT Between 1000 AND 1500;
The Wild Card symbols can be used in any combination with literal character.
For finding exact match for ‘%’ and ‘-‘ the ESCAPE option has to be used, which is ‘/’ symbol with ESCAPE option.
ORDER BY Clause:
The Order of rows returned in a query result is undefined.
The ORDER BY clause can be used to sort the rows.
The ORDER BY clause must be the last clause of the SQL statement.
An expression, or an alias, or column position as the sort condition.
Default ordering of Data is Ascending.
**Number 1-999
**Dates Earlist-Latest
**String A-Z;NULLSLast.
Syntax:
SELECT expr FROM table [WHERE condition(s) ]
[ORDER BY {column, expr} [ASC|DESC]];
The default order upon column is Ascending, to change the default ordering DESC should be used after the column name.
Sorting can be implemented on column aliases ,and can also be implemented upon multiple columns.
**SELECT List
**WHERE List
**Start With Clause
**CONNECT BY Clause
These function manipulate group of rows to give one result per group of rows.
Func_Name(Column/Expr,[Arg1,Arg2,……])
Character functions: Accept character input and can return both character and
number values.
Number functions:Accept numeric input and return numeric values.
Date functions:Operate on values of the DATE data type (All date
functions return a value of DATE data type except the MONTHS_BETWEEN function, which returns a number.)
Character Functions:
LOWER(column|expression)
Upper Function:
Syntax:
UPPER(Column | Expression)
Sql>Select Ename,Job, Upper (Ename), Upper (Job) From Emp Where Deptno=20;
INITCAP Function:
It returns a string with the first letter of each word in upper case, keeping all othered
letters in Lower case.
Returns specified characters from character value, string from a specified position ‘m’ to ‘n’ characters long.
To extract the portion of the string it is mainly used.
Points to Remember…
If m is 0, it is treated as 1.
If m is positive, Oracle counts from the beginning of char to find the first character.
If n is Omitted, Oracle returns all characters to the end of char.
If n is less than 1 or 0, A null is returned.
Floating points numbers passed as arguments to substr are automatically converted to Integers.
Syntax:SUBSTR(Col/Exp,m,[n])
LENGTH Function:
Syntax:
LENGTH(Column|Expression)
INSTRING Function:
Searches for Column / Expression beginning with its ‘m’th character for the ‘n’ th occurrences of character ‘C’, and return the position of the character .
‘m’ can be positive or negative, if negative searches backward from the end of Column / Expression.
The value of ‘n’ should be positive.
The default value of both ‘m’ and ‘n’ are 1.
If search is unsuccessful, the return value is zero.
LPAD Function:
Pads the character value right-justified to a total width of n character positions.
The default padding character is space.
Syntax:
LPAD(Column | Expression, n, 'C')
Fill extra spaces with char ‘C’ up to ‘n’ position on left side.
RPAD Function:
LTRIM Function:
Syntax:LTRIM(Char,Set)
RTRIM Function:
Syntax: RTRIM(Char,Set)
TRIM Function:
REPLACE Function:
It return the every Occurrence of search string replace by the replacement string.
If the replacement string is omitted or null, all occurrences of serch string are removed.
If substitutes one string for another as well as to remove character strings.
Syntax:REPLACE(text,Search_string, [Replacement_string])
Syntax:TRANSLATE(char,From ,To)
It returns a char with all occurrences of each character in ‘From’ replaced by corresponding character in ‘To’.
Characters in char that are not in From are not replaced.
The argument From can contain more characters than To.
If the extra characters appear in Char, they are removed from the return value.
CHR Function:
Syntax:CHR(n)
Sql>Select Chr(75)||Chr(82)||Chr(73)||Chr(83)||Chr(72)||Chr(78)||Chr(65)
Name From Dual;
ASCII Function:
It returns the decimal representation in the character database set of the first characters of the Char.
Syntax: ASCII(Char)
NUMBER Function:
ROUND Function:
Systax: ROUND(m,n)
TRUNCATE Function:
Systax:TRUNC(m,n)
It returns ‘m’ Truncated to ‘n’ decimal places.
If ‘n’ omitted , n is truncated to 0 decimal places.
‘n’ can be negative to truncate ‘m’ digits left of the decimal point.
Sql>Select 19.637 Num1,TRUNC(19.637,1) Truncated
From Dual;
Sql> Select 19.637 Num1-, TRUNC(19.637,-1) Truncated
From Dual;
Sql> Select 7843.637 Num1,
TRUNC(7843.637,2) Truncated,
TRUNC(7843.637,2) Truncated,
TRUNC(7843.637,2) Truncated,
TRUNC(7843.637,2) Truncated,
TRUNC(7843.637,2) Truncated
From Dual;
CEIL Function:
Syntax:CEIL(n)
Returns the Largest integer greater than or equal to ‘n’.
The adjustment is done to the highest Nearest decimal value.
Sql>Select 19.001 Num1,CEIL(19.001) Ceiled
From Dual;
Sql> Select 19.34 Num1,
CEIL(19.32) Ceiled ,
CEIL(19.2) Ceiled ,
CEIL(19) Ceiled ,
From Dual;
FLOOR Function:
Syntax: FLOOR(n)
Returns the smallest integer less than or equal than ‘n’.
The adjustment is done to the lowest Nearest decimal value.
Sql>Select 19.001 Num1, FLOOR(19.999) Floor
From Dual;
Sql> Select 18.34 Num1,
FLOOR(18.34) Floor,
FLOOR(18.9) Floor,
FLOOR(18) Floor
From Dual;
MODULUS Function:
Syntax: MOD(m,n)
It Returns remainder of ‘m’ divided by ‘n’.
It returns ‘m’ if ‘n’ is 0.
Sql> Select MOD(100,10) Modulus,
MOD(17,4) Modulus From Dual;
POWER Function:
Syntax: POWER(m,n)
It Returns ‘m’ Raised to the ‘n’th power.
The base ‘m’ and the exponent ‘n’ can be any number.
Sql> Select POWER(5,2) Power,
POWER(-5,2)Power
From Dual;
Sql> Select POWER(5,-2) Power,
POWER(-5,-2)Power
From Dual;
SQUARE Function:
Syntax: SQRT(n)
It Returns Square Root of ‘n’ as Real Value.
The Value of ‘n’ cannot be negative.
Sql> Select SQRT(25) From Dual;
ABSOLUTE Function:
Syntax: ABS(n)
It Returns the Absolute value of ‘n’
SIGN Function:
Syntax: SIGN(n)
It Returns the SIGN, Specification of a number.
If n<0,returns -1
If n=0,returns 0
If n>0,returns 1
SYSDATE:
Date Arithmetic:
As database stores dates as numbers, it allows to perform calculations using arithmetic operators such as addition and subtraction.
We can perform the following operations…….
Date + Number Date Adds a number of days to a date.
Date - Number Date Subtracts a number of days from a date .
Date - Date Number of days Subtracts one date from another.
Date + Number/24 Date Adds a number of hours to a date.
Sql>Select Empno,Hiredate,Round((Sysdate-Hiredate)/365)
From Emp;
DATE Function:
Syntax:ADD_MONTHS(D, +(or)-N)
Months_Between Function:
Syntax: Months_between(D1,D2)
It gives the different between dates D1 and D2 In months.
If D1 is later than D2, the result is Positive, else Negative.
If D1 and D2 are either the same days of the months or both last days of the months, the result is always an integer.
Sql>Select Ename,Hiredate,
Round(Months_Between(Sysdate,Hiredate)/12) " Experience In Years"
From Emp;
Sql> Select Ename,Hiredate,Months_Between(Sysdate,Hiredate)
From
EmpWhereMonths_Between(Sysdate,Hiredate)<320;
Next_Day Function:
It returns the date of the first week day named by char, that is later
than the data D.
The CHAR must be a day of the week in the sessions data language.
The day of the week can be full name or the abbreviation.
Last_Day Function:
Syntax:Last_day(D)
It returns the date of the last day of the month that contains D.
Mostly used to determine how many days are left in the current month.
Rounding of Dates:
Syntax: Round(Date,’Format’)
Truncating Dates:
Synatx:Trunc(Date,’Format’)
Return Date with the time portion of the day truncated to the specified unit.
If format is omitted, data is truncated to the nearest day.
Conversion Function:
The Conversation functions convert a value from one data type to another.
The Data type conversion in Oracle is two types.
Implicit Date type conversion work according to the convention specified by oracle.
The Assignment succeeds if the Oracle server can convert the date type of value.
CHAR to NUMBER conversion succeed only if the character string represent a valid NUMBER.
CHAR to DATES conversion succeed only if the character string represent the default format of DD-MON-YY.
In Assignment Operator:
Varchar2/Char àNumber
Varchar2/Char àDate
Number àVarchar2
Date àVarchar2
TO_CHAR Conversion:
TO_CHAR(Number Conversion)
Syntax: TO_CHAR(NUMBER,fmt)
Converts Number of Number data type to a value of VARCHAR2 data type.
‘fmt’ is the optional number format, that can be used.
TO_CHAR(Date Conversion)
Syntax: TO_CHAR(DATE,fmt)
Converts Date of Date data type to a value of VARCHAR2 data type in the format specified.
‘fmt’ is the optional Date format, that can be used.
Decimal Indicator:Dà99D99
It returns the specified position of the decimal character .
The default decimal delimiter is period ‘.’
Only one decimal indicator can be specified in a number format model.
Sql>select Sal,Comm,Comm-Sal,
TO_CHAR(Comm-Sal,'L99G999D99MI') From Emp;
Sql>select Sal,Comm,Comm-Sal,
TO_CHAR(Comm-Sal,'L9999PR') From Emp;
Group Separator:à9,999
Decimal Indicator:à99.99
Returns value with a specified number of digits with a Leading space when positive or Leading minus when Negative.
Sql>select 1000,600,TO_CHAR(1000-600,'99999'),
TO_CHAR(600-1000,'99999') From Dual;
Sql>select 20.25,20,TO_CHAR(20.55-20,'99999'),
TO_CHAR(20.25-20,'99999') From Dual;
The date format models can be used in the TO_CHAR function to translate a DATE value from original format to user format.
Data Format Elements:
Meridian Indicator:
Sql>Select Sydate,TO_CHAR(Sysdate,’A.M.’),
TO_CHAR(Sysdate,’PM’) From Dual;
Century Indicator: CC
Sql>Select Ename,Hiredate,TO_CHAR(Hiredate,'DAY')
From Emp Where TO_CHAR(Hiredate,'DY')='MON';
Specifies the week of the yaer(1-52 or 1-53) based on the ISO standard.
Sql>Select TO_CHAR(Sysdate,'YYYY'),TO_CHAR(Sysdate,'YYY'),
TO_CHAR(Sysdate,'YY') From Emp;
Returns the hour of the day in twenty four hour clock mode.(0-23)
Minutes Indicator: MI
Seconds Indicator: SS
Example:
TO_NUMBER Function:
Syntax:TO_NUMBER(Char,fmt)
It convert a char ,value of CHAR or VARCHAR2 data type containing a NUMBER in the format specified by the optional format model ‘fmt’, to a value of NUMBER data type.
TO_DATE function:
Syntax:TO_DATE(Char,’fmt’)
Converts given char of Char or Varchar2 data type to a value of DATE data type.
The ‘fmt’ is optional Date format specified the format of CHAR.
Invalid Dates:
Century Identification:
Some Combinations
Sql>Select
TO_CHAR( ADD_MONTHS(Hiredate,1), 'DD-MON-YYYY' ) "Next Month"
From Emp Where Empno=7788;
Sql> Select
Concat(Concat(Ename, 'is a '), Job )Designation From Emp
Where Deptno=20;
Sql> Select Trunc( TO_DATE('27-OCT-92','DD-MON-YY'), 'YEAR' )"New Year"
From Dual;
Sql>Select
TO_CHAR( ADD_MONTHS(
LAST_DAY(Hiredate),5),'DD-MON-YYYY' )"Five Months"
From Emp Where Empno=7788;
Sql>Select
MONTHS_BETWEEN(
TO_DATE( ’02-02-1995’,’MM-DD-YYYY’ ),
TO_DATE( ’02-02-1995’,’MM-DD-YYYY’ )
)Months FROM Dual;
Sql>Select Ename,
NVL(TO_CHAR(Comm),’Not Applicable’) “Commission”
From Emp
WHERE Deptno=30;
Sql>Select
Round(
TO_DATE(’27-OCT-92’,’DD-MON-YY’),’YEAR’
)”New Year”
From Dual;
Sql>Select Ename,
TO_CHAR(Hiredate,’FMMonth,DD YYYY’) Hiredate
From Emp WhereDeptno=20;
Sql> Select
TO_CHAR(
TO_DATE('27-OCT-98','DD-MON-RR'),'YYYY') Year From Dual;
Sql>Select Ename,Job,
NVL(TO_CHAR(MGR),’Supreme Authority’) “Managers”
From Emp Order by Sal Desc;
Spelling a Number:
Sql> Select
TO_CHAR( TO_DATE('&GiveNumber','J'), 'JSP' ) "Spelled Number"
From Dual;
Sql>Select
TO_CHAR( TO_DATE(Hiredate,’DD-MON-RRRR’), ‘DD-MON-YYYY’ ) Hiredate
From Emp;
Text Encryption:
Sql>Select
‘KRISHNA REDDY’ OrgName,
Translate(
‘KRISHNA REDDY’,
‘ABCDEFGHIJKLMNOPQRSTUVWXYZ’,
‘1234567890!@#$%^&*()-=_+;,.’)Encryptedname
From Dual;
Text Decryption:
Syntax:
group_function(DISTINCT/ALL Column)
The data types for the arguments can be CHAR, VARCHAR2, NUMBER, or DATE.
All group functions except COUNT(*) ignore null values. To substitute a value for null values, use he NVL function. COUNT returns either a number or zero.
The Oracle Server implicitly sorts the result set in ascending order of the grouping columns specified, when you use a GROUP BY clause. To override this default ordering, you can use
DESCin an ORDER BY clause.
When a group function is declared in a SELECT list, on single row columns should be declared.
Average Function:
Sum Function:
Maximum Function:
Minimum Function:
Variance Function:
Count Function:
The Group by clause is used to decide the rows in table into groups.
Syntax1:
Sql>SELECT columnname1, Columnname2,……
FROM table
[WHERE condition(s)]
[GROUP BY Column name(s)]
[ORDER BY column(s)];
Syntax2:
Sql>SELECT columnname1, GRP_FUN(Column)
FROM table
[WHERE condition(s)]
[GROUP BY Columnname(s)]
[ORDER BY column(s)];
All GROUP BY CLAUSE columns list may or may not used in SELECT clause.
The Extra non Group functional column should be declared in the GROUP BY Clause.
If the GROUP Function is included in a SELECT clause, we should not use individual result columns.
Using WHERE clause, Rows can be pre excluded before dividing then into groups.
Column aliases cannot be used used in GROUP BY CLAUSE.
By default, Rows are sorted by ascending order of the columns included in the GROUP BY LIST.
Example:
Sql>Select Owner,COUNT(Object_Name)
From dba_objects Group By Owner;
OCP Questions:
STD_ID NUMBER(4)
COURSE_ID VARCHARD2(10)
START_DATE DATE
END_DATE DATE
Which two aggregate functions are valid on the START_DATE column? (Choose two)
A. SUM(start_date) B. AVG(start_date)
C. COUNT(start_date) D. AVG(start_date, end_date)
E. MIN(start_date) F. MAXIMUM(start_date)
Having Clause:
You may not want all the summary rows returned by a GROUP BY query. You know that you can use WHERE to eliminate detail rows returned by a regular query. With summary queries,
you can use the HAVING clause to eliminate summary rows.
It used generally with GROUP BY Clause the having is useful for specifying a condition for the group.
The Clause is used to filter data that is associated with group function.
Syntax:
SELECT [column,] group_function(column). . .
FROM Table
[WHERE condition]
[GROUP BY group_by_expression]
[HAVING having_expression];
[ORDER BY Column/Alias];