Você está na página 1de 13

SQL(Structured Query Language)

Relational databases and SQL were developed in the early 1970s at IBM.In 1979, Oracle
released the first commercial relational database that used SQL. In 1986,
the American National Standards Institute (ANSI) began publishing SQL standards.
DDL(Data Definition Language):

These are autocommit statement.


Create :

Create database objects.


Alter :

Alter the structure of the database objects.


Drop :

Removes the object from the database.


Truncate:

Permanently removes data from the table not the structure of the table.
Comment :

Add comments to the database object.


Rename:

Rename the database .


DML(Data Manipulation Language) :

Requires explicit commit

Insert :

Insert records into the table.


Update:

Update existing records present in the table.


Delete:

Removes records from the table.


Select :

Retrives records from the table.(Select statement does not do any database changes but
Oracle considers it as DML statement).
Merge:

Conditional Insert and Update statement.


TCL(Transactional Control Language) :

Do the changes made by dml statement


Commit :

Do the permanent changes to the database.


Rollback :

restore the changes to original since from last commit.


Savepoint :

Acts like a marker to a transaction that can be rollback later.


DCL(Data Control Language) :

Grant :

Provides access privileges to the User.

Revoke:

Revokes the privileges from the user given by Grant.


Database Objects :

Tables:

Combination of rows and columns and stores the data.Must begin with a letter and must
not contain oracle reserve words and be Unique in the database and 1-30 characters long
and Create table privilege to create the table.
syntax:

Create table [schema.] tablename


(column_name datatype(size));

Constraints:

Oracle server uses constrains to prevent invalid data entry into table.
NULL / NOT NULL :

NOT NULL specifies that a column must have some value. NULL (default) allows NULL
values in the column.
DEFAULT:

Specifies some default value if no value entered during INSERT


UNIQUE:

Specifies that column(s) must have unique values. Index is automatically generated for
column
PRIMARY KEY :

Specifies that column(s) must have unique values. Index is automatically generated for
column

FOREIGN KEY :

Specifies that column(s) are defined primary key in another table. Used for referential
uniqueness of parent table. Index is automatically generated for column
CHECK :

Applies a condition to an input column value


DISABLE :

Suffix DISABLE to any other constraint to make Oracle ignore the constraint, the
constraint will still be available to applications / tools and you can enable the constraint
later if required.
Data dictionary views:

Four categories .User_,All_,Dba_,v$


Views :

Restrictive data access ,different views of same data ,making complex query easy.
Difference between simple view and complex view ?
Simple view :based on one table,dml operation is possible ,no group functions and
functions.
Complex view :based on one or more than one table ,dml operation is not possible ,can
Contain group functions and group data.
syntax:-

Create [or replace] [force|noforce] view viewname(alias)


As subquery
[with check option [constraint constname]]
[with read only ]
with check option : the rows that is accessible to the view can be inserted or updated.
Force :created the view whether base table exists or not.
Noforce :created the view if the base table is exists.
With read only :no dml operation is possible.
Replace : modifies the view.
Inline views : A named subquery in the FROM clause of the main query .is not an schema
object.
Drop view viewname ;

(removes the view from the database)


Materialized Views:

A materialized view is a database object that contains the results of a query. They are local
copies of data located remotely.
syntax:-

CREATE MATERIALIZED VIEW [REFRESH [FAST|COMPLETE|FORCE]] [START WITH


DATE] [NEXT DATE ] [WITH PRIMARY KEY | ROWID]

Refresh option states how the refresh of remote data occurs. Fast options specifies that the
modified data be transferred through the materialized view logs ( table)
Refresh Complete states that the data be refreshed completely. Force will choose fast
refresh if possible else do complete refresh.Start date states from when refresh should start
and next date gives the duration Primary key or rowid specifies which is the used as the
key in master table.
Index :

A schema object used to improve the query performance and avoids full
Table scan. Indexes are logically and physically independent of the table.Removing a table
indexes are dropped. Altering of the index is not possible.
Create index indexname on tablename(columnname);

Unique index :

primary key and unique key columns automatically creates unique index.
Non unique index :

explicitly create index on the column name of the table.


Drop Index indexname ;

(removes the index from the database.)


Not to create index :

If the table is small and updated frequently.columns are not used In condition.queries
expected to retrive more than 2-4 percent of the rows in the table.
Use :

column contains large no. of null values and wide range of data.frequently use in the
condition. Retrive less than 2-4 percent row.
Sequence :

A schema shareble object used to generate unique numbers.


Create sequence sequenname Increament by n
Start with n maxvalue n|nomaxvalue
minvalue n|nominvalue
cycle|nocycle
Cache|nocache

Cache n|nocache :

specifies how many values the oracle server keeps in memory.default 20


Cycle:

whether sequence continues to generate values after reaching is max


And min value.
Gaps in sequence :

rollback occurs,system crashes,used in another table.


Drop sequence sequencename;

(removes the sequence from the database)


Synonym :

A schema object used to refer the name of the object .


Create [public] synonym synname for objectname;

Drop synonym synonymname;

(removes the name of the synonym)

JOINS :

A join is a query that combines rows from two or more tables, views, or materialized
views.
Oracle performs a join whenever multiple tables appear in the query's FROM clause.
The query's select list can select any columns from any of these tables.
If any two of these tables have a column name in common, then you must qualify all
references to these columns throughout the query with table names to avoid ambiguity.
Most join queries contain WHERE clause conditions that compare two columns, each
from a different table. Such a condition is called a join condition.
In addition to join conditions, the WHERE clause of a join query can also contain other
conditions that refer to columns of only one table. These conditions can further restrict the
rows returned by the join query.

