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

Basic SQL Manual

The document provides an overview of SQL and how to use SQL*Plus. It describes SQL statements like DDL, DML, and DCL and covers basic SQL commands like SELECT, INSERT, UPDATE, DELETE. It also outlines SQL datatypes and how to execute, edit, save and load SQL scripts in SQL*Plus.

Uploaded by

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

Basic SQL Manual

The document provides an overview of SQL and how to use SQL*Plus. It describes SQL statements like DDL, DML, and DCL and covers basic SQL commands like SELECT, INSERT, UPDATE, DELETE. It also outlines SQL datatypes and how to execute, edit, save and load SQL scripts in SQL*Plus.

Uploaded by

22bce363
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 15

SQL Lab Manual

NIRMAUNIVERSITY
INSTITUTE OF TECHNOLOGY
SEMSTER V
2CS402 – DATABASE MANAGEMENT SYSTEM
Lab Manual

What is SQL?
SQL (Structured Query Language) is a powerful language that is used for retrieving or
modifying data from the database. It is designed such that this can be also accessed by non-
programmer.

IBM devloped the original version of SQL called as Sequel as a part of the system are developed
in the early 1970s. Since them, it has evolved & now called Structured Query language. SQL has
clearly established itself as the Standard relational database language.

SQL*PLUS is an ORACLe tool which accepts SQL, SQL commands and executes them.

SQL statements can be grouped as:


 Data Manipulation Language (DML) that retrieves or modifies data
 Data Definition Language (DDL) that defines the structures of the data, i.e. statements
that create, alter, or remove database objects
 Data Control Language (DCL) that defines the privileges granted to database users

DML group can be further broken down into the following statements:
 SELECT, which retrieves data
 INSERT, which adds data to the database
 UPDATE, which modifies existing data from the database
 DELETE, which removes data from the database

DDL statements can be used to create user and restructure database objects. The following list
are DDL commands:
 CREATE TABLE
 ALTER TABLE
 DROP TABLE
 CREATE INDEX
 DROP INDEX

DCL commands are used to create objects related to user access and privileges. Here are some
common DCL commands:
 ALTER PASSWORD
 GRANT
 REVOKE
 CREATE SYNONYM

Monika Shah 1
SQL Lab Manual

DDL and DCL are in the realm of the DBA (DataBase Administration) or for the privilege user.

How to access / start SQL*PLUS ?


1. Type sqlplus your_oracle_user_name / your_oracle_password and press enter at console
prompt
2. Other way is Select SQL*PLUS menu option from Start menu and type
your_oracle_user_name and your_oracle_password in appropriate text box.

SQL Grammar and Syntax


The following rules should be adhered to when writing your SQL scripts:
 To enter a SQL>command, type the command at SQL> prompt. An SQL command can
be entered continuously or it can be spread over multiple lines.
 Every SQL statement should be terminated by a semicolon ‘;’, slash ‘/’ or blank line at
the end of statement.
 SQL is case insensitive; however, care should be taken when retrieving the contents of a
field as the data stored within them may be case sensitive.

Commands to edit SQL command

A. LIST : To see command in buffer (last entered)


