Tuesday, July 28, 2015

Basics of SQL

1.What is Database :

A database is a collection of information that is organized so that it can easily be accessed, managed, and updated. In one view, databases can be classified according to types of content 

2.What is a table :

Tables are the basic unit of data storage in an Oracle Database. Data is stored in rows and columns. You define a table with a table name, such as employees , and a set of columns.

basic syntax to create table : 

CREATE TABLE table_name ( column1 datatype [ NULL | NOT NULL ], column2 datatype [ NULL | NOT NULL ], ... column_n datatype [ NULL | NOT NULL ] );

Create table Murthy (sno number,name varchar2);

 

3.What is view :

A view is a named and validated SQL query which is stored in the Oracle data dictionary. Views do not contain any data - it is just a stored query in the database that can be executed when called. One can think of a view as a virtual table or mapping of data from one or more tables

Syntax to create a view : 
 
CREATE VIEW emp_view AS SELECT last_name, salary*12 annual_salary FROM employees WHERE department_id = 20;


4.What is join and types of joins :

  • INNER JOIN: Returns all rows when there is at least one match in BOTH tables
  • LEFT JOIN: Return all rows from the left table, and the matched rows from the right table
  • RIGHT JOIN: Return all rows from the right table, and the matched rows from the left table
  • FULL JOIN: Return all rows when there is a match in ONE of the tables
Note :
LEFT JOIN is same as LEFT OUTER JOIN

RIGHT JOIN is same as RIGHT OUTER JOIN

5. Oracle Constraints :

  • Not null

  • Unique Constraint

  • Primary Key

  •  Foreign key

  • Check constraint

A NOT NULL constraint prohibits a database value from being null.

A unique constraint prohibits multiple rows from having the same value in the same column or combination of columns but allows some values to be null.

A primary key constraint combines a NOT NULL constraint and a unique constraint in a single declaration. That is, it prohibits multiple rows from having the same value in the same column or combination of columns and prohibits values from being null.

A foreign key constraint requires values in one table to match values in another table.

A check constraint requires a value in the database to comply with a specified condition.

A REF column by definition references an object in another object type or in a relational table. A REF constraint lets you further describe the relationship between the REF column and the object it references.
 

6.What is the difference between primary key and unique key

Unique KeyPrimary Key
A table can contain more than one unique keyA table can contain only one primary key (can be one/more columns)
Unique key allows one null valuePrimary key will not allow null values

7.What are DDL and DML commands .

DDL (DataDifinition Language)DML (Data Manipulation Language)
CreateSelect
AlterInsert
TruncateUpdate
DropDeletet

8. What is the difference between “delete” , “truncate” and “drop” commands
 
Delete CommandTruncate CommandDrop Command
Delete Command Belongs to DMLTruncate Command Belongs to DDLDrop Command Belongs to DDL
Can be Used to delete entire Table dataCan be Used to delete entire Table dataCan be Used to delete entire Table data and also the structure
Can be used to delete specific rows using where clauseCan't be used to delete specific rows using where clauseCan't be used to delete specific rows using where clause
Can be rolled backCan't be rolled backCan't be rolled back

 
9. Relation between views and tables

Tables are the actual database entities that hold your rows.
Views are "imaginary" tables that are constructed based on the actual tables.

A table contains data, a view is just a SELECT statement which has been saved in the database
The advantage of a view is that it can join data from several tables thus creating a new view of it. Say you have a database with salaries and you need to do some complex statistical queries on it.

Instead of sending the complex query to the database all the time, you can save the query as a view and then SELECT * FROM view

Syntax : 
CREATE VIEW view_name AS SELECT columns
  FROM tables WHERE conditions;

10. What are function,trigger and stored procedures :
A stored procedure is a user defined piece of code written in the local version of PL/SQL, which may return a value that is invoked by calling it explicitly.

A trigger is a stored procedure that runs automatically when various events happen (eg update, insert, delete).


A function is a user defined piece of code and it should return a value making it a function.

Syntax : 
Procedure : 
CREATE [OR REPLACE] PROCEDURE procedure_name
    [ (parameter [,parameter]) ]
IS
   [declaration_section]
BEGIN
    executable_section
[EXCEPTION
    exception_section]
END [procedure_name];


11. What is the purpose of ‘distinct’ in sql

Distinct is used to display unique values
Ex:
Select distinct from
Select distinct ename from emp

12. What is the difference between union and union all
UNION removes duplicate records (where all columns in the results are the same), UNION ALL does not.

There is a performance hit when using UNION vs UNION ALL, since the database server must do additional work to remove the duplicate rows, but usually you do not want the duplicates (especially when developing reports).