Equi-joins:

An equijoin is a join with a join condition containing an equality operator.


An equijoin combines rows that have equivalent values for the specified columns

Nonequi-joins:

An non equijoin is a join with a join condition containing other than equality operator.

Self Join:

A self join is a join of a table to itself.


This table appears twice in the FROM clause and is followed by table aliases that qualify
column names in the join condition.

Outer Join:

An outer join returns all rows that satisfy the join condition and also returns some or all of
those rows from one table for which no rows from the other satisfy the join condition

Left Outer Join:

Left outer join means all rows of the table left to the Join condition will appear

Right Outer Join:

right outer join means all rows of the table right to the Join condition will appear

Full Outer Join:

Full Outer, means missing rows from both the tables being joined.
Subquery:

A subquery is a select statement that is nested within another select statement .


Subqueries may be:

Single Row Subquery

(single row comparison operators can be used e.g. =, <, >, <=, >= etc.)
Multiple row subquery

(Multi row comparison operator e.g. IN,SOME/ANY or ALL operators)


Correlated Sub-Query:

Correlated subqueries enable you to use an outside reference to the query.The subquery
will get executed once for every row returned by the main query.
Functions:

Types of Functions

Single-row functions:

Operate on single-rows only and returns one result per row


Multiple-row functions:

Operate on groups of rows and produce one result per group of rows

Single Row Functions:

Are of the following types:


Character
Number
Date
Conversion
MULTIPLE-ROW-FUNCTION:

Operates on sets of rows to to give one result per group


SUM
AVG
MAX
MIN
COUNT(*)
COUNT(column name)
All group functions except COUNT(*) ignore NULL
MAX and MIN functions can be used for any datatype
Set Operators:

Set operators combine the results of two component queries into a single result
Major set operators
UNION:

All distinct rows selected by either query.


UNION ALL:

All rows selected by either query, including all duplicates.


INTERSECT:

All distinct rows selected by both queries.


MINUS:

All distinct rows selected by the first query but not the second.
Note:

The set operators are not valid on columns of type BLOB, CLOB, BFILE, VARRAY, or

nested table.

Display Quarter Start and End Dates for the Year


sql>SELECT ROWNUM qtr,ADD_MONTHS(TRUNC(SYSDATE,'y'),(rownum-1)*3) q_start,
ADD_MONTHS(TRUNC(SYSDATE,'y'),ROWNUM*3)-1 q_end
FROM emp WHERE ROWNUM <= 4

Display the records between two range ?


SQL>select rownum, empno, ename
from emp where rowid in
(select rowid from emp where rownum <=&upto
minus
select rowid from emp where rownum<&Start);

Enter value for upto: 10


Enter value for Start: 7
ROWNUM EMPNO ENAME
--------- --------- ---------1 6658 SMITH
2 6659 SCOTT
3 6687 KING
4 6675 TURNER

how to see all the indexes created on a particular table? how to view all the
indexes in a tablespace?

To see all the indexes created on a particular table you need to query all_indexes
specifying the name of the table.
example:
sql>SELECT index_name FROM all_indexes WHERE table_name = 'EMP';
To see all the indexes in a particular tablespace you just have to query all_indexes
specifying the name of the tablespace.
example:
sql>SELECT index_name FROM all_indexes WHERE tablespace_name =
'USERS';

Determining the First and Last Day of a Month?


sql>select trunc(sysdate,mm)firstday,
last_day(sysdate)lastday from dual;

display firstday and lastday of all months?


sql>select add_months(trunc(sysdate,'y'),rownum-1)first_day,
last_day(trunc(sysdate,'y'))last_day
from emp where rownum<=12;

display firstday and lastday of all months?


select add_months(trunc(sysdate,'y'),rownum-1)first_day,
last_day(trunc(sysdate,'y'))last_day
from emp where rownum<=12;

display name of all the manager in the employee table?


sql>select ename from emp
where empno in(select distinct mgr from emp);

lastday of ayear?

sql>select add_months(last_day(trunc(sysdate,'y')),11)
from dual;

display hour,min,sec,day,month,year?
sql>SELECT TO_CHAR(SYSDATE,'hh24') HOUR,
TO_CHAR(SYSDATE,'mi') MIN,
TO_CHAR(SYSDATE,'ss') sec,
TO_CHAR(SYSDATE,'dd') DAY,
TO_CHAR(SYSDATE,'mm') mth,
TO_CHAR(SYSDATE,'yyyy') YEAR
FROM dual;

Display duplicate record?


sql>select * from emp a
where( select count(*) from emp b
where b.eno= a.eno) > 1;

Delete duplicate row?


sql>Delete from emp a where Rowid not in (select max(rowid) from emp b
where a.eno=b.eno);

Difference Between Count(*),Count(1), Count(column_name)


In the query count(*) and count(1) are interchangeably used,
But count(*) is not good due to the performance reason, because parser writes the
name of all column in the table in place of * before executing query.
Count(column_name) return count of only not null values of that column.

What is a Cartesian product ?


Produced as a result of a join select statement with no where clause

Is sqrt() a group function ?


NO

What is the difference between UNION and UNION ALL?


Union eliminates duplicate rows while combining two result sets. While Union All
does not do any thing with result set. It shows duplicate rows also.

maxvalue.sql Select the Nth Highest value from a table?


sql> select level, max('col_name') from my_table where level = '&n' connect by prior ('col_name') >
'col_name')
group by level;

maxvalue.sql Select the Nth Highest value from a table?


sql> select level, max('col_name') from my_table where level = '&n' connect by prior ('col_name') >
'col_name')
group by level;

Você também pode gostar