SQL_Tutorial_PCC-CS691
SQL_Tutorial_PCC-CS691
Objectives
SQL SELECT statements
A basic SELECT statement
SQL statements and SQL*Plus commands
DQL : SELECT
DDL : CREATE, ALTER, DROP
DML : INSERT, UPDATE, DELETE
DCL : GRANT, REVOKE
TCL : COMMIT, ROLLBACK
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)
SQL> SELECT *
2 FROM department;
• 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 - )
+ - * /
Operator Precedence
Comparison Operators
= , > , >= , < , <= , <>
Logical Operators
AND , OR , NOT
Example
Output
NAME SALARY
------------- ------------
...
Output
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.
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]
Example
Example
SQL Functions:
Objectives
Get an awareness of the Various SQL Functions available.
• Types of Functions in the SELECT Statement.
• Conversion functions
1. Single-row functions
2. Multiple-row functions
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
OUTPUT
TO_CHAR(SYSDATE, ‘DAY,DDTHMONTHYYYY)
---------------------------------------------------------------------------
FRIDAY , 23RD JULY 2010
OUTPUT
TO_CHAR(SYSDATE,
----------------------------------------
Friday, 23rd July 2010
Date Format
Note: The Codes are case sensitive and will affect display of date elements
DAY : FRIDAY
Day : Friday
Month : July
ddth : 24th
Others: NVL
SQL> SELECT ename, sal, comm, (sal*12)+NVL(comm,0)
2 FROM employee;
AVG(COMM)
------------------
550
• The NVL function forces group functions to include null values.
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.
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.
JOINS:
A join is used when a SQL query requires data from more than one table on database.
EQUI-JOIN
NON-EQUI-JOIN
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
INTERSECT
MINUS
ORDER BY Clause
• 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).
Types of Sub-queries
• Single-Row sub-query(Single row comparison operator : =, <, <=, > ,>=, <>)
• Inline Views
• Multiple-column sub-query
Example
To find employees who have at least one person reporting to them.
DDL Statements
Objectives
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
Defining Constraints
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
Dropping a Constraint
Viewing Constraints
Dropping a Table
Rename an Object
INSERT Statement
RUN ( / )
UPDATE Statement
UPDATE table
SET column = value [, column = value]
[WHERE condition];
DELETE Statement
Example
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
Table privileges
To give another user access to one of your database objects, use the GRANT command:
GRANT privileges
ON object
TO user;