ORA-03113: & ORA-19809: & ORA-19804: &ORA-19815: WARNING: db_recovery_file_dest_size is 100.00% used,

It might be just because the lack of space in the recovery dest.

SQL> startup
ORACLE instance started.

Total System Global Area  778387456 bytes
Fixed Size                  1374808 bytes
Variable Size             385877416 bytes
Database Buffers          385875968 bytes
Redo Buffers                5259264 bytes
Database mounted.
ORA-03113: end-of-file on communication channel
Process ID: 4152
Session ID: 5 Serial number: 3

Check the alert log for further investination.
==============================================
contents from alert log
=======================
ORA-19815: WARNING: db_recovery_file_dest_size of 4039114752 bytes is 100.00% used, and has 0 remaining bytes available.
Errors in file c:\app\rpilla\diag\rdbms\mntest1\mntest1\trace\mntest1_arc2_4956.trc:
ORA-19809: limit exceeded for recovery files
ORA-19804: cannot reclaim 2866688 bytes disk space from 4039114752 limit

ORA-19815: WARNING: db_recovery_file_dest_size of 4039114752 bytes is 100.00% used, and has 0 remaining bytes available.
************************************************************************
You have following choices to free up space from recovery area:
1. Consider changing RMAN RETENTION POLICY. If you are using Data Guard,
   then consider changing RMAN ARCHIVELOG DELETION POLICY.
2. Back up files to tertiary device such as tape using RMAN
   BACKUP RECOVERY AREA command.
3. Add disk space and increase db_recovery_file_dest_size parameter to
   reflect the new space.
4. Delete unnecessary files using RMAN DELETE command. If an operating
   system command was used to delete files, then use RMAN CROSSCHECK and
   DELETE EXPIRED commands.
************************************************************************
I used the 4th suggestion by deleting archive log files from db_recovery_file_dest.

login

rman target /

list backup;
list copy;
delete archivelog all;


ORA-19815: WARNING: db_recovery_file_dest_size is 100.00% used,


Sat May 30 08:28:20 2015
ARC2 started with pid=22, OS id=38112
ARC1: Archival started
ARC2: Archival started
ARC1: Becoming the 'no FAL' ARCH
ARC1: Becoming the 'no SRL' ARCH
ARC2: Becoming the heartbeat ARCH
Sat May 30 08:28:20 2015
ARC3 started with pid=23, OS id=39704
Errors in file e:\app\murthy\diag\rdbms\orcl\orcl\trace\orcl_arc1_39816.trc:
ORA-19815: WARNING: db_recovery_file_dest_size of 4039114752 bytes is 100.00% used, and has 0 remaining bytes available.
Errors in file e:\app\murthy\diag\rdbms\orcl\orcl\trace\orcl_ora_38608.trc:
ORA-19815: WARNING: db_recovery_file_dest_size of 4039114752 bytes is 100.00% used, and has 0 remaining bytes available.
************************************************************************
You have following choices to free up space from recovery area:
1. Consider changing RMAN RETENTION POLICY. If you are using Data Guard,
   then consider changing RMAN ARCHIVELOG DELETION POLICY.
2. Back up files to tertiary device such as tape using RMAN
   BACKUP RECOVERY AREA command.
3. Add disk space and increase db_recovery_file_dest_size parameter to
   reflect the new space.
4. Delete unnecessary files using RMAN DELETE command. If an operating
   system command was used to delete files, then use RMAN CROSSCHECK and
   DELETE EXPIRED commands.
************************************************************************
Errors in file e:\app\murthy\diag\rdbms\orcl\orcl\trace\orcl_ora_38608.trc:
ORA-19809: limit exceeded for recovery files
ORA-19804: cannot reclaim 44892672 bytes disk space from 4039114752 limit
ARCH: Error 19809 Creating archive log file to 'E:\APP\MURTHY\FLASH_RECOVERY_AREA\ORCL\ARCHIVELOG\2015_05_30\O1_MF_1_98_%U_.ARC'
Errors in file e:\app\murthy\diag\rdbms\orcl\orcl\trace\orcl_ora_38608.trc:
ORA-16038: log 2 sequence# 98 cannot be archived
ORA-19809: limit exceeded for recovery files
ORA-00312: online log 2 thread 1: 'E:\APP\MURTHY\ORADATA\ORCL\REDO02.LOG'
USER (ospid: 38608): terminating the instance due to error 16038
************************************************************************
You have following choices to free up space from recovery area:
1. Consider changing RMAN RETENTION POLICY. If you are using Data Guard,
   then consider changing RMAN ARCHIVELOG DELETION POLICY.
