0% found this document useful (0 votes)
79 views

SQL

SQL is a standard language used to manage relational databases. It allows users to define, manipulate, and query data within these databases. Some key capabilities of SQL include creating and modifying database structures like tables, inserting, updating, deleting and retrieving data from tables, filtering data using conditions, sorting results, and aggregating data using functions. Common SQL statements include SELECT, INSERT, UPDATE, DELETE, CREATE, ALTER, and DROP.

Uploaded by

annaps123
Copyright
© © All Rights Reserved
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
79 views

SQL

SQL is a standard language used to manage relational databases. It allows users to define, manipulate, and query data within these databases. Some key capabilities of SQL include creating and modifying database structures like tables, inserting, updating, deleting and retrieving data from tables, filtering data using conditions, sorting results, and aggregating data using functions. Common SQL statements include SELECT, INSERT, UPDATE, DELETE, CREATE, ALTER, and DROP.

Uploaded by

annaps123
Copyright
© © All Rights Reserved
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
You are on page 1/ 87

Introduction to SQL

SQL is a standard computer language for


accessing and manipulating databases.
What is SQL?
• SQL stands for Structured Query Language

• SQL allows the user to access a database

• SQL is an ANSI standard computer language

• SQL can execute queries against a database

• SQL can retrieve data from a database

• SQL can insert new records in a database

• SQL can delete records from a database

• SQL can update records in a database

• SQL is easy to learn


SQL Data Definition Language
(DDL)
Data Definition Language is a set of SQL
commands used to create, modify and
delete database structures (not data).
DDL
• The most important DDL statements in
SQL are:
• CREATE TABLE - creates a new
database table
• ALTER TABLE - alters (changes) a
database table
• DROP TABLE - deletes a database table
• TRUNCATE TABLE
Creating & Managing Tables

Naming Rules
1.Must begin with a letter
2.Must be 1-30 characters long
3.Must contain only A-Z, a-z, 0-9, _, $ and #
4.Must not duplicate the name of another object owned
by the same user
5.Must not be an oracle reserved word

1
Data Types
Data Type Description

1. VARCHAR2(size) Variable-length character data


2. CHAR(size) Fixed-length character data
3. NUMBER(p,s) Variable-length numeric data
4. DATE Date & time values
5. LONG Variable-length character data upto 2 GB
6. CLOB Character data upto 4GB
7. RAW & LONG RAW Raw binary data
8. BLOB Binary data upto 4 GB
9. BFILE Binary data stored in an external file upto
4GB
10. ROWID A 64 base number system representing the
unique address of a row in its table.
1
The Create Table Statement

Syntax:

CREATE TABLE tablename


[column 1 datatype column size,
.,
.,
.,
column n datatype column size];

Confirm table creation.

1
Creating Table

Example:

CREATE TABLE dept


[deptno NUMBER(2),
dname VARCAR2(10),
loc VARCAR2(5));

Table created.

1
The ALTER TABLE Statement

Use the ALTER TABLE statement to :

Add a new column

Modify an existing column

Drop a column

1
Syntax

• ALTER table tablename ADD / MODIFY


(column data type);

• ALTER table tablename DROP (column);


Example

ALTER table dept80


ADD job_id VARCHAR2(5));

ALTER table dept80


MODIFY (last_name VARCHAR2(30));

ALTER table dept80


DROP COLUMN job_id;

1
Dropping a Table

All data & structure in the table is


deleted.
One cannot rollback drop table
statement.

1
Syntax

DROP table tablename;

Example:

DROP TABLE dept80;

Table Dropped
Truncating the Table

The TRUNCATE TABLE statement:


Removes all rows from a table
Releases the storage space used by
that table

Syntax TRUNCATE TABLE Tablename;

1
Example:

TRUNCATE TABLE detail;

Table Truncated
Renaming the table
To change the name of the table

Syntax:

RENAME old tablename To new tablename;

Example:

RENAME employees TO employee_master;

1
SQL Data Manipulation Language (DML)

