Download RDBMS Study Material Unit-2

Survey
yes no Was this document useful for you?
   Thank you for your participation!

* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project

Document related concepts

Relational algebra wikipedia , lookup

Microsoft Access wikipedia , lookup

DBase wikipedia , lookup

Tandem Computers wikipedia , lookup

Oracle Database wikipedia , lookup

Ingres (database) wikipedia , lookup

Microsoft Jet Database Engine wikipedia , lookup

Database wikipedia , lookup

Functional Database Model wikipedia , lookup

Entity–attribute–value model wikipedia , lookup

Clusterpoint wikipedia , lookup

Extensible Storage Engine wikipedia , lookup

Microsoft SQL Server wikipedia , lookup

Open Database Connectivity wikipedia , lookup

Database model wikipedia , lookup

SQL wikipedia , lookup

Relational model wikipedia , lookup

PL/SQL wikipedia , lookup

Transcript
US03CBCA01 (Relational Database Management Systems - I)
Unit - II
CHARUTAR VIDYA MANDAL’S
SEMCOM
Vallabh Vidyanagar
Faculty Name: Ami D. Trivedi
Class: SYBCA (SEM-III)
Subject: US03CBCA01 (Relational Database Management Systems-I)
*UNIT – 2 (INTRODUCTION TO SQL)
*SQL
Structured Query Language (SQL) is the language used to communicate with the server
to access, manipulate and control data.
SQL is a set of commands that lets you access a relational database.
SQL provides interface to relational database systems. It has a simple command
structure for data definition, access, and manipulation.
SQL is set-oriented and non-procedural. When you use SQL you specify what to be
done, not how to do it.
SQL was developed by IBM in the 1970s for use in System R, and is a de facto
standard, as well as an ISO and ANSI standard. SQL is often pronounced SEQUEL.
In common usage SQL also encompasses DML (Data Manipulation Language), for
INSERTs, UPDATEs, DELETEs and DDL (Data Definition Language), used for creating
and modifying tables and other database structures.
The development of SQL is governed by standards. The American National Standards
Institute (ANSI) is an organization that approves certain standards in many different
industries.
SQL has been, deemed the standard language in relational database communication,
originally approved in 1986 based on IBM's implementation.
In 1987, the International Standards Organization (ISO) accepted the ANSI SQL
standard as the international standard.
The standard was revised again in 1992 and was called SQL-92. The newest standard
is now called SQL-99, it is also referred to as SQL3.
SQL3 supports object extensions and are partially implemented in Oracle8 and 9. SQL
has been a command language for communication with the Oracle 9i 'Server from any
tool or application.
Oracle SQL contains many extensions. When an SQL statement is entered, it is stored
in a part of memory called the SQL buffer and remains there until a new SQL statement
is entered.
SQL *PLUS is an Oracle tool that recognizes and submits SQL statements to the Oracle
9i Server for execution. It contains its own command language.
Page 1 of 22
US03CBCA01 (Relational Database Management Systems - I)
Unit - II
FEATURES OF SQL
1.
SQL can be used by a range of users, including those with little or no programming
experience.
2.
It is a non procedural language.
3.
It reduces the amount of time required for creating and manipulating systems.
4.
It is an English like language.
5.
SQL commands may be entered on one or many lines
6.
Clauses are usually placed on separate lines for readability and ease of editing.
7.
Tabs and indents can be used to make code more readable.
8.
Command words cannot be split across line or abbreviated.
9.
SQL statements are not case sensitive.
10. An SQL command entered at the SQL prompt, and subsequent lines are
numbered. This is called the SQL buffer.
11. Statement can be executed in a number of ways.
a) Place a semicolon (;) at the end of last clause
b) Place a semicolon or slash on the last line in the buffer.
c) Place a slash at the SQL prompt.
d) Issue a SQL*Plus START command at the SQL prompt.
RULES FOR SQL
1.
SQL starts with a verb (i.e. a SQL action word). Example: SELECT statements.
This verb may have additional adjectives. Example: FROM
2.
Each verb is followed by number of clauses. Example: FROM, WHERE, HAVING
3.
A space separates clauses. Example: DROP TABLE EMP;
4.
A comma (,) separates parameters without a clause
5.
A ';' is used to end SQL statements.
6.
Statements may be split across lines but keywords may not
7.
Lexical units such as identifiers, operator names, literals are separated by one or
more spaces or other delimiters. that will not be confused with the lexical unit.
8.
Reserved words cannot be used as identifiers unless enclosed with double quotes.
9.
Identifiers can contain up to 30 characters and must start WIth an alphabetic
character
10. 10f Character and date literals must be enclosed within single quotes
11. Numeric literals can be represented by simple values such as 0.32, -34, 01991,
and so on, scientific notation as 2E5 meaning 2xlO to the power of 5 = 200,000
12. Comments may be enclosed between /* and */ symbols and may be multi line.
Single line comments may be prefixed with a – symbol.
Page 2 of 22
US03CBCA01 (Relational Database Management Systems - I)
Unit - II
ADVANTAGES OF SQL
1. Standard independent language
The widespread rules of the SQL have been recognized by ANSI and ISO. Therefore
the SQL is an open language, involving it is not owned or controlled by a single
company.
Nowadays, SQL is offered by all the foremost DBMS vendors.
SQL is not just for an exacting product; it also works with oracle, Microsoft SQL server
and Sybase, and lot more.
Almost all the data base vendors may have proprietary extensions to SQL, but the
fundamentals of SQL are almost equal across all the data base vendors.
2. Cross-platform abilities
The prevalent adversity of using a programming language to access database is that it
infrequently produces an accurate cross platform application.
SQL may be moderately innovative to some of the for the most part of popular
programming languages like COBOL or C.
But it has been in use on dissimilar hardware platforms for years. Majority of the cases,
the same SQL statement can be used on a mainframe, desktop and a server.
3. Easy to learn and use
SQL statements look like very simple English sentences that are easy to understand.
SQL has been created such that it is instinctive, easy, and maps human’s cognitive
model.
While it is non-procedural in nature, the user host has to type SQL declaration and
afterwards it has to be handed over to the DBMS.
Then it is executed by the DBMS, internal code and returns a set, which is a logically
defined group of data.
4. Speed
For the past ten years, SQL data engines have been focusing the powerful effort to get
better performance.
The passionate competition among data base vendors has resulted in quicker, more
vigorous database management systems that work at lower costs.
Page 3 of 22
US03CBCA01 (Relational Database Management Systems - I)
Unit - II
DISDVANTAGES OF SQL
1. Procedural capabilities
SQL cannot be used for programming because SQL does not provide the
programming techniques of condition checking, looping and branching etc.
2. Data processing speed
SQL statements are passed to oracle engine one at a time. Each time an SQL
statement is executed, a call is made to the engine’s resources.
This increases the traffic on the network which results in decrease of speed of data
processing.
3. Lack of error handling techniques
While processing an SQL sentence if an error occurs, the Oracle engine displays its
own error messages.
SQL has no facility for programmed handling of errors that arise during manipulation
of data.
*DATA TYPES
Data types come in several forms and sizes. It allows programmer to create tables
suited to scope of the project.
Some commonly used data types are:
1. Character
2. Number
3. Date
4. Long
5. RAW and LONG RAW
6. LOB
1. Character Data types
Character data types are used to manipulate words and free-form text. These data
types are used to store character (alphanumeric) data in the database or national
character set.
They are less restrictive than other data types and consequently have fewer properties.
These data types are used for character data:
1) CHAR
2) VARCHAR
3) VARCHAR2
Page 4 of 22
US03CBCA01 (Relational Database Management Systems - I)
Unit - II
1) CHAR Data type