2. Back up files to tertiary device such as tape using RMAN
   BACKUP RECOVERY AREA command.
3. Add disk space and increase db_recovery_file_dest_size parameter to
   reflect the new space.
4. Delete unnecessary files using RMAN DELETE command. If an operating
   system command was used to delete files, then use RMAN CROSSCHECK and
   DELETE EXPIRED commands.
************************************************************************
Instance terminated by USER, pid = 38608

To check the free space :

select name,
floor(space_limit/1024/1024) "Size_MB",
ceil(space_used/1024/1024) "Used_MB"
from v$recovery_file_dest
order by name;
/
  Solution : 

  open CMD>

1. RMAN
2. connect /
3. crosscheck archivelog all;
4. delete archivelog all completed before 'sysdate -7';
5. Prompt for Yes or No
6. Y and enter
7. exit

C:\Users\jnmurthy>rman target /

Recovery Manager: Release 11.2.0.1.0 - Production on Sat May 30 08:44:13 2015

Copyright (c) 1982, 2009, Oracle and/or its affiliates.  All rights reserved.

connected to target database: ORCL (DBID=1381995653)

RMAN> show all;

using target database control file instead of recovery catalog
RMAN configuration parameters for database with db_unique_name ORCL are:
CONFIGURE RETENTION POLICY TO REDUNDANCY 1; # default
CONFIGURE BACKUP OPTIMIZATION OFF; # default
CONFIGURE DEFAULT DEVICE TYPE TO DISK; # default
CONFIGURE CONTROLFILE AUTOBACKUP OFF; # default
CONFIGURE CONTROLFILE AUTOBACKUP FORMAT FOR DEVICE TYPE DISK TO '%F'; # default
CONFIGURE DEVICE TYPE DISK PARALLELISM 1 BACKUP TYPE TO BACKUPSET; # default
CONFIGURE DATAFILE BACKUP COPIES FOR DEVICE TYPE DISK TO 1; # default
CONFIGURE ARCHIVELOG BACKUP COPIES FOR DEVICE TYPE DISK TO 1; # default
CONFIGURE MAXSETSIZE TO UNLIMITED; # default
CONFIGURE ENCRYPTION FOR DATABASE OFF; # default
CONFIGURE ENCRYPTION ALGORITHM 'AES128'; # default
CONFIGURE COMPRESSION ALGORITHM 'BASIC' AS OF RELEASE 'DEFAULT' OPTIMIZE FOR LOAD TRUE ; # default
CONFIGURE ARCHIVELOG DELETION POLICY TO NONE; # default
CONFIGURE SNAPSHOT CONTROLFILE NAME TO 'E:\APP\MURTHY\PRODUCT\11.2.0\DBHOME_1\DATABASE\SNCFORCL.ORA'; # default


before deleted the file location and size
SYS@orcl:SQL>show parameter recovery_file_dest;

NAME                                 TYPE        VALUE
------------------------------------ ----------- ------------------------------
db_recovery_file_dest                string      E:\app\Murthy\flash_recovery_area
db_recovery_file_dest_size           big integer 30M


Above 3rd and 4th command check for the archieve log file and delete the old archieve log file which is older than the week from current date.
So Now we have free space in "flash_recovery_area" .
 After deleted the backup-ed archive files:

SYS@orcl:SQL>show parameter recovery_file_dest;

NAME                                 TYPE        VALUE
------------------------------------ ----------- ------------------------------
db_recovery_file_dest                string      E:\app\Murthy\flash_recovery_area
db_recovery_file_dest_size           big integer 300M
After successfully deleted will get the space and then try to startup the db.

SYS@orcl:SQL>startup
ORACLE instance started.

Total System Global Area 1071333376 bytes
Fixed Size                  1375792 bytes
Variable Size             713032144 bytes
Database Buffers          352321536 bytes
Redo Buffers                4603904 bytes
Database mounted.
Database opened.

more commands :

SQL> show parameter alert
NAME                                 TYPE        VALUE
------------------------------------ ----------- ------------------------------
log_checkpoints_to_alert             boolean     FALSE

SQL> show parameter BACKGROUND_DUMP_DEST
NAME                                 TYPE        VALUE
------------------------------------ ----------- ------------------------------
background_dump_dest                 string      e:\app\****\diag\rdbms\za1\za1\trace

SQL> show parameter db_recovery_file_dest_size
NAME                                 TYPE        VALUE
------------------------------------ ----------- ------------------------------
db_recovery_file_dest_size           big integer 3852M