• Data manipulation language is the area of


SQL that allows you to change data within
the database

• It consists of only four command


statement groups, they are
INSERT,SELECT UPDATE and DELETE.
DML
• INSERT INTO - inserts new data into a
database table
• SELECT - extracts data from a database
table
• UPDATE - updates data in a database
table
• DELETE - deletes data from a database
table
The INSERT Statement Syntax
Add new rows to a table by using the INSERT
statement.

Syntax:

INSERT INTO tablename[ ( column [, column . . . .] )


]
VALUES (value [, value . . . . ]);
Only one row is inserted at a time with this
syntax.

1
Example:

INSERT INTO departments (department_id, department_name,


manager_id, location_id) VALUES (70,'pubic',78,7000);

1 Row Created

Explicit Method:

INSERT INTO departmentsVALUES(100,'finance',null,null);

1 Row Created.

1
Basic SELECT statement

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


FROM TABLENAME;

SELECT identifies what columns


FROM identifies which table

1
Example using Basic SELECT
statement
SELECT *
FROM departments;

SELECT department_id, location_id


FROM departments;

SELECT DISTINCT department_id


FROM departments;

1
Arithmetic Expressions

Create expressions with number and date data by using the


Arithmetic operators.

Operator Description

+ Add

- Subtract

* Multiply

/ Divide
1
Using Arithmetic Operators

SELECT last_name, salary, salary + 300


FROM employees;

Note: Oracle 9i server ignores blank space before & after


arithmetic operator

1
Operator Precedence

Multiplication & Division take priority over addition and


subtraction
Operators of the same priority are evaluated from left to right
Parentheses are used to force prioritized evaluation and to
clarify statements

1
Example for Operator
Precedence

Write a query to add a one time bonus of Rs 100 and


calculate the annual compensation?

SELECT last_name, salary, 12*salary+100


FROM employees

1
Limiting the Rows Selected

Restrict the rows returned by using the


WHERE clause.

Syntax:

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


FROM TABLENAME
[WHERE condition];

1
Using the WHERE clause

SELECT employee_id,
FROM employees
WHERE department_id = 90;

1
Comparison Conditions

Operator Meaning

= Equal to
> Greater than
>= Greater than or equal to
< Lesser than
<= Less than or equal to
<> Not equal to

1
Using Comparison Conditions
SELECT last_name, salary
FROM employees
WHERE salary <> 3000;

1
Comparison Conditions

Operator Meaning

BETWEEN Between two values (inclusive).


.....AND....

IN(set) Match any of a list of values

LIKE Match a character pattern

IS NULL is a null value

1
Using BETWEEN, IN, LIKE, NULL Conditions
SELECT last_name, salary
FROM employees
WHERE salary BETWEEN 2500 AND 3000;

SELECT employee_id,last_name, salary,manager_id


FROM employees
WHERE manager_id IN (100,101,202);

SELECT first_name
FROM employees
WHERE first_name LIKE 's%';

SELECT last_name, manager_id


FROM employees
WHERE manager_id IS NULL;
1
Logical conditions
Operator Meaning

AND Returns TRUE if both component conditions are


true

OR Returns TRUE if either component conditions are


true

NOT Returns TRUE if the following conditions is


false

1
Using AND, OR, NOT operators

SELECT employee_id,Last_name, job_id, salary


FROM employees
WHERE salary >= 5000
AND last_name LIKE “%MAN%”;