The CHAR data type specifies a fixed length character string.

When you create a table with a CHAR column, you supply the column length in
bytes. Oracle subsequently ensures that all values stored in that column have this
length.

If you insert a value that is shorter than the column length, Oracle blank-pads the
value to column length.

If you try to insert a value that is too long for the column, Oracle returns an error.

The default length for a CHAR column is 1 character and the maximum allowed is
2000 characters.

A zero-length string can be inserted into a CHAR column, but the column is blankpadded to 1 character when used in comparisons.
2) VARCHAR Data type

The VARCHAR data type is currently synonymous with the VARCHAR2 data type.
 It is recommended that you use VARCHAR2 rather than VARCHAR. In a future
version of Oracle, VARCHAR might be a separate data type used for variable length
character strings compared with different comparison semantics.
3) VARCHAR2 Data type

The VARCHAR2 data type specifies a variable length character string.

When you create a VARCHAR2 column, you can supply the maximum number of
bytes of data that it can hold.

Oracle subsequently stores each value in the column exactly as you specify it,
provided it does not exceed the column's maximum length.

This maximum must be at least 1 byte, although the actual length of the string
stored is permitted to be zero.

If you try to insert a value that exceeds the specified length, Oracle returns an error.

You must specify a maximum length for a VARCHAR2 column. The maximum
length of VARCHAR2 data is 4000 bytes.
Page 5 of 22
US03CBCA01 (Relational Database Management Systems - I)
Unit - II
2. NUMBER Data type
The NUMBER data type is used to store numbers (fixed or floating point).
Numbers of any magnitude may be stored up to 38 digits of precision.
Valid values are
 Zero and
 Positive and Negative numbers with magnitudes between 1.0 x 10 -130 and
