0% found this document useful (0 votes)
6 views23 pages

SQL_Tutorial_PCC-CS691

The document provides an introduction to SQL, covering essential commands, syntax, and functions used in SQL statements. It includes details on selecting data, using various operators, and performing joins between tables. Additionally, it explains SQL functions, grouping data, and the differences between SQL and SQL*Plus environments.

Uploaded by

ranitmanik555
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
6 views23 pages

SQL_Tutorial_PCC-CS691

The document provides an introduction to SQL, covering essential commands, syntax, and functions used in SQL statements. It includes details on selecting data, using various operators, and performing joins between tables. Additionally, it explains SQL functions, grouping data, and the differences between SQL and SQL*Plus environments.

Uploaded by

ranitmanik555
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 23

Introduction to SQL

Objectives
 SQL SELECT statements
 A basic SELECT statement
 SQL statements and SQL*Plus commands

SQL Command Set

DQL : SELECT
DDL : CREATE, ALTER, DROP
DML : INSERT, UPDATE, DELETE
DCL : GRANT, REVOKE
TCL : COMMIT, ROLLBACK

To see the structure of the Tables in SQL *PLUS

SQL> DESC Table_Name

SELECT [DISTINCT] {*, column [alias],...}


FROM table;

Writing SQL Statements


• SQL is not Case Sensitive.
• Tabs and Indentations will promote readability.
• Keywords cannot be split or abbreviated.
• SQL Statements can be split across lines.
• Clauses are placed in different lines, to promote readability.

TABLES:
(Examples are based on default Employee (EMP), Department and Salgrade tables of ORACLE
RDBMS)
EMP(empno, ename, job, mgr, hiredate, sal, comm, deptno)
Department(deptno, dname, loc)
Salgrade(losal, hisal)

Selecting All Columns

SQL> SELECT *
2 FROM department;

Selecting Specific Columns

SQL> SELECT deptno, loc


2 FROM department;
Default Column Headings

• Default justification
• Date and Character Data is Left Justified
• Numeric Data is Right Justified
• Display Headings in UPPER CASE.
• Character / Date Columns headings will be truncated.
• Numerical Columns headings are not truncated.
• Alias name can be replaced by the column name.

Arithmetic Expressions
 Basic Arithmetic operators & Precedence ( * and / followed by + and - )
+ - * /

Using Arithmetic Operators

SQL> SELECT ename, sal, sal+300


2 FROM employee;

Operator Precedence

SQL> SELECT ename, sal, 12*sal+100


2 FROM employee;

Defining a Null Value

• NULL is UNASSIGNED Value.

SQL> SELECT ename, job, comm


2 FROM employee;

Comparison Operators
= , > , >= , < , <= , <>

Logical Operators
AND , OR , NOT

SQL> SELECT empno, ename, job, sal


2 FROM employee
3 WHERE sal>=1100
4 AND job='CLERK';

SQL> SELECT ename, job


2 FROM employee
3 WHERE job NOT IN ('CLERK','MANAGER','ANALYST');
Set Operators
Union, Union all, Intersect, Minus

More Comparison Operators

BETWEEN (v1 AND v2) : Between two values v1 and v2 (inclusive)


IN(list) : Match any of a list of values
LIKE : Match a character pattern
IS NULL : Is a null value

Example

 Use of BETWEEN & IN operators

SQL> SELECT ename, sal


2 FROM employee
3 WHERE sal BETWEEN 1000 AND 1500;

SQL> SELECT empno, ename, sal, mgr


2 FROM employee
3 WHERE mgr IN (7902, 7566, 7788);

 Like Keyword does Wildcard Searches in Valid String Values.


% ---------- zero or many characters
_ ---------- one character

SQL> SELECT ename


2 FROM employee
3 WHERE ename LIKE 'S%';

SQL> SELECT ename


2 FROM employee
3 WHERE ename LIKE ‘_A%‘;

SQL> SELECT ename, mgr


2 FROM employee
3 WHERE mgr IS NULL;

Null Values in Arithmetic Expr

• NULL as an operand will result NULL

SQL> select ename NAME, 12*sal+comm


2 from employee
3 WHERE ename='KING';
Defining Column Alias
 The Heading name is replaced for the current SELECT Statement.
 AS Keyword [ Optional ] between the column name and the actual alias name
 Double Quotation Marks.