SELECT last_name,job_id
FROM employees
WHERE job_id NOT LIKE
('IT_PROG','ST_CLERK',SA_REP');

1
ORDER BY Clause

Sort rows with the ORDER BY clause

ASC : ascending order by default


DESC : descending order

The ORDER BY clause comes last in the


SELECT statement

1
Sorting in Descending Order

SELECT last_name job_id,department_id,hire_date


FROM employees
ORDER BY hire_date DESC

1
Group Functions

Operates on sets of rows to give one result per group

Types:
AVG
COUNT
MAX
MIN
SUM

1
GROUP BY Clause Syntax

SELECT column, group_function(column)


FROM table
[WHERE condition]
[GROUP BY group_by_expression]
[ORDER BY column];

1
Using GROUP BY clause

SELECT AVG(salary), MAX(salary),


MIN(salary),SUM(salary)
FROM employees
WHERE job_id LIKE “%REP%”;

1
HAVING Clause Syntax

SELECT column, group_function(column)


FROM table
[WHERE condition]
[GROUP BY group_by_expression]
[HAVING group_condition]
[ORDER BY column];

1
Using the HAVING Clause (Example)

SELECT job_id, SUM(salary) totalsal


FROM employees
WHERE job_id LIKE '%REP%'
GROUP BY job_id
HAVING SUM(salary) > 10000;
ORDER BY totalsal;

1
SUBQUERIES

A Subquery is a select statement that is embedded


in a clause of another select statement.

Types of Subqueries

Single Row Subqueries


Multiple Row Susqueries

1
SUBQUERY SYNTAX

SELECT select_list
FROM table
WHERE expr operator
( SELECT select_list
FROM table );

1
USING A SUBQUERY
Who has the salary greater than Abel's?

SELECT last_name
FROM employees
WHERE salary >
( SELECT salary
FROM employees
WHERE last_name = 'Abel');

1
Single-Row Subqueries

A single-row subquery is one that returns one row from


the inner SELECT statement.
Use single-row comparison operators.

1
Executing Single-Row Subqueries

SELECT last_name, job_id, salary


FROM employees
WHERE job_id =
( SELECT job_id
FROM employees
WHERE employees_id = 141)
AND salary >
( SELECT salary
FROM employees
WHERE employees_id = 143);

1
Multiple-Row Subqueries

Return more than one row


Use multiple-row comparison operators

Operator Meaning

IN Equal to any member in the list


ANY Compare value to each value returned
by the subsquery
ALL Compare value to every value returned
by the subsquery

1
USING The ANY Operator in Multiple-Row
Subqueries

SELECT employee_id,last_name,job_id,salary
FROM employees
WHERE salary < ANY
( SELECT salary
FROM employees
WHERE job_id = ' IT_PROG');

1
The UPDATE Statement Syntax
Modify existing rows with the UPDATE Statement.
Syntax:

UPDATE table name


SET column = value
[WHERE condition];

Example:
UPDATE employees
SET department_id = 80
WHERE employee_id = 120;

1 row updated.

1
The DELETE Statement Syntax
Can remove the existing rows from a table by using
the DELETE statement
Syntax:

DELETE(FROM) table
[WHERE condition];

Example.

DELETE FROM departments


WHERE department_name = 'finance';

1 row deleted.
1
TCL
• COMMIT Statement - commit (make
persistent) all changes for the current
transaction
• ROLLBACK Statement - roll back (rescind)
all changes for the current transaction
DCL
• Data control commands in SQL allow you
to control access to data within the
database. These DCL commands are
normally used to create objects related to
user access and also control the
distribution of privileges among users.
Some data control commands are as
follows
COMMANDS IN DCL

– ALTER PASSWORD
– GRANT
– REVOKE
– CREATE SYNONYM
JOINS

✔ When data from more than one table in the database is required, a
join condition is used.

✔ Rows in one table can be joined to rows in another table according


to common values existing in corresponding columns, that is, usually
primary and foreign key columns.

1
Types of JOINS
Oracle Proprietary Joins ( 8i and prior)

Equi Join
Non – Equi Join
Outer Join
Self Join

1
Equi join

The relationship between two tables is an Equijoin. i.e.,


the two tables should have a matching column.
This type of Join involves Primary and Foreign key
complements

Syntax:

SELECT T1.column,T2.column
FROM T1 , T2
WHERE T1.column = T2.column

1
Example:

SELECT e.employee_id, e.last_name, e.department_id,


d.department_id, d.location_id
FROM employees e ,departments d
WHERE e.department_id = d.department_id;

1
Non-Equijoin

A Non-equijoin is a join condition containing


something other than an Equality operator.

1
Example( Non Equi-join)
SELECT e.last_name, e.salary, j.gradelevel
FROM employees e ,job_grades j
WHERE e.salary
BETWEEN j.lowest sal AND j.highest sal;

1
Example of Inner Join
SELECT suppliers.supplier_id,
suppliers.supplier_name, orders.order_date
FROM suppliers, orders
WHERE suppliers.supplier_id =
orders.supplier_id;

This SQL statement would return all rows from the


suppliers and orders tables where there is a matching
supplier_id value in both the suppliers and orders tables.
Outerjoins
Returning Records with No Direct Match
If a row does not satisfy a Join condition , the row will
not appear in the query result.
We can use the Outer join to also see the rows that do not
meet the join condition.
Syntax
SELECT table1.column, table2.column
FROM table1, table 2
WHERE table1.column(+) = table2.column;

1
USING Outerjoin

Example:

select suppliers.supplier_id, suppliers.supplier_name,


orders.order_date
from suppliers, orders
where suppliers.supplier_id = orders.supplier_id(+);

1
Functions
Functions are very powerful feature of SQL and can be
used to do the following;

• Perform calculations on data


• Modify individual data items
• Manipulate output for groups of rows
• Format dates and numbers for display
• Convert column data types

Functions sometimes take arguments and always return a value.

1
1
1
1
Case Manipulation Function

Functions Results

LOWER('MAVERIC systems') maveric systems

UPPER('MAVERIC systems') MAVERIC SYSTEMS

INITCAP('MAVERIC systems') Maveric Systems

1
1
1
NUMBER FUNCTONS

ROUND : Rounds value to specified decimal


ROUND(45.926,2) 45.92

TRUNC : Truncate value to specified decimal


TRUNC(45.926,2) 45.92

MOD : Returns remainder of division


MOD(1600,300) 100

1
Working with DATES
➔ Oracle database stores dates in an internal numeric
format:
Century, year, month, day, hours, minutes, seconds

➔ The default date display format is DD-MON-RR.

1
ARITHMETIC WITH DATAS

• Add or subtract a number to or from a data for a


resultant date value
• Subtract two datas to find the number of
daysbetween those days

1
Using Arithmetic Operators With Dates

SELECT last_name, (SYSDATE* hire_date)/7 AS WEEKS


FROM employees
WHERE department_id = 90;

Output.

LAST_NAME WEEKS
king 744.56758
kochar 626.7878

1
1
1
Conversion Functions
Datatype conversion:

Implicit datatype conversion

Explicit datatype conversion

1
1
1
1
General Functions
These functions work with any data type and pertain
to using nulls.

NVL ( expr1, expr2)


NVL2( expr1, expr2, expr3)
NULLIF (expr1, expr2)
COALESCE (expr1, expr2, ..., exprn)

1
NVL Function
Converts a NULL value to an Actual value.

Data types that can be used are DATE, CHARACTER,


and NUMBER.

Data types must match:

- NVL (commission_pct, 0)
- NVL (hire_date, '01-JAN-97')
- NVL (job_id, 'No Job Yet')

1
USING NVL Function
SELECT last_name, salary, NVL(commission_pct,0),
(salary*12)+ (salary*12*(commission_pct,0))
FROM employees;

1
NVL2 Function
Syntax

NVL2 (expr1, expr2, expr3)

The NVL2 function examines the first expression. If the


first expression is not null, then the NVL2 function
returns the second expression. If the first expression is
null, then the third expression is returned.

1
USING NVL2 Function

SELECT last_name, salary, commission_pct,


NVL2(commission_pct,'sal+comm', 'sal') income
FRO M employees
WHERE department_id IN (50,80) ;

1
NULLIF Function
Syntax

NULLIF (expr1, expr2)

In the syntax:
expr1 is the source value compared to expr2
expr2 is the source value compared with expr1.

1
1
Thank You

You might also like