Documente Academic
Documente Profesional
Documente Cultură
DBMS
A database management system (DBMS) is a collection of programs that
enables you to store, modify, and extract information from a database. It’s a
single table with no relation on other table.
RDBMS
Relational databases are sets of tables. It must have relation between two or
more tables. One table have a primary key value and another table have a
Foreign Keys – which point (reference) the first table primary key value.
ORDBMS
An object relational database is also called an object relational database
management system (ORDBMS). This system simply puts an object oriented
front end on a relational database (RDBMS).
The system will convert the object information into data tables with rows and
colums and handle the data the same as a relational database
Advantages of choosing Oracle Database.
Portability
Oracle provides industrial strength support for on-line backup and recovery
and good software fault tolerance to disk failure.
Performance
Speed of a Oracle database and application is quite good, even with large
databases
Cursor Support
A cursor basically lets you do row-by-row processing.
Oracle has a superior ability to manage multiple databases within the same
transaction using a two-phase commit protocol.
Oracle version
DQL commands are basically SELECT statements. SELECT statements let you
query the database to find information in one or more tables, and return the
query as a result set.
ALTER :Use to Alter Objects like ALTER TABLE, ALTER USER, ALTER
TABLESPACE, ALTER DATABASE. Etc.
DROP :Use to Drop Objects like DROP TABLE, DROP USER, DROP
TABLESPACE, DROP FUNCTION. Etc.
System Privileges
Object privileges
Strings variables
Strings can be literals or variables. A string literal begins and ends with a
single quotation mark:
'This is a string literal'
If you need to embed a single quote inside a string literal, you can type
in two single quotes right next to one another, as in:
'THISI SN''TADATE'
This isn't a date
You can also use the “q” character to indicate an alternative terminating
character for the literal:
q'[This isn't a date]'
Operator Meaning
+ (Add) Addition
select first_name ,salary, salary +1000 from
employees
- (Subtract) Subtraction
select first_name ,salary, salary -1000 from
employees
* (Multiply) Multiplication
select first_name ,salary, salary * commission_pct
from employees
FIRST_NAME SALARY salary * commission_pct
John 14000 5600
Karen 13500 4050
Alberto 12000 3600
/ (Divide) Division
select first_name ,salary, salary / 2 from employees
FIRST_NAME SALARY SALARY/2
Steven 24000 12000
Neena 17000 8500
Concatenation Operator
The Oracle/PLSQL || operator allows you to concatenate 2 or more strings
together.
|| Operator
But if all expressions evaluate to NULL, || operator returns NULL, not empty string.
|| operator implicitly converts numbers and datetime values to string before concatenation.
Using Unique
Select unique sal from emp
Using group by
select first_name from employees
group by first_name
Using rowid
select sal from emp
where rowid in
(select max(rowid) from emp group by sal);
Using join
select sal from emp e1
where rowid in
(select max(rowid) from emp e2
where e1.sal= e2.sal);
2. Restricting and Sorting Data
WHERE Clause - Character Strings and Dates, number
General Comparison Conditions = > >= < <= <>
Other Comparison BETWEEN , IN , LIKE , NULL
Logical Conditions AND OR NOT
ORDER BY Clause, Sorting by Column Alias , Column Position, Multiple Columns
FIRST_NAME SALARY
Steven 24000
Steven 2200
FIRST_NAME SALARY
Steven 24000
Neena 17000
Lex 17000
Operator Description
= Equal
select first_name, salary from employees where employee_id = 130
FIRST_NAME SALARY
Mozhe 2800
select first_name, salary from employees where salary not between 15000
and 20000
FIRST_NAME SALARY
Neena 14000
Lex 22000
FIRST_NAME
NOT LIKE
TJ
Tayler
WHERE First_name LIKE 'a%' Finds any values that starts with "a"
WHERE First_name LIKE '%a' Finds any values that ends with "a"
WHERE First_name LIKE '%or%' Finds any values that have "or" in any
position
WHERE First_name LIKE '_r%' Finds any values that have "r" in the
second position
WHERE First_name LIKE 'a_%_%' Finds any values that starts with "a"
and are at least 3 characters in length
WHERE First_name LIKE 'a%o' Finds any values that starts with "a"
and ends with "o"
FIRST_NAME
Hermann
Gerald
Lex
select first_name , job_id from employees where job_id not in ('IT_PROG',
'AD_VP', 'ST_MAN')
FIRST_NAME JOB_ID
Steven AD_PRES
Nancy FI_MGR
Daniel FI_ACCOUNT
Using AND
select location_id from locations where country_id = 'IT' and city= 'Roma'
LOCATION_ID
1000
Using OR
select location_id from locations where country_id = 'IT' or city= 'Roma'
LOCATION_ID
1000
1100
Using AND OR
select first_name, salary from employees where salary=17000 and
(department_id= 90 or department_id=100)
FIRST_NAME SALARY
Neena 17000
Lex 17000
Using NOT
select first_name, salary, department_id from employees where not
department_id=100 and not department_id =90
Using DESC
select first_name from employees order by first_name desc
FIRST_NAME
Winston
William
William
Vance
FIRST_NAME SALARY
Winston 3200
William 7400
William 8300
Vance 2800
Valli 4800
Using alias
select first_name f , salary from employees order by f desc
F SALARY
Winston 3200
William 7400
William 8300
1. LOWER
The Lower function converts the character values into lowercase letters.
oracle
2. UPPER
The Upper function converts the character values into uppercase letters.
ORACLE
3. INITCAP
The Initcap function coverts the first character of each word into uppercase and the remaining
characters into lowercase.
Learn Oracle
4. CONCAT
The Concat function join the first string with the second string.
Oracle Backup
5. SUBSTR
The Substr function returns specified characters from character value starting at position m and n
characters long. If you omit n, all characters starting from position m to the end are returned.
You can specify m value as negative. In this case the count starts from the end of the string.
BACKUP
6. LENGTH
17
7. INSTR
- The Instr function is used to find the position of a string in another string.
- Optionally you can provide position m to start searching for the string and the occurrence n
of the string.
- By default m and n are 1 which means to start the search at the beginning of the search and
the first occurrence.
24
8. LPAD
The Lpad function pads the character value right-justified to a total width of n character positions.
xx100
9. RPAD
The Rpad function pads the character value left-justified to a total width of n character positions.
100xx
10. TRIM
The Trim function removes the leading or trailing or both the characters from a string.
RACLE
11. REPLACE
The Replace function is used to replace a character with another character in a string.
12 Translate
- Translate replaces by position, the first character of the list to match is
replaced by the first character of the replacement list.
- The second character with the second, and if there are characters in the list
to match that do not have positional equivalents in the replacements list they
are dropped.
Translate ah to e
So Wet
FROM DUAL;
'p78o 8o 0 o42i4p
Secret to original
FROM DUAL;
this is a secret
Length of vowels
13. Reverse
- used to reverse the string
SELECT REVERSE('Dan Morgan') FROM DUAL;
nagroM naD
Number Functions Example
1. ROUND
Syntax: round(number,n)
123.7
124
120
2. TRUNC
The Trunc function truncates the value to the n decimal places. If n is omitted, then n defaults to zero.
Syntax: trunc(number,n)
123.6
123
3. MOD
Syntax: mod(m,n)
3
4. Ceil
5. Sign
-1
-
6. abs
Remove ‘ – ‘ sign
6
7. power
6
Date Functions Example
1. SYSDATE
The Sysdate function returns the current oracle database server date and time.
You can add or subtract the number of days or hours to the dates. You can also subtract the
dates
3. MONTHS_BETWEEN
The Months_Between function returns the number of months between the two given dates.
Syntax: months_between(date1,date2)
The Add_Months is used to add or subtract the number of calendar months to the given date.
Syntax: add_months(date,n)
5. NEXT_DAY
The Next_Day function finds the date of the next specified day of the week. The syntax is
NEXT_DAY(date,'char')
6. LAST_DAY
The Round function returns the date rounded to the specified format. The Syntax is
Round(date [,'fmt'])
01-NOV-17
01-JAN-18
8. TRUNC
The Trunc function returns the date truncated to the specified format. The Syntax is
Trunc(date [,'fmt'])
01-Nov-2017
01-Jan-2017
9.To_date
Convert string date into oracle date format
SELECT to_date('10-12-06','MM-DD-YY') from dual;
12-OCT-06
01-Jan-2007
12-OCT-06
31-MAY-07
31-DEC-07
SELECT to_date('2006,091,00:00:00' , 'YYYY,DDD,HH24:MI:SS') from dual;
01-APR-06
15-MAY-06
01-FEB-02
31-DEC-99
10. To_Char
Used to change date format
11 17
wednesday 2017
DD 19
MM 09
MON SEP
MONTH SEPTEMBER
YY 17
YYYY 2017
YEAR TWENTY SEVENTEEN
DAY TUESDAY
DY TUE
D 3
HH 11 (HOUR 12H)
HH24 13 (HOUR 24H)
MI 06 (MIN)
SS 59
AM/PM AM
DDTH 19TH
DDSP NINTEEN
DDSPTH NINTEENTH
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
Query-2
SELECT employee_id,first_name,salary
FROM employees
TO_CHAR, TO_NUMBER and TO_DATE are the three functions which perform cross modification of data
types.
TO_CHAR function
TO_CHAR function is used to typecast a numeric or date input to character type with a format model
(optional).
TO_NUMBER function
The TO_NUMBER function converts a character value to a numeric datatype. If the string being
converted contains nonnumeric characters, the function returns an error.
Syntax
TO_NUMBER (string1, [format], [nls_parameter])
Format Description
Model
CC Century
BC BC/AD Indicator
TO_DATE function
The function takes character values as input and returns formatted date equivalent of the same.
The TO_DATE function allows users to enter a date in any format,
Null function
NVL
NVL( exp1, exp2 )
NVL2
NVL2(input_value, return_if_not_null, return_if_null)
NULLIF
COALESCE
COALESCE function, returns the first non-null expression in the argument list. It takes
minimum two mandatory parameters but maximum arguments has no limit.
CASE expression
CASE expressions works on the same concept as DECODE but differs in
syntax and usage.
SELECT ename, empno,
(CASE deptno
WHEN 10 THEN 'Accounting'
WHEN 20 THEN 'Research'
WHEN 30 THEN 'Sales'
WHEN 40 THEN 'Operations'
ELSE 'Unknown'
END) department
FROM emp
Nesting Functions
4. JOINS
EQUI JOIN / SIMPLE JOIN / NORMAL JOIN
ANSI JOIN, LEFT OUTER, RIGHT OUTER, FULL OUTER
NATURAL JOIN, NATURAL OUTER JOINS
INNER JOIN, JOIN ... USING clause, JOIN ... ON clause,
CROSS JOIN, NON-EQUI JOIN, SELF JOIN
ORACLE STANDARD OUTER JOINS.
Multi table Joins, Complex Joins How to simplified complex joins.
JOINS
A join is the process of combining data from two or more tables using matching columns.
SNAME CNAME
steven C++
lex sql
SNAME CNAME
steven C++
lex sql
neena -
- Java
Cross join
Cross join is a Cartesian product
No of rows in first table joined with no of rows in second table
Cartesian product is formed when user ignores where clause or a valied join
condition
It is used by developers for performance testing
If one table has 3 record and another has 0 record then cross join =0 rows
If 3 in both table then output will be 9 rows
Rule ->
If need to get n tables record then there must be n-1 join conditions
If 5 tables then 4 join condition
Self join
Join table by itself
Select max(salary), min (salary), avg(salary), sum(salary), count( salary) from employees
A
-----
1000
-
1000
1000
4 rows selectd
But
Select count(a) from t1;
Count(*)
----------
4
-- count(*) include null value
GROUP BY Clause
Next example
select first_name, salary from employees
where salary = (select max(salary) from employees)
UNION ALL
FIRST_NAME SALARY
Steven 24000
TJ 2100
DEPARTMENT_NAME CNT
Administration 1
Marketing 2
Purchasing 6
Human Resources 1
Shipping 45
IT 5
Public Relations 1
Sales 34
Executive 3
Finance 6
Accounting 2
Another example
select 1+2 + (select 2+3 from dual)
from dual;
1+2+(SELECT2 +3FROMDUAL)
8
Inline views
-if query written in from clause is called inline views
select max(salary)
from
(select first_name, salary from employees where department_id=60);
MAX(SALARY)
9000
If outer query depend the output of inner query is called nested sub query
FIRST_NAME SALARY
Steven 24000
Neena 17000
Lex 17000
For this example, we’ll be manually altering these settings one time prior to our query and
file generation, but if desired, you can change the defaults of various settings in your User
Profile, located in the login.sql file.
set colsep ,
set pagesize 0
set trimspool on
colsep is the separator character used to split your columns. For a .csv file, this is a simple
comma.
headsep is the separator character for the header row (if you require one). In this example
we’re not outputting the header row, so we’ll leave this off.
pagesize is the number of lines “per page.” This is a slightly archaic setting that is intended
for printing without having too many lines per page. With a value of 0, we don’t use pages
since we’re outputting to a file. If you elect to show the header row, set pagesize to a very
large number (larger than the expected number of record results in the query), so your
header row will only show up one time rather than once “per page.”
set linesize #
set numwidth #
For linesize, the # value should be the total number of output columns in your resulting
query.
numwidth is the column width (number of character spaces) used when outputting
numeric values.
With our settings taken care of, now we must tell SQL*Plus to output a file. This is
accomplished using the SPOOL statement.
While SPOOL is active, SQL*PLus will store the output of any query to the specified file.
spool file_path
Skipping ahead slightly, after your query is inserted, you also need to halt spoolso the file
output is closed by using the spool off command:
spool off
The last step after the settings are modified and spool is running is to insert your query. For
our simple example, we’re outputting all books from our books table.
SELECT
title, primary_author
FROM books;
Don’t forget the semi-colon to close out your query statement, then enter the
aforementioned spool off command.
EDIT file_name
Now paste the entire script command list into your new file and save.
set colsep ,
set pagesize 0
set trimspool on
set linesize 2
set numwidth 5
spool books.csv
spool off
To execute the script, simply use the @ symbol followed by the file name:
@file_name
Your script should be executed and the .csv file created as expected.
Insert
Insert a single row into a table:
INSERT ALL
INTO dept (deptno, dname, loc) VALUES (11, 'Sales', 'New York')
INTO dept (deptno, dname, loc) VALUES (12, 'Pre-sales', 'Dallas')
SELECT 1 FROM dual;
INSERT INTO dept
SELECT 13, 'Sales', 'New York' FROM dual UNION
SELECT 14, 'Pre-sales', 'Dallas' FROM dual;
Update
Update is a SQL DML command used to change data in a table.
Note that it's important to specify a WHERE-clause, if not ALL rows in the table will be updated.
Delete
Delete is a SQL DML command used to remove one or more rows from a table. Note that it's important to
specify a WHERE-clause, if not ALL rows in the table will be removed.
Merge
MERGE (sometimes also called UPSERT) is a SQL command that performs a series of
conditional update and/or insert operations. A row is updated if it exists, inserted if it doesn't.
Merge into t2
Using t1
On (t1.a=t2.a)
Commit
commit;
saved in database
Rollback
delete from emp;
Save point
Table t1
A
----
1
2
Save point x;
3
4
Rollback to x
Now 3 and 4 will rollback
Select * from t1
A
----
1
2
Commit;
The value will store in database
ALTER :Use to Alter Objects like ALTER TABLE, ALTER USER, ALTER
TABLESPACE, ALTER DATABASE. Etc.
DROP :Use to Drop Objects like DROP TABLE, DROP USER, DROP
TABLESPACE, DROP FUNCTION. Etc.
Create table
create table course
(
cid number(3),
cname varchar(20) not null,
constraint c1 primary key(cid)
);
user_tab_columns
select * from user_tab_columns where table_name='EMPLOYEES';
user_tables
select * from user_tables;
Used to find how many table in the user
USER_TAB_COLUMNS
select * from USER_TAB_COLUMNS where table_name='STUDENTS'
Used to find all column and detail in the table
Sample table
create table students
(
sid number(4),
sname varchar(30) not null,
cid number(3),
phno number(10),
email varchar(30),
gender char(1) not null,
dob date not null,
doj timestamp,
address varchar(100),
resume long,
constraint c2 primary key(sid),
constraint c3 unique (phno),
constraint c4 unique(email),
constraint c5 check (gender in ('m','f')),
constraint c6 foreign key (cid) references course(cid)
);
Alter
Drop column
Alter table students drop column resume
Add column
Alter table students add (qual varchar(20));
Rename column
Alter table students rename email to mailid
Drop constraint
Alter table students drop constraint c2;
Add constraint
Alter table students add constraint c2 primary key(sid);
Rename a table
Rename students to newstud
Drop a table
Drop table newstud
Truncate
Truncate table students;
Now change table name and constraint name which want to be unique
Constraint
A constraint is a data rule or restriction that is enforced within the database rather than at
application or object level.
UNIQUE - Ensures that all values in a column are different, allow null value,
automatically generate unique index, not accept duplicate value.
CREATE TABLE t1 (c1 NUMBER PRIMARY KEY, c2 VARCHAR2(30) UNIQUE);
PRIMARY KEY - A combination of a NOT NULL and UNIQUE. Uniquely identifies each row
in a table
(Or)
CREATE TABLE t1 (
c1 NUMBER,
c2 VARCHAR2(30),
c3 VARCHAR2(30),
FOREIGN KEY - Uniquely identifies a row/record in another table, reference key, refer
the primary key or unique of another table.
Define a table with primary key to reference:
CREATE TABLE t1 (c1 NUMBER PRIMARY KEY);
CREATE TABLE t3 (
c1 NUMBER,
c2 NUMBER,
Views
- Is a virtual table
- One view can create for one select statement
- Logically represent a subset of data from one or more table
- To make complex query look simple
View types
Simple view
Create or replace view v1
As
Select first_name, department_id from employees
Where department_id = 60;
User_views
- Check how many views created
User_error
- Used to find error in views
Select *from user_error where type = ‘view’;
Complex view
Create
FAST : A fast refresh is attempted. If materialized view logs are not present
against the source tables in advance, the creation fails.
COMPLETE : The table segment supporting the materialized view is truncated
and repopulated completely using the associated query.
FORCE : A fast refresh is attempted. If one is not possible a complete refresh is
performed.
Refresh groups of views
A refresh group is a collection of one or more materialized views that Oracle refreshes
in an atomic transaction, guaranteeing that relationships among the master tables are
preserved.
To create a refresh group:
exec DBMS_REFRESH.MAKE(name=>'my_grp', -
list=>'my_mv1,my_mv2', -
next_date => sysdate, -
interval => 'null');
Index
- Used to improve performance
- Need to create in where clause
- Oracle create separate copy of a column in asc order to fetch result
fast.
- Can create multiple index for single table
Types
1. B* tree index
2. Bitmap index
3. Composite index
4. Unique index
5. Function based index
6. Indexed virtual column
7. Index organized table(IOT)
B* tree index
- B – Balanced index
- Create for high cardinality column ( more unique record)
Bitmap Index
- Create for low cardinality index ( more duplicate index)
Create index idx2 on emp( gender );
Composite index
- Index created for multiple column
User_indexes
Check how many index created
Select * from user_indexes where table_name =’emp’;
Drop index
Drop index idx2;
SYSDATE SYSTIMESTAMP
--------- ----------------------------------------
UID USER
---------- ------------------------------
50 MICHEL
LEVEL
ROWID
- ROWNUM returns a number indicating the order in which a row was selected
from a table.
- The first row selected has a ROWNUM of 1, the second row has a ROWNUM of
2, and so on.
- If a SELECT statement includes an ORDER BY clause, ROWNUMs are
assigned to the retrieved rows before the sort is done.
sequence_name.CURRVAL
sequence_name.NEXTVAL
- Dual
-
- V$database -> dispalay the database name
Select * from v$database;
- V$version- > to find oracle version
Select * from v$version
Create sequence s1
Start with 5
Increment by 1
Max value 10;
Step1
Login to sys /admin
>Sqlplus sys/admin as sysdba
Step 2
Create directory in oracle
>create directory test as ‘D:\new’;
Step 3
Permission to hr user
>Grant Read, Write on directory test to hr;
Step 4
Login to hr user
>connect hr/admin
Step 5
Create 2 text files, with data in comma separator
Step 6
Create the external table as column like in the file
SQL> SELECT *
2 FROM countries_ext
3 ORDER BY country_name;
COUNT COUNTRY_NAME COUNTRY_LANGUAGE
----- ---------------------------- -----------------------------
ENG England English
FRA France French
GER Germany German
IRE Ireland English
SCO Scotland English
USA Unites States of America English
WAL Wales Welsh
7 rows selected.
Sql Loader
Is a bulk loader utlity to load data from a flat file to an oracle table
It is used to high performance data loads
Step1
Create table
CREATE TABLE emp (empno number(5),
name varchar2(50),
sal number(10,2),
jdate date);
step 2
move csv file from remote to local
a. For example:-
Password:oracle
FTP>
b. Now give PUT command to transfer file from current Windows machine to
Linux machine
FTP>put
Local file:C:\>emp.csv
remote-file:/u01/oracle/emp.csv
c. Now after the file is transferred quit the FTP utility by typing bye command.
FTP>bye
Good-Bye
Step 3
After creating the table, you have to write a control file describing the actions which
SQL Loader should do. You can use any text editor to write the control file.
$ vi emp.ctl
1. LOAD DATA
2. INFILE ‘/u01/oracle/emp.csv’
3. APPEND OR TRUNCATE OR INSERT OR REPLACE
4. INSERT INTO TABLE emp
5. FIELDS TERMINATED BY “,” OPTIONALLY ENCLOSED BY ‘”’
TRAILING NULLCOLS
6. (empno,name,sal,jdate date ‘mm/dd/yyyy’)
Line1. The LOAD DATA statement is required at the beginning of the control file.
Line2. The INFILE option specifies where the input file is located
Step 4
After you have wrote the control file save it as ‘emp .ctl file’ and then, call SQL
Loader utility by typing the following command
In windows
The LOG option of sqlldr specifies where the log file of this sql loader
session should be created.
The log file contains all actions which SQL loader has performed i.e. how
many rows were loaded, how many were rejected and how much time is
taken to load the rows and etc.
Skip is used to skip how many lines in the file before load.
Step 5
SQL loader
----------------
1.
create table course
(
cid number(3),
cname varchar(20)
);
2.
insert into course values(30, 'Java');
3.
select * from course;
CID CNAME
10 sql
20 C++
30 Java
4.
create a file 1.csv with the following data and store in d:/new
cid,cname
40,sos
50,R
60,python
70,pega
5.
6.
CID CNAME
40 sos
50 R
60 python
70 pega
10 sql
20 C++
30 Java
Global temporary table
- Temp table insert value and can use till give commit
- If commit data will delete
- Many large applications make extensive use of Temporary data storage.
Oracle implements the feature in Temporary tables.
- Global temporary tables are types of database tables which can privately
store data, persistently for a session or transaction.
- The data flushes out at defined instant automatically.
- Default is on commit delete rows
Analytical function
RANK
DENSE_RANK
FROM employees
FIRST_VALUE
- The FIRST_VALUE analytic function is similar to the FIRST analytic function,
allowing you to return the first result from an ordered set.
LAST_VALUE
- The LAST_VALUE analytic function is similar to the LAST analytic function, allowing
you to return the last result from an ordered set.
Lead()
- To fetch next record
Select first_name , lead(first_name,1,'X') over (order by first_name asc) from employees
Lag()
- Fetch previous Record
Row_number()
- It will create row number for each row according to the order specified
by the column
Listagg()
- Use keyword within group
- Convert row data into column data
ROW_TO_COLUMN
101,102,103,104,105,106,107
DEPTID EMPID
10 200
10 201
10 304
20 301
20 456
20 321
20 978
30 122
30 222
40 444
select deptid, listagg(empid,',') within group(order by empid) from deptid group by deptid;
Random Number
RANDOM
==========
-748908608
The function VALUE generate random numbers from the range provided. The range will be taken as 0-1
if none is provided.
NUM
==========
2001
The function STRING generate strings in upper case, lower case or alphanumeric format.
==========
eYksMvGhTT
Random - Date
Oracle stores dates as integer offsets from a key date in the past (January 1, 4712 B.C., in case you were
curious). This means that you can generate random dates in a given range by finding the integer that
corresponds to your desired start date, and then adding a random integer to it.
You can generate the internal date number for today's date by using the TO_CHAR function with the 'J'
format code:
For example, to generate random dates during the year 2003, you would first determine the date
integer for January 1, 2003:
TO_CHAR
=======
2454467
The system responds with 2454467. So, to generate a random date within the year, we use
DBMS_RANDOM.VALUE with :
a low_value of 2454467
TO_DATE(T
=========
04-JUN-08
RANDOM
_____________
1393936551
VALUE
_____________
1
NUM
_____________
611
E.g.: Generating a 12 digit random number.
NUM
_____________
175055628780
STR
_______________________
VUOQOSTLHCKIPIADIZTD
STR
____________________
Xpoovuspmehvcptdtzcz
STR
__________________
sTjERojjL^OlTaIc]PLB
STR
________________________
SQ3E3B3NRBIP:GOGAKSC
E.g.: Generating a string of printable 20 characters. This will output a string of all
characters that could possibly be printed.
STR
___________________
*Yw>IKzsj\uI8K[IQPag
E.g.: Example for calling the dbms_random package and setting the seed for generating the
same set of random numbers in different sessions. Please note that the same random
numbers are generated in different sessions. Though I have found this to work on most
accounts, in some cases, the first number generated was different in different sessions and
the remaining were same. I recommend not using this option in any of production code until
it is properly document by Oracle.
jaJA>declare
2 l_num number;
3 begin
4 l_num := dbms_random.random;
5 dbms_output.put_line(l_num);
6 dbms_random.seed('amar testing 67890');
7 l_num := dbms_random.random;
8 dbms_output.put_line(l_num);
9 end;
10 /
483791552
478774329
Revoke select
>revoke select on emp from lex;
Create a group
>create role r1;
Add user to group(role)
>grant r1 to lex, steven;
UNION Example
The following statement combines the results with the UNION operator, which
eliminates duplicate selected rows.
INTERSECT Example
- It returns the common records from all the select statement
SELECT empno FROM emp
INTERSECT
SELECT empno FROM oldemp;
MINUS Example
Returns all the rows in the first select statement that are not returned by
second select statement.
SELECT empno FROM emp
MINUS
SELECT empno FROM oldemp;
Clear screen
Set feedback on
Set feedback off
Set pagesize
Set line size
Ttitle
Btitle
Set heading on
Set heading off
Define
Undefine
Set verify on
Set verify off
Show user
Set timing on
Set timing off
Spool
Ed
@
/
Exit
quit
Clear screen
Set feedback on
Set feedback off
cid cname
10 sql
1 row selected
Set pagesize
Ttitle
>ttitle Reports
-Create a title on top of a query output page
-Header part
Btitle
>btitle confidential
-Create a title on bottom of a query output page
-footer part
Example
Reports
cid cname
10 sql
Confidential
1 row selected
>btitle off
>ttitle off
Set heading on
Set heading off
cid cname
10 sql
1 row selected
4+1
----------
5
&& constant
-When executed next time it will not ask value for B ( constant)
-The value cant change
4+1
----------
5
Define
>define B=10
-Used to change the constant value
- Now the value of B is 10
Undefine
>undefine B
-Used to remove the value of B
- Now it will ask value of B from user
Set verify on
Set verify off
>set verify on
-The highlighted part will display
>set verify off
-The highlighted part will not display
4+1
----------
5
Show user
>show user;
User is ‘HR’
-Show the current user
Set timing on
Set timing off
>set timing on
-used to display time taken to execute a query in the bottom of
the page
Spool
-used to store query and output of query in a txt file
>spool d:\new\2.txt
>select * from course;
cid cname
10 sql
1 row selected
>spool off
-spool stop
-Save and exit to write in a file
-Now check 2.txt file in d:\new
1 row selected
Ed
-The last query open in note pad, then edit and save, quit
-After quit from notepad , the edited query will display in prompt
@
>@d:\new\1.txt
/
-used to execute last executed query.
Exit
quit
Table Exports/Imports
The TABLES parameter is used to specify the tables that are to be exported. The following is an
example of the table export and import syntax.
Schema Exports/Imports
The OWNER parameter of exp has been replaced by the SCHEMAS parameter which is used to
specify the schemas to be exported. The following is an example of the schema export and
import syntax.
Database Exports/Imports
The FULL parameter indicates that a complete database export is required. The following is an
example of the full database export and import syntax.
What is migration?