SQL > L[IST] [from line no./*(current line)/LAST [to line no.]]
Recent Buffer Query :
1 SELECT EmpNo, EmpName, EmpDesignation
2 EmpDept, EmpSalary
3 *FROM emp
4 WHERE EmpDesignation = 'Manager' ;
Example : To display first line of the recent buffer
SQL > LIST 1
OUTPUT :
1. SELECT EmpNo, EmpName, EmpDesignation
Example : To display first three lines of the recent buffer
SQL > LIST 1 3
OUTPUT :
1. SELECT EmpNo, EmpName, EmpDesignation
2. EmpDept, EmpSalary
3. FROM emp
Example : To display current line of the recent buffer
SQL > LIST *

Monika Shah 2
SQL Lab Manual

OUTPUT :
3. FROM emp

Example : To display the last of the recent buffer


SQL > LIST LAST
OUTPUT :
4. WHERE EmpDesignation = 'Manager' ;

B. CL[EAR] BUFF[ER] : To delete all lines.

C. CL[EAR] SCR[EEN] : To clear SQL screen

D. To edit the SQL statement which is in buffer

 To edit the last entered SQL statement


Syntax : ED[ITOR]

 If the command is broken into multiple lines, make the line which is to be edited, the
current line
Type N at the SQL> prompt to make line no N to make as current line
Example : To make line 1 as current line
SQL > 1
OUTPUT :
1* SELECT *

 To Change Part Of Text From The Current Line


Syntax : C [HANGE] / old_text / new_text
Example : Replace * with ename, salary
SQL > C / * / ename, salary
OUTPUT :
1* SELECT ename, salary

 To Remove text from the current line


Syntax : C [HANGE] / old_text_to_be_removed
Example : To remove ,salary from current line
SQL > C / , salary
OUTPUT :
1* SELECT ename

 To remove or delete current line


Syntax : DEL [from line no/ *(current line) [to line no.]]
SQL > DEL

Monika Shah 3
SQL Lab Manual

 To Insert a line below the current line


Syntax : I [NPUT] text_to_be_added
I //Insert one or more lines
I text // Insert text below the current line
Example :
To add a line “,salary, dept” after 1st line
SQL > 1
SQL > I , salary, dept
OUTPUT :
1 SELECT ename
2 , salary, dept
3 From emp

 To add text at the end of current line


Syntax : A[PPEND] text_to_be_added
Example : To add text “Order by” in line 3
SQL > 3
SQL > A Order by ename
OUTPUT :
1 SELECT ename
2 , salary, dept
3 From emp Order by ename

E. To save the buffer contents ( last query) into a file


Syntax : SAVE file_name
If user does not specify an extension, then ORACLE adds .sql as default extension.

F. To Retrieve the contents of a saved file


Syntax : GET file_name

G. To load command of file in memory and execute it


Syntax : @filename
or
START file_name

H. To Execute the command in buffer


Syntax : RUN
or
/

Monika Shah 4
SQL Lab Manual

I. To Store / print the queries and the output


Syntax : SPO[OL] [file_name | OFF | OUT]
Where
SPOOL file_name - will open a file to send the query and the output. If the extension
is not specified, will take .lst as default extension.
SPOOL OFF - will stop the spooling.
SPOOL OUT - will send the contents of current spool file for printing and stop
further spooling.

Commands to save / cancel the transaction.


1. COMMIT : To save transactions work.
2. ROLLBACK : To cancel the transactions work (undo).

Monika Shah 5
SQL Lab Manual

Basic Datatypes
Datatype Description Length limitation
Char(n) Fixed length character string. Note that 255(2000 in oracle)
a string of type char is always padded
on right with blanks to full length of n.

varchar2(n) Variable-length character string N is 2000(4000 in


Only the bytes used for a string require oracle)
storage

number(o, d) *) Numeric data type for integers and Maximum values:


reals. o =38, d= _84 to
o = overall number of digits, +127.
d= number of digits to the right of the
decimal point.
*) number(5,2) not more than 999.99
*) Data types derived from number are
int[eger], dec[imal], smallint
and real.

date Date data type for storing date and


time.
The default format for a date is: DD-
MMM-YY.
Examples: '13-OCT-94'

long Character data up to a length of 2GB.


Only one long column is allowed per
table.

Integer Same as Number, but integer data only 39 digits

Monika Shah 6
SQL Lab Manual

SQL COMMANDS

The SELECT Statement


Most widely used DML command can be incorporated as a subquery in an UPDATE, INSERT,
or DELETE statement. The SELECT statement only scan at the contents of tables; it cannot
create or modify it.
Syntax :
SELECT [ * | all | distinct ] column1, column2, ...
FROM table1 [, table2, ...]
[ WHERE condition1 | expression1 | subquery]
[ AND condition2 | expression2 ]
[ START WITH condition ]
[ CONNECT BY condition ]
[ GROUP BY column1, column2, ...]
[ HAVING conditions1 | expression1 ]
[ ORDER BY column1 | integer1, column2 | integer2, ...[ASC | DESC] ]

Where ,
 The asterisk (*) in the SELECT statement is used to denote that all columns in the table.

 WHERE clause used to filter out the records satisfying the specified criteria
Where clause - Comparators
• <, >, =, <>, >=, <=
– Compare two values as expected
– Operates on numbers as well as text values
• LIKE
– Compare a text value with a pattern
– ‘%’ compares with zero or more characters
– ‘_’ compares with exactly one character
For, E.g.
Select * from student Where Age>=20; //List the students atleast 20 yr. older
Select * from student Where name like 'A%' //Students having A as first character.

 The DISTINCT keyword is used to prevent duplicate rows being returned.

 CONNECT BY is used to set hierarchical relation of records. like


E.g. Select ename from emp connected by prior id = mgr_id

 START WITH clause is used to start fetching the data from the record, which satisfies the
specified criteria.
E.g. SELECT ename FROM emp CONNECTED BY prior id = mgr_id START WITH
id=101

 sub-query : is an additional SELECT statement embedded in the WHERE clause of a parent


SQL statement.

Monika Shah 7
SQL Lab Manual

 The query writer can assign new, different names to the attributes or columns that appear in a
query answer with the AS <new attribute name> clause. Use the AS operator to name the
result attributes for formulas.

The INSERT Statement


INSERT INTO table_name [ ('column1', 'column2') ]
VALUES ('values1', 'value2', [ NULL ] );

INSERT INTO table_name [ ('column1', 'colum2') ]


SELECT [ * | ('column1', 'column2') ]
FROM table_name
[WHERE condition(s) ];

This is an only statement that enables you to add new record to an existing table.

The DELETE Statement


DELETE FROM table_name
[WHERE condition];

The delete statement is used to remove the record from the table.

The UPDATE Statement


UPDATE table_name
SET column1 = 'value',
[column2 = 'value',]
[column3 = 'value']
[WHERE condition];

Update statement is used to make changes to existing rows in a table.

How to delete a Table/User/view Object ???????????


The DROP Statement
DROP STATEMENT : It is used to remove element such as table, user from a database.
E.g.
DROP TABLE table_name : To remove table from database
DROP USER user_name : To remove User

How to Modify a Table Structure ????????????


The ALTER Statement

ALTER STATEMENT: To make the changes to the schema of tables in a database


ALTER TABLE table_name [ADD | DROP | MODIFY [CONSTRAINT | column_name]
(SPECIFICATION)

Monika Shah 8
SQL Lab Manual

Example:

SQL> desc student;


Name Null? Type
----------------------------------------- -------- -----------------

RNO CHAR(8)
NAME VARCHAR2(30)
CITY VARCHAR2(20)
DOB DATE
PROGRAM CHAR(3)
HSC NUMBER(5,2)
JEE NUMBER(3)

Query : Update width of program column to 4 size

 ALTER TABLE student MODIFY (program char(4))

Query : Add two more properties (columns) surname, full name

 ALTER TABLE student ADD (surname varchar(10), fullname varchar(50))

Query : Remove DoB column from the table


 ALTER TABLE student DROP (DOB)

 SubQuery : is an additional SELECT statement embedded in the WHERE clause of a


parent SQL statement.

Types of SubQuery
 Correlated
The subquery mentions an attribute from a table in the outer query.
The subquery executes as many times as many records are in outer Query.
E.g.
SELECT S.Number, S.Name
FROM Salesperson S
WHERE S.Number IN
(SELECT C.SalespersonNum
FROM Customer C
WHERE C.Name = S.Name);

 Non-correlated
The subquery only uses attributes from the the table mentioned in the subquery.
The subquery executes once only.

E.g.
SELECT C1.Number, C1.Name
FROM Customer C1

Monika Shah 9
SQL Lab Manual

WHERE C1.CRating IN
(SELECT MAX (C2.CRating)
FROM Customer C2);

Operator JOINS

JOINS
There are a number of join types that can be
expressed in the FROM clause:
These are syntactic sugar
– inner join (the regular join)
… these joins can be
– cross join
expressed in a basic
– natural join
SELECT..FROM..WHERE ..query
– left outer join
– right outer join
– full outer join There are new operators
– union join … these joins can only be
expressed in a complex
SQL query involving the
union operator.

Monika Shah 10
SQL Lab Manual

Type Records in result Matching Matching Matching Duplicate Duplicate


using which condition criteria column row
operator
CROSS All combination Y
INNER Only matching ON (=) Explicitly Y
JOIN
EQUI Only matching = Explicitly Y
Theta Only matching <, > ,<=, Explicitly Y
Natural Only matching = Implicit Column name N N
must be same,
column data
type must be
same
Outer Matching + non = Explicitly Y
matching

Monika Shah 11
SQL Lab Manual

 CROSS JOIN
A “CROSS JOIN” is simply a cross product
E.g.
These two queries are equivalent:
(1)
SELECT A,T1.B, C,D
FROM Customer T1, Salesperson T2

Where T1.B=T2.B;

B C D T1.a T1.B T2.B T2.C T2.D


A B A1 B1 B1 C1 D1
A1 B1 B1 C1 D1
B1 C1 D2 A1 B1 B1 C1 D2
A1 B2
A1 B1 B2 C2 D2
B2 C2 D2
(2) A1 B2 B1 C1 D1
SELECT * A1 B2 B1 C1 D2
FROM Customer CROSS JOIN
Salesperson; A1 B2 B2 C2 D2

 ON clause for the join


Join condition in the ON clause (vs. the WHERE clause)
E.g.
These two queries are equivalent:
(1)
SELECT C.Name, S.Name
FROM Customer C JOIN Salesperson S ON C.SalespersonNum = S.Number
WHERE C. CreditRating < 6;

(2)
SELECT C.Name, S.Name
FROM Customer C, Salesperson S WHERE C.SalespersonNum = S.Number AND
C. CreditRating < 6;

 Basic Join  INNER JOIN

E.g.
These queries are equivalent.

(1)
SELECT C.Name, S.Name
FROM Customer C JOIN
(SELECT Name, Number AS SalespersonNum FROM Salesperson ) S
ON SalespersonNum;

(2)
SELECT C.Name, S.Name
FROM Customer C INNER JOIN
(SELECT Name, Number AS SalespersonNum FROM Salesperson) S

Monika Shah 12
SQL Lab Manual

ON SalespersonNum;

Note for the above example:


For the INNER JOIN, the query answer does not include:
a Customer that doesn’t have a Salesperson ….
nor
a Salesperson that is not assigned to any customers.

 Natural Join
 NATURAL JOIN requires equal values for all corresponding columns from the two tables that
have the same name (or you can list the column name for the join) in the ON clause.

 The NATURAL JOIN eliminates one of the duplicates.

E.g.
These queries are equivalent.
(1)
SELECT C.Name, S.Name
FROM Customer C, Salesperson S
WHERE C.SalespersonNum = S.Number;

(2)
SELECT C.Name, S.Name
FROM Customer C NATURAL JOIN
(SELECT Name, Number AS SalespersonNum From SalesPerson) S
ON SalespersonNum;

 OUTER JOIN

INNER JOIN on C.Salesperson = S.Number gives us:


“smith” with “johnson” and “jones” with “johnson”

LEFT OUTER JOIN on C.Salesperson = S.Number gives us:


INNER JOIN plus “wei” with “<null>” salesperson

RIGHT OUTER JOIN on C.Salesperson = S.Number gives us:


INNER JOIN plus “<null>” customer with “miller”

FULL OUTER JOIN = LEFT OUTER JOIN RIGHT OUTER JOIN

Monika Shah 13
SQL Lab Manual

OUTER JOIN

E.g. Left Outer Join


These queries are equivalent.
(1)
SELECT C.Name, S.Name
FROM Customer C LEFT OUTER JOIN Salesperson S ON
SalespersonNum;

(2)
SELECT C.Name, S.Name
FROM Customer C, Salesperson S
Where C.SalespersonNum(+) = S.SalespersonNum;

E.g. Right Outer Join


These queries are equivalent.
(1)
SELECT C.Name, S.Name
FROM Customer C RIGHT OUTER JOIN Salesperson S ON
SalespersonNum;

(2)
SELECT C.Name, S.Name
FROM Customer C, Salesperson S
Where C.SalespersonNum = S.SalespersonNum(+);

E.g. Full Outer Join


These queries are equivalent.
(1)
SELECT C.Name, S.Name
FROM Customer C FULL OUTER JOIN Salesperson S ON
SalespersonNum;

(2)
SELECT C.Name, S.Name
FROM Customer C, Salesperson S
Where C.SalespersonNum(+) = S.SalespersonNum(+);

UNION JOIN
Not really a join ... tuples from the two tables are not matched.
UNION JOIN = FULL OUTER JOIN - INNER JOIN

E.g.
These two queries are equivalent.

(1)

Monika Shah 14
SQL Lab Manual

SELECT C.Name, S.Name


FROM Customer UNION JOIN Salesperson;

(2)
(SELECT C.Name, S.Name
FROM Customer FULL OUTER JOIN Salesperson ON
SalespersonNum;)
MINUS
(SELECT C.Name, S.Name
FROM Customer JOIN Salesperson ON
SalespersonNum;);

Characteristics of Good Database:


 Self-evident (easy to understand the relationship among pieces of data)
 Make easy to retrieve the data you need
 Exhibit high intergrity so that data remains consistent after update
 Good performance tunning

Characteristics of Bad Database:


 Columns or tables with confusing or unclear names
 Duplicate rows within a single table
 Difficulty in determining the relationship between pieces of data.

Note: Refer Oracle Documentation for detail syntax help for any SQL command

Monika Shah 15

You might also like