Using Column Aliases

SQL> SELECT ename AS name, sal salary


2 FROM employee;

Output

NAME SALARY
------------- ------------
...

SQL> SELECT ename "Name",


2 sal*12 "Annual Salary"
3 FROM employee;

Output

Name Annual Salary


------------- ------------------
...

Concatenation Operator (||)


• Concatenates the Columns of any data type.
• A Resultant column will be a Single column.

Using Concatenation Operator

SQL> SELECT ename || job AS "Employees"


2 FROM employee;

Output

Employees
-------------------
KINGPRESIDENT
BLAKEMANAGER
CLARKMANAGER
JONESMANAGER
MARTINSALESMAN
ALLENSALESMAN
...
14 rows selected.
Literal Character Strings
• Date and character literal values must be enclosed within single quotation marks.

Character Strings and Dates


• Character / Dates are Represented by the Single Quotation Marks.
• Default date format is 'DD-MON-YY'

Using ‘DISTINCT’ Clause


• Eliminate duplicate rows by using the DISTINCT keyword

SQL> SELECT DISTINCT deptno


2 FROM employee;

SQL Vs SQL*Plus

SQL
• A language
• Keyword cannot be abbreviated
• Statements manipulate data and table definitions in the database
• SQL statements are stored in buffer

SQL*Plus
• An environment
• Keywords can be abbreviated
• Commands do not allow manipulation of values in the database
• SQL*PLUS statements are not stored in Buffer

SQL*Plus Commands
– A[PPEND] text
– C[HANGE] / old / new
– C[HANGE] / text /
– CL[EAR] BUFF[ER]
– DEL
– DEL n
– DEL m n
– I[NPUT]
– I[NPUT] text
– L[IST]
– L[IST] n
– L[IST] m n
– R[UN]

SQL*Plus File Commands


– SAVE filename
– GET filename
– START filename
– @ filename
– EDIT filename
– SPOOL filename
Summary

SELECT [DISTINCT] {*,column[alias],...}


FROM table;

• Use SQL*Plus as an environment to:


– Execute SQL statements
– Edit SQL statements

Using 'Where' and 'Order By' Clauses

 Using ‘WHERE’ Clause

SELECT [DISTINCT] {*, column [alias], ...}


FROM table
[WHERE condition(s)];

Example

SQL> SELECT ename, job, deptno


2 FROM employee
3 WHERE job='CLERK';

 ORDER BY’ Clause


Sort rows specified by the order: ASC/DESC
Default ordering is ASC

Example

SQL> SELECT ename, job, deptno, hiredate


2 FROM employee
3 ORDER BY hiredate;

SQL> SELECT ename, job, deptno, hiredate


2 FROM employee
3 ORDER BY hiredate DESC;

Sorting the rows by Alias

SQL> SELECT empno, ename, sal*12 annsal


2 FROM employee
3 ORDER BY annsal;

Sorting by Multiple Columns


The order of ORDER BY list is the order of sort.

SQL> SELECT ename, deptno, sal


2 FROM employee
3 ORDER BY deptno, sal DESC;
Summary

SELECT [DISTINCT] {*, column [alias], ...}


FROM table
[WHERE condition(s)]
[ORDER BY {column, expr, alias} [ASC|DESC]];

SQL Functions:
Objectives
Get an awareness of the Various SQL Functions available.
• Types of Functions in the SELECT Statement.
• Conversion functions

Types of SQL Functions

1. Single-row functions
2. Multiple-row functions

Single-row functions : Act on every row as a result of every row.

function_name (column | expression, [arg1, arg2,...])

 Character : CONCAT, SUBSTR, LENGTH, INSTR, RPAD, LPAD, LOWER, UPPER,


INITCAP,
CONCAT('Good', 'String') : GoodString
SUBSTR('String',1,3): Str
LENGTH('String') : 6
INSTR('String', 'r') : 3
LPAD(sal,10,'*'): ******5000
LOWER('SQL Course') : sql course
UPPER('SQL Course'): SQL COURSE
INITCAP('SQLCourse'): Sql Course

 Numeric : ROUND, TRUNC, MOD, ABS, FLOOR, CEIL, SQRT,