9.9...9 x 10125 (38 9s followed by 88 0s) with 38 digits of precision.
If you specify an arithmetic expression whose value has a magnitude greater than or
equal to 1.0 x 10126, Oracle returns an error.
You can specify a fixed-point number using the form: NUMBER (p,s)
Where,
 p is the precision, or the total number of digits. Oracle guarantees the portability of
numbers with precision ranging from 1 to 38.

s is the scale, or the number of digits to the right of the decimal point. The scale can
range from -84 to 127.
You can specify a scale that is greater than precision, although it is uncommon. In this
case, the precision specifies the maximum number of digits to the right of the decimal
point.
If the value exceeds the precision, Oracle returns an error message.
If the value exceeds the scale, Oracle rounds the value.
For example, a column defined as NUMBER(4,5) requires a zero for the first digit after
the decimal point and rounds all values past the fifth digit after the decimal point.
3. DATE Data type
The DATE data type is used to store date and time information.
The standard format is DD-MON-YY.
Although date and time information can be represented in both CHAR and NUMBER
data types, the DATE data type has special associated properties.
For each DATE value the following information is stored:
 century
 year
 month
 day
 hour
 minute
 second
Page 6 of 22
US03CBCA01 (Relational Database Management Systems - I)
Unit - II
4. LONG Data type
LONG columns store variable length character strings containing up to 2 gigabytes, or
231-1 bytes.
LONG columns have many of the characteristics of VARCHAR2 columns. You can use
LONG columns to store long text strings.
Oracle uses LONG columns in the data dictionary to store the text of view definitions.
The length of LONG values may also be limited by the memory available on your
computer.
The use of LONG values is subject to some restrictions:





A table cannot contain more than one LONG column.
LONG columns cannot appear in integrity constraints (except for NULL and NOT
NULL constraints).
LONG columns cannot be indexed.
A stored function cannot return a LONG value.
Within a single SQL statement, all LONG columns, updated tables, and locked
tables must be located on the same database.
5. RAW and LONG RAW Data types
The RAW and LONG RAW data types are used for data that is not to be interpreted (not
converted when moving data between different systems) by Oracle.
These data types are used to store binary data. For example, to store graphics, sound,
documents, or arrays of binary data.
LONG RAW data cannot be indexed, but RAW data can be indexed.
RAW data type can contain up to 2000 bytes. LONG RAW data type can contain up to 2
GB.
6. Large Object (LOB) Data types
Internal LOB data types, BLOB, CLOB, NCLOB, and external data type BFILE, can
store large and unstructured data such as text, image, video, and spatial data, up to 4
gigabytes in size.
You can define one or more LOB data type columns in a table.
*TYPES OF SQL STATEMENTS / COMPONENTS OF SQL
1.
2.
3.
4.
5.
DDL (Data Definition Language)
DML (Data Manipulation Language)
DCL (Data Control Language)
TCL (Transaction Control Language)
DQL (Data Query Language)
Page 7 of 22
US03CBCA01 (Relational Database Management Systems - I)
Unit - II
SQL STATEMENTS
DML (Row)
DQL
TCL
DDL(Table)
DCL
SELECT
CREATE
DROP
RENAME
ALTER
TRUNCATE
GRANT
GRANT
INSERT
UPDATE
DELETE
COMMIT
REVOKE
ROLLBACK
SAVEPOINT
1. DDL (Data Definition Language)
Data definition language (DDL) is a set of commands used to create, modify and
delete database structures.
These statements are immediate. Oracle Database implicitly commits the current
transaction before and after every DDL statement.
If several DML statements are executes then issuing any DDL command will
COMMIT all DML because every DDL command implicitly issue COMMIT
command.
They are not at risk to ROLLBACK command.
For example:
 CREATE - to create objects in the database
 ALTER - alters the structure of the database
 DROP - delete objects from the database
 TRUNCATE - remove all records from a table, including all spaces allocated for