ROUND(45.926, 2) : 45.93
TRUNC(45.926, 2) : 45.92
MOD(1600, 300) : 100
CEIL(23.2) : 24

 DATE
1. Default date format is DD-MON-YY.
2. SYSDATE is a Function which returns the System date and time.
3. DUAL is a dummy table used to view SYSDATE.
4. Add/Subtract a Number to the Date.
5. Add/Subtract hours to a date by dividing the number of hours by 24.
MONTHS_BETWEEN : Number of months between two dates
ADD_MONTHS : Add calendar months to date
NEXT_DAY : Next day of the date specified
LAST_DAY : Last day of the month
ROUND : Round date
TRUNC : Truncate date

 Conversion ()
1. VARCHAR2 / CHAR to NUMBER : TO_NUMBER(‘char’)
2. NUMBER to VARCHAR2 : TO_CHAR(number)

DATE functions
3. DATE to VARCHAR2 : TO_CHAR(date, ‘fmt’)
4. VARCHAR2 / CHAR to DATE : TO_DATE(‘string’, ‘date format’)

Example

SQL> SELECT SYSDATE


2 FROM DUAL;

SQL> SELECT TO_CHAR(SYSDATE, ‘ DAY, DDTH MONTH YYYY’)


2 FROM DUAL;

OUTPUT

TO_CHAR(SYSDATE, ‘DAY,DDTHMONTHYYYY)
---------------------------------------------------------------------------
FRIDAY , 23RD JULY 2010

Note: To remove the blank padding use fm (fill mode) prefix

SQL> SELECT TO_CHAR(SYSDATE, ‘ fmDay, ddth Month YYYY’)


2 FROM DUAL;

OUTPUT