the records are removed
 RENAME - rename an object
2. DML (Data Manipulation Language)
Data manipulation language (DML) statements allow changing data within the
database.
These statements do not implicitly commit the current transaction.
For example:
 INSERT - insert data into a table
 UPDATE - updates existing data within a table
 DELETE - deletes all records from a table, the space for the records remain
Page 8 of 22
US03CBCA01 (Relational Database Management Systems - I)
Unit - II
3. DCL (Data Control Language)
Data control language (DCL) statements control access to data and to the
database. It is used to give the permission to user to use the database or object. It
can also take back the permission.
It allows central administration of user privileges and access.
For example:
 GRANT - gives user's access privileges to database
 REVOKE - withdraw access privileges given with the GRANT command
4. TCL (Transaction Control Language)
Transaction Control Language (TCL) statements are used to manage the changes
made by DML statements. It allows statements to be grouped together into logical
transactions.
For example:
 COMMIT - save work done
 SAVEPOINT - identify a point in a transaction to which you can later roll back
 ROLLBACK - restore database to original since the last COMMIT
5. DQL (Data Query Language)
Data Query Language (DQL) allows getting data from the database. This command
is heart of SQL.
When SELECT is fired against a table or tables, the result is compiled into a
temporary table.
For example:
 SELECT – get data from database