TO_CHAR(SYSDATE,
----------------------------------------
Friday, 23rd July 2010

Date Format

YYYY : Full year in numbers


YEAR : Year spelled out
MM : 2-digit value for month
MONTH : Full name of the month
DY : 3-letter abbreviation of the day of the week
DAY : Full name of the day
Suffixes

TH : Ordinal number (e.g., ‘DDTH’ for 24TH)


SP : Spelled-out number(e.g., ‘DDSPTH’ for TWENTY FOUR)
SPTH : Spelled-out ordinal numbers(e.g., ‘DDSPTH’ TWENTY FOURTH)

Note: The Codes are case sensitive and will affect display of date elements

DAY : FRIDAY
Day : Friday
Month : July
ddth : 24th

Example: To show all employees hired on June 4, 1984(non-default format)


SQL> SELECT EMPNO, ENAME, HIREDATE
2 FROM EMPLOYEES
3 WHERE HIREDATE= TO_DATE(‘June 4, 1984’ , ‘Month dd, yyyy’);

SQL> SELECT TO_CHAR(TO_DATE('23/07/2010','DD/MM/YYYY'), 'fmDD Month YYYY')


2 FROM DUAL;

 Others: NVL
SQL> SELECT ename, sal, comm, (sal*12)+NVL(comm,0)
2 FROM employee;

Multiple-row functions(Group Functions)


: Operate on sets of rows to give one result per group (AVG , COUNT , MAX, MIN , SUM )

SQL> SELECT column, group_function(column)


FROM table
[WHERE condition]
[ORDER BY column];
Example
SQL> SELECT COUNT(*)
2 FROM employee
3 WHERE deptno = 30;
• COUNT(expr) returns the number of non null values in the given column.
SQL> SELECT COUNT(comm)
2 FROM employee
3 WHERE deptno = 30;
Output
COUNT(COMM)
-----------------------
4
• Group functions ignore null values in the column.
SQL> SELECT AVG(comm)
2 FROM employee;
Output

AVG(COMM)
------------------
550
• The NVL function forces group functions to include null values.

SQL> SELECT AVG(NVL(comm,0))


2 FROM employee;

Group By ………….Having Clause

The Order of Clauses in the SELECT Statement

SELECT column(s)
FROM table(s)
WHERE row condition(s)
GROUP BY column(s)
HAVING group of rows condition(s)
ORDER BY column(s);

GROUP BY : The GROUP BY clause can be used to divide the rows in a table into
smaller groups. Group functions may be used to return summary information for each group.

Example: To calculate the average salary for each different job type.

SQL> SELECT JOB, AVG(SAL)


2 FROM EMPLOYEE
3 BROPU BY JOB;

HAVING : The HAVING clause is very similar to WHERE clause except the
statements within it are of an aggregate nature

Example: To display the average salary for all departments employing more than three people.

SQL> SELECT DEPTNO, AVG(SAL)


2 FROM EMPLOYEE
3 BROPU BY DEPTNO
4 HAVING COUNT(*) > 3;
SQL> SELECT DEPTNO, JOB, SUM(SAL) AS salary
2 FROM EMPLOYEE
3 BROPU BY ROLLUP(DEPTNO, JOB);

SQL> SELECT DEPTNO, JOB, SUM(SAL) AS salary


2 FROM EMPLOYEE
3 BROPU BY CUBE(DEPTNO, JOB);

JOINS:
A join is used when a SQL query requires data from more than one table on database.

Note1: A join condition is specified in the WHERE clause.


Note2: Table Alias can be used in the FROM clause. Table alias should also be used in the
SELECT clause.

Types of join : EQUI-JOIN, NON-EQUI-JOIN, OUTER-JOIN

EQUI-JOIN

Example: To Display employee’s name, job and their departments name

SQL> SELECT ENAME, JOB, DNAME


2 FROM EMPLOYEE, DEPARTMENT
3 WHERE EMPLOYEE.DEPTNO = DEPARTMENT.DEPTNO;

SQL> SELECT E.ENAME, E.JOB, D.DNAME


2 FROM EMPLOYEE E, DEPARTMENT D
3 WHERE E.DEPTNO = D.DEPTNO;

NON-EQUI-JOIN

Example: To Display employee’s name, salary and grade

SQL> SELECT E.ENAME, E.SAL, S.GRADE


2 FROM EMPLOYEE E, SALGRADE S
3 WHERE E.SAL BETWEEN S.LOSAL AND S.HISAL;
OUTER-JOIN : LEFT, RIGHT, FULL

Right outer join


SQL> SELECT E.ENAME, D.DEPTNO, D.DNAME
2 FROM EMPLOYEE E, DEPARTMENT D
3 WHERE E.DEPTNO(+) = D.DEPTNO;
OR
SQL> SELECT E.ENAME, D.DEPTNO, D.DNAME
2 FROM EMPLOYEE E RIGHT OUTER JOIN DEPARTMENT D
3 ON E.DEPTNO = D.DEPTNO;

Left outer join


SQL> SELECT E.ENAME, D.DEPTNO, D.DNAME
2 FROM EMPLOYEE E, DEPARTMENT D
3 WHERE E.DEPTNO = D.DEPTNO(+);
OR
SQL> SELECT E.ENAME, D.DEPTNO, D.DNAME
2 FROM EMPLOYEE E LEFT OUTER JOIN DEPARTMENT D
3 ON E.DEPTNO = D.DEPTNO;

Full outer join


SQL> SELECT E.ENAME, D.DEPTNO, D.DNAME
2 FROM EMPLOYEE E FULL OUTER JOIN DEPARTMENT D
3 ON E.DEPTNO = D.DEPTNO;

Set Operators:

Each set operators combines the results of two SELECT statements into a single result.
Data types should be same of both the tables.
Select statements must select the same number of columns
Column names from the first query appear in the result
ORDER BY clause appears at the end of statement
ORDER BY column position only

UNION
The UNION operator returns the records retrieved by either of the queries.
By default, UNION operator eliminates duplicate records
To retain duplicates, use UNION ALL instead of UNION .
SQL> SELECT JOB
2 FROM EMPLOYEE
3 WHERE DEPTNO =10
4 UNION
5 SELECT JOB
6 FROM EMPLOYEE
7 WHERE DEPTNO =20;

UNION ALL

SQL> SELECT JOB


2 FROM EMPLOYEE
3 WHERE DEPTNO =10
4 UNION ALL
5 SELECT JOB
6 FROM EMPLOYEE
7 WHERE DEPTNO =20;

INTERSECT

SQL> SELECT JOB


2 FROM EMPLOYEE
3 WHERE DEPTNO =10
4 INTERSECT
5 SELECT JOB
6 FROM EMPLOYEE
7 WHERE DEPTNO =20;

MINUS

SQL> SELECT JOB


2 FROM EMPLOYEE
3 WHERE DEPTNO =10
4 MINUS
5 SELECT JOB
6 FROM EMPLOYEE
7 WHERE DEPTNO =20;

ORDER BY Clause

SQL> SELECT EMPNO, ENAME, SAL


2 FROM EMPLOYEE1
3 UNION
4 SELECT ESSN, NAME, SALARY
5 FROM EMPLOYEE2
6 ORDER BY 2

NOTE: NUMERICAL 2 IS USED TO REPRESENT THE COLUMN ENAME IN SELECT


CLAUSE.
Sub-queries:
SELECT select_list
FROM table
WHERE expr operator
(SELECT select_list
FROM table);

• The sub-query (inner query) executes once before the main query.
• The result of the sub-query is used by the main query (outer query).

SQL> SELECT ename


2 FROM employee
3 WHERE sal >
4 (SELECT sal
5 FROM employee
6 WHERE empno=7566);

Guidelines for Sub-queries

• Enclose sub-queries in parentheses.


• Place sub-queries on the right side of the comparison operator.
• Do not add an ORDER BY clause to a sub-query.
• Use single-row operators with single-row sub-queries.
• Use multiple-row operators with multiple-row sub-queries.

Types of Sub-queries
• Single-Row sub-query(Single row comparison operator : =, <, <=, > ,>=, <>)

SQL>SELECT ename, job


2 FROM employee
3 WHERE job =
4 (SELECT job
5 FROM employee
6 WHERE empno = 7369)
7 AND sal >
8 (SELECT sal
9 FROM employee
10 WHERE empno = 7876);

SQL> SELECT deptno, MIN(sal)


2 FROM employee
3 GROUP BY deptno
4 HAVING MIN(sal) >
5 (SELECT MIN(sal)
6 FROM employee
7 WHERE deptno = 20);
• Multiple-Row sub-query(Multiple row comparison operator : ANY, IN, ALL)
IN : Equal to any member in the list
ANY : Compare value to each value returned by the sub-query
ALL : Compare value to every value returned by the sub-query

SQL> SELECT empno, ename, job


2 FROM employee
3 WHERE sal < ANY
4 (SELECT sal
5 FROM employee
6 WHERE job = 'CLERK')
7 AND job <> 'CLERK';

SQL> SELECT empno, ename, job


2 FROM employee
3 WHERE sal > ALL
4 (SELECT avg(sal)
5 FROM employee
6 GROUP BY deptno);

• Inline Views

SQL> SELECT a.ename, a.sal, a.deptno, b.salavg


2 FROM employee a, (SELECT deptno, avg(sal) salavg
3 FROM employee
4 GROUP BY deptno) b
5 WHERE a.deptno = b.deptno
6 AND a.sal > b.salavg;

• Multiple-column sub-query

SQL> SELECT ename , job


2 FROM employee
3 WHERE (deptno, sal) IN (SELECT deptno, MAX(sal)
4 FROM employee
5 GROUP BY deptno);
Co-related Sub-Query
 A correlated sub-query is a nested sub-query which is executed once for each candidate
row considered by the main query
 Steps to execute a correlated sub-query
1. Get candidate row(fetched by outer query)
2. Executed inner query using candidate row’s value
3. Use value(s) resulting from inner query to qalify or disqualify candidate.
4. Repeat until no candidate row remains.
 The EXISTS operator is frequently used with correlated sub-queries.
Example
To find employees who earn a salary greater than the average salary for their department

SQL> SELECT EMPNO, ENAME, SAL, DEPTNO


2 FROM employee E
3 WHERE SAL> (SELECT AVG(SAL)
4 FROM employee
5 WHERE DEPTNO=E.DEPTNO)
6. ORDER BY DEPTNO;

Example
To find employees who have at least one person reporting to them.

SQL> SELECT EMPNO, ENAME, JOB, DEPTNO


2 FROM employee E
3 WHERE EXISTS (SELECT EMPNO
4 FROM employee
5 WHERE employee.MGR=E.DEPTNO)
6. ORDER BY DEPTNO;

DDL Statements

Objectives

• Describe the main database objects


• Create tables
• Describe the data types that can be used when specifying column definition
• Alter table definitions
• Drop, rename, and truncate tables
Database Objects
Table: Basic unit of storage; composed of rows and columns
View: Logically represents subsets of data from one or more tables
Sequence: Generates primary key values
Index: Improves the performance of some queries
Synonym: Gives alternative names to objects

Naming Conventions
• Must begin with a letter
• Can be 1–30 characters long
• Must contain only A–Z, a–z, 0–9, _, $, and #
• Must not duplicate the name of another object owned by the same user
• Must not be an Oracle Server reserved word

Data types
VARCHAR2(size): Variable-length character data
CHAR(size) : Fixed-length character data
NUMBER(p,s): Variable-length numeric data
DATE : Date and time values
LONG: Variable-length character data up to 2 gigabytes
CLOB: Single-byte character data up to 4 gigabytes
RAW and LONG RAW: Raw binary data
BLOB: Binary data up to 4 gigabytes
BFILE: Binary data stored in an external file; up to 4 gigabytes

Constraints: Constraints enforce rules at the table level. Constraints prevent the deletion of a
table if there are dependencies.
Types of constraint
• NOT NULL
• UNIQUE key
• PRIMARY KEY
• CHECK
• FOREIGN KEY

Constraint Guidelines
• Name a constraint or the Oracle Server will generate a name by using the SYS_Cn
format.
• Create a constraint:
• At the same time as the table is created
• After the table has been created
• Define a constraint at the column or table level.
• View a constraint in the data dictionary.
• Query the USER_CONSTRAINTS table to view all constraint definitions and
names.
CREATE TABLE Statement

CREATE TABLE [schema.] table


(column data_type [DEFAULT expr];

SQL> CREATE TABLE department


2 (deptno NUMBER(2),
3 dname VARCHAR2(14),
4 loc VARCHAR2(13));

Defining Constraints

• Column constraint level


column [CONSTRAINT constraint_name] constraint_type,

• Table constraint level


column,...
[CONSTRAINT constraint_name] constraint_type
(column, ...),

CREATE TABLE [schema.]table


(column data type [DEFAULT expr]
[column_constraint],

[table_constraint]);

SQL>CREATE TABLE employee(


empno NUMBER(4),
ename VARCHAR2(10),

deptno NUMBER(7,2) NOT NULL,

CONSTRAINT emp_empno_pk RIMARY KEY (EMPNO),
CONSTRAINT emp_deptno_fk FOREIGN KEY (deptno) REFERENCES dept (deptno)
);

ALTER TABLE Statement

• Add a new column


• Modify an existing column
• Drop an existing column,
• Define a default value for the new column

ALTER TABLE table


ADD (column data type [DEFAULT expr]
[, column data type]...);
ALTER TABLE table
MODIFY (column data type [DEFAULT expr]
[, column data type]...);

ALTER TABLE table


DROP column column_name;

Adding a Constraint
• Add or drop, but not modify, a constraint
• Enable or disable constraints
• Add a NOT NULL constraint by using the MODIFY clause

ALTER TABLE table


ADD [CONSTRAINT constraint] type (column);

Dropping a Constraint

SQL> ALTER TABLE employee


2 DROP CONSTRAINT emp_mgr_fk;

Viewing Constraints

SQL> SELECT constraint_name, constraint_type,


2 search_condition
3 FROM USER_CONSTRAINTS
4 WHERE table_name = 'EMPLOYEE';

SQL> SELECT constraint_name, column_name


2 FROM user_cons_columns
3 WHERE table_name = 'EMPLOYEE';

Dropping a Table

• All data and structure in the table is deleted.


• Any pending transactions are committed.
• All indexes are dropped.
• You cannot roll back this statement.
SQL> DROP TABLE table_name;

Rename an Object

SQL> RENAME old_name TO new_name;


DML Statements:
Objectives
• Insert rows into a table
• Update rows in a table
• Delete rows from a table
• Controlling the Transactions

INSERT Statement

SQL> INSERT INTO table [(column [, column...])]


2 VALUES (value [, value...]);

SQL> INSERT INTO department (deptno, dname, loc)


2 VALUES (50, 'HRD', 'KOLKATA');

Insert Rows with Null Values


 Implicit method: Omit the column from the column list.

SQL> INSERT INTO department (deptno, dname )


2 VALUES (60, 'CSE');

 Explicit method: Specify the NULL keyword.


SQL> INSERT INTO department
2 VALUES (70, 'FINANCE', NULL);

Inserting Specific Date Values

SQL> INSERT INTO employee


2 VALUES (2296,'JIM','SALESMAN',7782,
3 TO_DATE('FEB 3,97', 'MON DD, YY'),
4 1300, NULL, 10);

Substitution Variables (&)

SQL> INSERT INTO DEPARTMENT(deptno, dname, loc)


2 VALUES (&department_id,
3 '&department_name', '&location');

RUN ( / )

Enter value for department_id: 80


Enter value for department_name: EDUCATION
Enter value for location: KOLAGHAT
Copying from Another Table

SQL> INSERT INTO managers(id, name, salary, hiredate)


2 SELECT empno, ename, sal, hiredate
3 FROM employee
4 WHERE job = 'MANAGER';

UPDATE Statement

UPDATE table
SET column = value [, column = value]
[WHERE condition];

DELETE Statement

DELETE [FROM] table


[WHERE condition];

The Sequence Generator


CREATE SEQUENCE [user.] sequence_name
[increment by n]
[start with n]
[maxvalue n | nomaxvalue]
[minvalue n | nominvalue]

Example

To produce a sequence for the DEPTNO column of the department table.

SQL> CREATE SEQUENCE dept_seq


2 INCREMENT BY 10
3 START WITH 10
4 MAXVALUE 100

SQL> SELECT dept_seq NEXTVAL


2 FROM SYS.DUAL;

SQL> INSERT INTO department


2 VALUES (dept_seq.NEXTVAL, ‘HRD’, ‘KOLKAT’);

Creating a SYNONYM for a Table, View, or Sequence

CREATE SYNONYM synonym_name


FOR [owner.] object_name;
DROP SYNONYM Command

SQL> DROP SYNONYM synonym_name;

Indexes
Oracle indexes have two main purposes:
 To speed up the retrival of rows via particular key.
 To enforce uniqueness on values in a column, usually primary key values.

Creating an INDEX

CREATE [UNIQUE] INDEX index_name


ON table_name (column [, <column2>] …..);
SQL> CREATE INDEX I_ENAME
2 ON EMP (ENAME);

DROP Index Command

SQL> DROP INDEX index_name;

Table privileges
To give another user access to one of your database objects, use the GRANT command:

GRANT privileges
ON object
TO user;

The View DICTIONARY


To displays the contents of the DICTIONARY table:
SQL> SELECT * FROM DICTIONARY;

To see the structure of USER_OBJECTS


SQL> desc user_objects
SQL> desc dict
VIEW:
 A view is like a ‘window’ through which data on tables can be viewed of changed.
 Types of Views
1. Simple Views: derived data from only one table, contains no functions or
GROUPs of data
2. Complex View: derived from many tables, contains functions or GROUPs of
data.

CREATE VIEW Command

CREATE [OR REPLACE] VIEW view_name


[ ( column1, column2, … …) ]
AS
SELECT statement [WITH CHECK OPTION [CONSTRAINT constraint_name] ];
Example

CREATE VIEW D30EMP


AS
SELECT EMPNO, ENAME, SAL
FROM EMPLOYEE
WHERE DEPTNO=30;

CREATE VIEW DEPT_SUMMARY


(NAME, MINSAL, MAXSAL, AVSAL)
AS
SELECT DNAME, MIN(SAL), MAX(SAL), AVG(SAL)
FROM EMPLOYEE E, DEPARTMENT D
WHERE E.DEPTNO=D.DEPTNO
GROUP BY DNAME

DROP VIEW Command

DROP VIEW view_name;

View with DML Operations


 DELETION is prohibited if the view contains: Join condition, Group functions, GROUP
BY clause, DISTINCT command etc.
 UPDATE is prohibited if the view contains: Any of the condition of DELETION,
Columns defined by expression(e.g.; SAL*12)
 INSERT is prohibited if the view contains: Any of the above, Any NOT NULL columns
are not selected by view(e.g.; EMPNO);

You might also like