*WORKING WITH SQL*PLUS
FEATURES OF SQL*PLUS
1.
2.
3.
4.
5.
6.
7.
SQL*PLUS accepts ad hoc entry of statements.
It accepts SQL input from files.
It provides a editor for modifying SQL statements.
It controls environmental settings.
It formats query results into basic reports.
It interacts with end users.
It accesses local and remote database.
Page 9 of 22
US03CBCA01 (Relational Database Management Systems - I)
Unit - II
SQL V/s SQL *PLUS
SQL
SQL *PLUS
SQL is a language for communicating with
the Oracle Server to access data.
SQL is based on American National
Standards Institute (ANSI) standard SQL.
SQL manipulates data and table
definitions in the database.
SQL is entered into the SQL buffer on one
or more lines.
SQL does not have a continuation
character.
SQL *PLUS recognizes SQL statements
and sends them to the server.
SQL *PLUS is the Oracle propriety
interface for executing SQL statements.
SQL *PLUS does not allow manipulation of
values in the database.
SQL *PLUS is entered one line at a time,
not stored in the SQL buffer.
SQL *PLUS uses a dash (-) as a
continuation character if the command is
longer than one line.
It cannot be abbreviated.
It can be abbreviated.
SQL uses a termination character to SQL *PLUS does not require termination
execute commands immediately.
character.
SQL uses functions to perform some SQL *PLUS uses commands to format
formatting.
data.
BASIC SQL*PLUS COMMANDS
1. EDIT
It invokes a host operating system text editor on the contents of the specified file or on
the contents of the buffer. By default, saves the file to AFIEDT.BUF.
Syntax: ED [ IT ] [ file_name [.ext ] ]
If you omit the file extension, the default command file extension (normally SQL) is
assumed.
If you specify a filename, SQL*Plus searches for the file in the current working directory.
If SQL*Plus cannot find the file in the current working directory, it creates a file with the
specified name.
EDIT alone places the contents of the SQL buffer in a file by default named
AFIEDT.BUF (in your current working directory).
If the file AFIEDT.BUF already exists, it is overwritten with the contents of the buffer.
If you do not specify a filename and the buffer is empty, EDIT returns an error message.
Page 10 of 22
US03CBCA01 (Relational Database Management Systems - I)
Unit - II
2. START
Executes the contents of the specified script.
Syntax: STA [ RT ] < url | filename [ .ext ] > [arg…]
Runs the SQL*Plus statements in the specified script. The script can be called from the
local file system or from a web server.
If you do not specify an extension, SQL*Plus assumes the default command-file
extension (normally SQL).
Data items you wish to pass to parameters in the script. If you enter one or more
arguments, SQL*Plus substitutes the values into the parameters (&1, &2, and so forth)
in the script.
The first argument replaces each occurrence of &1, the second replaces each
occurrence of &2, and so on.
The START command defines the parameters with the values of the arguments; if you
START the script again in this session, you can enter new arguments or omit the
arguments to use the old values.
All previous settings like COLUMN command settings stay in effect when the script
starts. If the script changes any setting, then this new value stays in effect after the
script has finished
3. GET
Loads (Retrieve) the previously stored command file.
Syntax: GET < filename [ .sql ] >
GET command can be used to load files created with SAVE command.
4. SAVE
Save the contents of the SQL*Plus buffer in a command file (script).
Syntax: SAV[E] < filename [ .ext ] > [ CRE [ ATE ] | REP[ LACE ] | APP[ END ] ]
If you do not specify an extension, SQL*Plus assumes the default command-file
extension (normally SQL).
5. EXIT
Commit, logoff and exit.
Page 11 of 22
US03CBCA01 (Relational Database Management Systems - I)
Unit - II
6. CONNECT
Connect a given user to Oracle.
Syntax: CONN [ ECT ] < username / password [ @ connect_identifier ]
Connects a given username to oracle. CONNECT does not reprompt for username or
password if the initial connection does not succeed.
CONNECT commits the current transaction to the database, disconnects the current
username from oracle and reconnects with the specified username.
7. SET LINESIZE
Display or change SQL * Plus line size setting.
Syntax: SET LINES [ IZE ] < n >
Sets the total number of characters that SQL*Plus displays on one line before
beginning a new line.
Changing the linesize setting can affect text wrapping in output from DESCRIBE
command. Decreasing or increasing the linesize may give unexpected text wrapping in
display.
You can define LINESIZE value from 1 to maximum that is system dependent.
8. SET PAGESIZE
Display or change SQL * PLUS page size setting.
Syntax: SET PAGES [ IZE ] < n >
Sets the total number of lines that SQL*Plus displays on each page.
You can set PAGESIZE to zero to suppress all headings, page breaks, titles, initial
blank line and other formatting information.
9. HOST
Execute host operating system command without leaving SQL*Plus.
Syntax: HO[ST] [command]
Page 12 of 22
US03CBCA01 (Relational Database Management Systems - I)
Unit - II
*CREATE TABLE
Create tables to store data by executing the SQL CREATE TABLE statement. This
statement is one of the data definition language (DDL) statements.
TYPE
DDL statement
SYNTAX
CREATE TABLE < TableName >
( < ColumnName1 > < DataType > ( < size > ),
< ColumnName2 > < DataType > ( < size > ) …….
< ColumnNameN > < DataType > ( < size > ) ) ;
EXAMPLE
CREATE TABLE stud
( s_no NUMBER(3),
s_name VARCHAR2(15),
address VARCHAR2(20) );
The CREATE TABLE command defines each column of the table uniquely. Each
column has a minimum of three attributes, a name, data type and size (i.e. column
width).
Each table column definition is a single clause in the create table syntax. Each table
column definition is separated from the other by a comma.
Finally, the SQL statement is terminated with a semi colon.
Whenever user creates table, the table name must be a legal SQL name and it must not
conflict with the name of any of your existing tables.
CREATING A TABLE FROM PREVIOUSLY CREATED TABLE
SYNTAX
CREATE TABLE < TableName1 >
[ < ColumnName1 >, < ColumnName2 > …..< ColumnNameN > ]
AS SELECT <ColumnName1>, <ColumnName2>…..< ColumnNameN >
FROM < TableName2 >
[WHERE <condition>]
Note: If the TableName2 is having records then the target table – TableName1 will be
populated with the same records.
Page 13 of 22
US03CBCA01 (Relational Database Management Systems - I)
Unit - II
EXAMPLE
1. CREATE TABLE stud1 AS SELECT * FROM STUD;
2. Create a table named ACCT_DTLS having 3 fields _NO, BRANCH_NO and
CURBAL from the source table named ACCT_MSTR and rename the field CURBAL
to BALANCE.
CREATE TABLE ACCT_DTLS (ACCT_NO, BRANCH_NO, BALANCE)
AS SELECT ACCT_NO, BRANCH_NO, CURBAL FROM ACCT_MSTR;
CREATE TABLE WITHOUT RECORDS
To create a target table without records from the source table (i.e. create the structure
only) then the SELECT statement must have a WHERE clause.
And specify a condition in WHERE clause that cannot be satisfied.
This means that the SELECT statement in the CREATE TABLE definition will not
retrieve any rows from the source code. It will just retrieve the table structure. Thus, the
target table will be created empty.
CREATE TABLE < new tablename >
AS SELECT * FROM < old tablename > WHERE 1=2
RULES FOR CREATING TABLES
1.
2.
3.
4.
A name can have maximum up to 30 characters
Alphabets from A-Z, a-z and numbers from 0-9 are allowed
A name should begin with an alphabet
The use of the special character like _ is allowed and also recommended. (Special
characters like $, # are allowed only in Oracle).
5. SQL reserved words not allowed. For example: create, select, and so on.
*INSERT (INSERTION OF DATA INTO TABLES)
Once a table is created, the most natural thing to do is load this table with data to be
manipulated later.
When inserting a single row of data into the table, the insert operation:
 Creates a new row (empty) in the database table
 Loads the values passed (by the SQL insert) into the specified columns
TYPE:
DML statement
SYNTAX
INSERT INTO <TableName>
[ < ColumnName1 >, < ColumnName2 >…..< ColumnNameN > ]
VALUES ( < Expression1 >, < Expression2 >……< ExpressionN > );
Page 14 of 22
US03CBCA01 (Relational Database Management Systems - I)
Unit - II
EXAMPLE
INSERT INTO STUDENT (ROLLNO, NAME) VALUES (1, ‘ANAND’);
In INSERT INTO sentence, table columns and values have a one to one relationship.
i.e. First value is inserted into first column, second value is inserted into second column
and so on.
Column names are optional if
1. There are exactly same number of values as columns and
2. The values are in sequence exactly in accordance with data type of table columns.
However, if there are less values being described than there are columns in the table
then it is mandatory to indicate both the table column name and its corresponding value
in the INSERT INTO SQL sentence.
In the absence of mapping a table column name to a value in the INSERT INTO SQL
sentence, the Oracle engine will not know which columns to insert the data into.
This will generally cause a loss of data integrity. Then the data held within the table will
be largely useless.
BIND VARIABLES / SUBSTITUTION VARIABLES
1. & (Single empersand)
&VariableName indicates a variable in a SQL statement. If the variable does not exist,
SQL*PLUS prompts the user for a value every time the command is executed.
With a single ampersand (&) we can accept a value from the user for INSERT INTO
<table name> VALUES statement too.
INSERT INTO < TableName >
[ < ColumnName1 >, < ColumnName2 >, ….. < ColumnNameN >,]
VALUES ( &<VariableName1>,&<VariableName2>…. &<VariableNameN>);
When SQL*PLUS detects that the SQL statement contains an &, you are prompted to
enter a value for the substitution variable named in the SQL statement.
It will not preserve value to a variable. Once the value is transferred into a specific
column each time it will ask the user to input value.
2. &&variable_name
It will preserve value to a variable. It is used for define variable first time.
It will not ask user second time and previous values will automatically been assigned to
the specific field.
INSERT INTO < TableName >
[ < ColumnName1 >, < ColumnName2 >, ….. < ColumnNameN > ]
VALUES ( &&<VariableName1>, &<VariableName2>…. &<VariableNameN>);
Page 15 of 22
US03CBCA01 (Relational Database Management Systems - I)
Unit - II
Here, value for VariableName1 will be asked only once.
Specifying character and date values with substitution variables
In substitution variables, date and character values must be enclosed within single
quotation marks.
INSERTING DATA INTO A TABLE FROM ANOTHER TABLE
INSERT INTO tablename SELECT columnname,columnname FROM tablename [
WHERE <condition> ];
*SELECT (RETRIEVING DATA USING QUERY)
Once data has been inserted into a table, the next most logical operation would be to
view what has been inserted. The SELECT SQL verb is used to achieve this.
The SELECT command is used to retrieve rows selected from one or more tables.
TYPE:
DML statement
All Rows and All Columns
SYNTAX SELECT * FROM < TableName >;
It will display all the data from all rows and columns from the table.
FILTERING TABLE DATA
While viewing data from a table, it is rare that all the data from the table will be required
each time. So, SQL provides a method of filtering table data that is not required.
Ways for filtering data are:
1. Selected columns and all rows
2. Selected rows and all columns
3. Selected columns and selected rows
1. Selected Columns and All Rows
SYNTAX SELECT <ColumnName1>, <ColumnName2>,……..<ColumnNameN>
FROM < TableName >;
It will display all the records with specific fields that user has specified with SELECT
command.
2. Selected Rows and All Columns
SYNTAX SELECT * FROM < TableName > WHERE < Condition >;
It will display all the records for which the condition specified after WHERE will become
true.
Page 16 of 22
US03CBCA01 (Relational Database Management Systems - I)
Unit - II
WHERE clause applies a filter on the rows retrieved.
When a WHERE clause is added to the SQL query, the Oracle engine compares each
record in the table with the condition specified in WHERE clause.
The Oracle engine displays only those records that satisfy the specified condition.
All standard operators such as logical, arithmetic, etc. can be used in the condition of
WHERE clause.
3. Selected Columns and Selected Rows
SYNTAX SELECT <ColumnName1>, <ColumnName2>,……..<ColumnNameN>
FROM < TableName > WHERE < Condition > ;
It will display all the records with specific fields for which the condition specified after
WHERE will become true.
ELIMINATING DUPLICATE ROWS
A table can have duplicate rows. To view only unique rows, DISTINCT clause can be
used.
SYNTAX
SELECT DISTINCT <ColumnName1>, <ColumnName2>,……..<ColumnNameN>
FROM < TableName >;
DISTINCT clause allows removing duplicates from the result set. This clause can be
used only with SELECT statement.
It scans all the values of the specified column(s) and display only unique values.
SYNTAX
SELECT DISTINCT * FROM <TableName>;
Here, DISTINCT * scans the entire rows. It eliminates rows that have exactly same
contents in each column.
SORTING DATA IN A TABLE
Oracle allows to view the table data in sorted order.
Rows retrieved from table will be sorted in either ascending or descending order
depending on the condition specified in SELECT statement.
Page 17 of 22
US03CBCA01 (Relational Database Management Systems - I)
Unit - II
SYNTAX
SELECT * FROM < TableName >
ORDER BY <ColumnName1>, <ColumnName2>,……..
[ASCE | DESC];
OR
SELECT <ColumnName1>, <ColumnName2>,……..<ColumnNameN>
FROM < TableName >
ORDER BY <ColumnName1>, <ColumnName2>,……..
[ASCE | DESC];
Note:
 User can specify field number instead of specifying the column name after
ORDER BY clause.
 ASCE means sort the records in an ascending order.
 DESC means sort the records in a descending order.
ORDER BY clause can only be used in SELECT statement. It sorts the result set based
on the specified column(s).
For viewing data in descending sorted order, DESC word must be mentioned after
column name and before the semi colon in ORDER BY clause.
If sort order is not mentioned then Oracle engine sorts in ascending order by default.
*Arithmetic calculation
Example: Select employee name, salary and compute salary * 0.05 for each row
retrieved:
SELECT ename, sal, sal * 0.05 “Salary” from emp; OR
SELECT ename, sal, sal * 0.05 AS “Salary” from emp;
Here the default output column sal*0.05 is renamed with Salary.
*DELETE (MANIPULATING DATA)
DELETE command deletes rows from the table.
TYPE
DML statement
SYNTAX
DELETE FROM < TableName > [ WHERE < condition >] ;
If WHERE clause is not specified then all rows will be deleted.
If WHERE clause is specified then it will delete all rows that satisfy the condition
specified after WHERE.
EXAMPLE
DELETE FROM CUST;
It will delete all the records from a CUST table.
Page 18 of 22
US03CBCA01 (Relational Database Management Systems - I)
Unit - II
DELETE FROM CUST WHERE CUSTNO > 10;
It will delete all the records for which CUSTNO is greater than 10.
*UPDATE (UPDATING A CONTENTS OF A TABLE)
UPDATE command is used to change or modify data values in a table.
User can update
 all rows from table OR
 selected rows from table
TYPE
DML statement
SYNTAX
UPDATE < TableName > SET
<ColumnName1> = <Expression1>,
<ColumnName2> =<Expression2> ………………,
<ColumnNameN> =<ExpressionN>
[ WHERE <Condtion> ] ;
EXAMPLE
UPDATE ADDR_DTLS SET CITY = ‘BARODA’;
UPDATE ADDR_DTLS SET CITY = ‘BARODA’ WHERE CUSTNO = 10;
*ALTER TABLE (MODIFYING THE STRUCTURE OF TABLE)
Structure of the table can be modified using ALTER TABLE command.
ALTER TABLE can
 add or delete columns
 create or destroy indexes
 change data types of columns OR
 rename columns.
TYPE
DDL statement
ADDING NEW COLUMNS
SYNTAX
ALTER TABLE < TableName > ADD
( < NewColumnName1 > < Datatype1 > (< Size1 >),
< NewColumnName2 > < Datatype2 > (< Size2 >), …….
< NewColumnNameN > < DatatypeN > (< SizeN >) );
EXAMPLE
ALTER TABLE CUST ADD (CITY VARCHAR2(20) );
Page 19 of 22
US03CBCA01 (Relational Database Management Systems - I)
Unit - II
DROPING A COLUMN
SYNTAX
ALTER TABLE <TableName> DROP COLUMN <ColumnName>;
EXAMPLE
ALTER TABLE CUST DROP COLUMN CITY;
MODIFYING EXISTING COLUMNS
SYNTAX
ALTER TABLE <TableName> MODIFY ( <ColumnName> <NewDatatype> (<Size>) );
EXAMPLE
ALTER TABLE CUST MODIFY (NAME VARCHAR2(40) );
Restrictions on the ALTER table
1. User cannot change the column name
2. User cannot decrease the size of column if record(s) there in the table for that
column.
3. Earlier versions do not support the deletion of column(s).
ALTER TABLE TO ADD / REMOVE CONSTRAINTS
To add a primary key constraint after creation of a table
ALTER TABLE <TableName> ADD PRIMARY KEY (column(s))
It will add a primary key constraint to a specified column(s) specified after PRIMARY
KEY.
If there are more than one column to specify then all the columns are separated by
commas and will create composite primary key.
To remove primary key constraint
ALTER TABLE <TableName> DROP PRIMARY KEY;
It will remove primary key constraint from a table.
To remove user defined constraint
ALTER TABLE <TableName> DROP CONSTRAINTS <Const_Name>
It will remove the constraint, which was defined on the table.
Page 20 of 22
US03CBCA01 (Relational Database Management Systems - I)
Unit - II
*DROP TABLE (REMOVING TABLE)
Sometimes tables within a particular database become obsolete (out of date) and need
to be discarded. DROP TABLE statement can destroy a specific table.
TYPE
DDL statement
SYNTAX
DROP TABLE < TableName > ;
Example
DROP TABLE stud;
If a table is dropped, all records within table are lost and cannot be recovered. DROP
TABLE statement once executed is irreversible.
Note:
1.
2.
3.
4.
5.
6.
DROP statement removes the table.
It deletes all its data.
It deletes constraints and indexes associated with it.
Any views and synonyms are remain but are invalid.
Any pending Transaction are committed.
Only the creator of the table as user with the DROP ANY TABLE privilege can
remove a table.
*TRUNCATE
It will delete all the records from a table and records cannot be ROLLBACK.
TYPE
DML statement
SYNTAX
TRUNCATE TABLE < TableName >;
*RENAME
Used to rename a table.
TYPE
DDL statement
SYNTAX
RENAME < OldTableName > TO < NewTableName>;
*VIEWING TABLE STRUCTURE
SYNTAX DESCRIBE < TableName > OR DESC < TableName >
Used to view structure of a table.
Page 21 of 22
US03CBCA01 (Relational Database Management Systems - I)
Unit - II
*SPOOL
SPOOL command is used to store the results of a query in a file as well as print and
display on the screen.
SYNTAX
SPOOL < filename[ .ext ] >
SPOOL with file name tells SQL to store all the information that is displayed on the
screen after SPOOL command has been entered, into the specified file.
The default file extension is .LST unless user specifies the specific extension.
SQL will continue to spool information to the file until you turn spooling off.
SPOOL OFF will stop spooling data to a file.
SPOOL OUT will stop spooling and will also copy the spool file’s contents to a default
printer.
Disclaimer
The study material is compiled by Ami D. Trivedi. The basic objective of this material is
to supplement teaching and discussion in the classroom in the subject. Students are
required to go for extra reading in the subject through library work.
Page 22 of 22