Você está na página 1de 36

A table is uniquely identified by its name and consists of rows that contain the

stored information, each row containing exactly one tuple (or record). A table can
have one or more columns. A column is made up of a column name and a data
type, and it describes an attribute of the tuples. The structure of a table, also
called relation schema, thus is defined by its attributes. The type of information to
be stored in a table is defined by the data types of the attributes at table creation
time.

SQL uses the terms table, row, and column for relation, tuple, and attribute,
respectively. A table can have up to 254 columns which may have different or
same data types and sets of values (domains), respectively.

Before creation of the database we will find out the Tables, Table attributes and
data types of the attributes. We will take the example of School Management
System Database. This includes the details about the teachers, courses,
students and marks.

The following are SQL components:-

1. DDL (Data Definition Language) :- DDL is used to define, modify and delete the
schema (structure of the database objects).

Examples: - CREATE, ALTER, DROP, TRUNCATE.

2. DML (Data Manipulation Language):- DML is used to operate on the data in the
database rather than the schema. The common operations are: Fetch the data according
the user requirements and Insertion, Deletion and updating of the data. for example:-
SELECT, INSERT, UPDATE, AND DELETE.

3. DCL (Data Control Language):- DCL is used to give and take the data access
permissions and rights to the different users.for example : - GRANT, REVOKE
Transaction control statements Transaction Control Statements are used to control the
overall transaction of the data. for example : - SET TRANSACTION, COMMIT,
ROLLBACK

SQL Objects: An Overview

Tables: - Tables are logical structures maintained by the database manager. Tables are
made up of columns and rows. The rows are not necessarily ordered within a table (order
is determined by the application program). At the intersection of every column and row is
a specific data item called a value. A column is a set of values of the same type or one of
its subtypes. A row is a sequence of values arranged so that the nth value is a value of the
nth column of the table.

Views: - A view provides an alternative way of looking at the data in one or more tables.
It is a named specification of a result table. The specification is a SELECT statement that
is executed whenever the view is referenced in an SQL statement.

Aliases: - An alias is an alternative name for a table or view. It can be used to reference a
table or view in those cases where an existing table or view can be referenced. An alias
cannot be used in all contexts. For example, it cannot be used in the check condition of a
check constraint.

Indexes: - An index is an ordered set of pointers to rows of a base table. Each index is
based on the values of data in one or more table columns. An index is an object that is
separate from the data in the table. When an index is created, the database manager builds
this structure and maintains it automatically. Indexes are used by the database manager
to: Improve performance. In most cases, access to data is faster than without an index. An
index cannot be created for a view. However, an index created for a table on which a
view is based can sometimes improve the performance of operations on the view. Ensure
uniqueness. A table with a unique index cannot have rows with identical keys.
Queries: - A query is a component of certain SQL statements that specifies a (temporary)
result table.

The following are the data types used in SQL: -

Character Data Types in SQL: -

CHAR( size)[BYTE | CHAR] Fixed-length character data of length size bytes. Maximum
size is 2000 bytes. Default and minimum size is 1 byte. BYTE and CHAR have the same
semantics as for VARCHAR2.

NCHAR( size) Fixed-length character data of length size characters. Maximum size is
determined by the national character set definition, with an upper limit of 2000 bytes.
Default and minimum size is 1 character.

VARCHAR2( size) [BYTE | CHAR] Variable-length character string having maximum


length size bytes or characters. Maximum size is 4000 bytes, and minimum is 1 byte or 1
character. You must specify size for VARCHAR2. BYTE indicates that the column will
have byte length semantics; CHAR indicates that the column will have character
semantics.

NVARCHAR2( size) Variable-length character string having maximum length size


characters. Maximum size is determined by the national character set definition, with an
upper limit of 4000 bytes. You must specify size for NVARCHAR2.

Numeric Data Types in SQL: -

NUMBER( p,s) Number having precision p and scale s. The precision p can range from 1
to 38. The scale s can range from -84 to 127.
LONG Character data of variable length up to 2 gigabytes, or 2 31 -1 bytes.

Date, Time and Interval Data Types: -

DATE Valid date range from January 1, 4712 BC to December 31, 9999 AD. 180

TIMESTAMP ( fractional_ seconds_precision) Year, month, and day values of date, as


well as hour, minute, and second values of time, where fractional_seconds_precisionis
the number of digits in the fractional part of the SECOND datetime field. Accepted
values of fractional_ seconds_precision are 0 to 9. The default is 6.

TIMESTAMP ( fractional_ seconds_precision) WITH TIME ZONE All values of


TIMESTAMP as well as time zone displacement value, where fractional_
seconds_precisionis the number of digits in the fractional part of the SECOND datetime
field. Accepted values are 0 to 9. The default is 6. 231

TIMESTAMP ( fractional_ seconds_precision) WITH LOCAL TIME ZONE All values


of TIMESTAMP WITH TIME ZONE, with the following exceptions: n Data is
normalized to the database time zone when it is stored in the database. n When the data is
retrieved, users see the data in the session time zone.

INTERVAL YEAR ( year_precision) TO MONTH Stores a period of time in years and


months, where year_precision is the number of digits in the YEAR datetime field.
Accepted values are 0 to 9. The default is 2.

INTERVAL DAY (day_ precision) TO SECOND ( fractional_ seconds_precision) Stores


a period of time in days, hours, minutes, and seconds, where n day_precision is the
maximum number of digits in the DAY datetime field. Accepted values are 0 to 9. The
default is 2. n fractional_seconds_precision is the number of digits in the fractional part
of the SECOND field. Accepted values are 0 to 9. The default is 6.
Raw and Long Raw Data Types: -

RAW( size) Raw binary data of length size bytes. Maximum size is 2000 bytes. You must
specify size for a RAW value.

LONG RAW Raw binary data of variable length up to 2 gigabytes.

RowID Data Types: -

ROWID Base 64 string representing the unique address of a row in its table. This
datatype is primarily for values returned by the ROWID pseudocolumn.

UROWID [( size)] Base 64 string representing the logical address of a row of an index-
organized table. The optional size is the size of a column of type UROWID. The
maximum size and default is 4000 bytes.

Large Object Data Types (LOB's): -

CLOB A character large object containing single-byte characters. Both fixed-width and
variable-width character sets are supported, both using the CHAR database character set.
Maximum size is 4 gigabytes.

NCLOB A character large object containing Unicode characters. Both fixed-width and
variable-width character sets are supported, both using the NCHAR database character
set. Maximum size is 4 gigabytes. Stores national character set data.
BLOB A binary large object. Maximum size is 4 gigabytes.

BFILE Contains a locator to a large binary file stored outside the database. Enables byte
stream I/O access to external LOBs residing on the database server. Maximum size is 4
gigabytes.

CREATE TABLE: - It is used to create an empty table in the database.


Syntax: -

create table <table Name> (

<column 1> <data type> [not null] [unique] [<column constraint>],

.........

<column n> <data type> [not null] [unique] [<column constraint>],

[<table constraint(s)>]

);

Examples: -

Creation of Teacher Table: -

create table Teacher (


TeacherID Number(10) ,
TeacherName Varchar2(30),
Qualification Varchar2(30),
Subject Varchar2(30),
ContactNumber Number(10) );

In the above example a table will be created with the name Teacher and TeacherID,
TeacherName, Qualification, Subject and ContactNumber fields. This way we create all
the tables discussed in the previous section
It is possible to modify the structure of a table (the relation schema) even if rows
have already been inserted into the table.

Adding the Column to the Table: - A column can be added using the alter table
command. Following is the syntax for adding the column to the table.

Syntax: - alter table <table name> add(<column> data type [<default value>]
[<column constraint>]);

If more than one column should be added at one time, respective add clauses
need to be separated by colons.

A table constraint can be added to a table using

alter table <table name> add (<table constraint>);

(Note that a column constraint is a table constraint, too. not null and primary key
constraints can only be added to a table if none of the specified columns contains
a null value.)

Example: - Suppose you want to add a new column Contact_Number to the


Student table in the previous example.

You can add the column using the following statement: -

alter table Student add(Contact_Number Number(10));


Modifying the Column of the Table: - A column can be modified using the alter
table command. Following is the command for modifying the column attributes: -

Syntax: - alter table <table name> modify(<column> [<data type>] [<default


value>] [<column constraint>]);

Example: - If you want to change the size of TeacherName in the Teacher table.
You can do it with the following statement:-

alter table Teacher modify(TeacherName varchar2(35));

Deleting a Table: - A table and its rows can be deleted by issuing the drop table
command. Following is the syntax for deleting a table.

Syntax: - drop table table name [cascade constraints];

Example: - If you want to delete the Marks table. You can delete it using the
following statement:-

drop table Marks;

Updating the Table: - For modifying attribute values of (some) tuples in a table, we use
the update statement. The following is the syntax for Update:

Syntax: - update <table name> set <column i> = <expression i>, . . . , <column
j> = <expression j> [where <condition>];

An expression consists of either a constant (new value), an arithmetic or string


operation, or an SQL query. Note that the new value to assign to column i must
be the matching data type. An update statement without a where clause results
in changing respective attributes of all tuples in the specified table. Typically,
however, only a (small) portion of the table requires an update.
Constraints
Constraints are the special elements of SQL which are used to enforce the
standards defined by the organization. The definition of a table may include the
specification of integrity constraints. There are two types of constraints:

Column Constraints: - These are associated with a single column. However,


any column constraint can also be formulated as a table constraint.

Table Constraints: - These are associated with more than one column.

Further Constraints can be divided as: -

1. Integrity Constraints 2. Check Constraints 3. Foreign Key Constraints

The specification of a constraint has the following form:

[<constraint name>] primary key | unique | not null

(A constraint can be named. It is advisable to name a constraint in order to get


more meaningful information when this constraint is violated due to, e.g., an
insertion of a tuple that violates the constraint. The information will be provided
with the name of the constraints so that it is easier to find the violation.)

Integrity Constraints: - We have three types of integrity constraints: not null


constraints, primary keys, and unique constraints. Probably the most important
type of integrity constraints in a database is primary key constraints. A primary
key constraint enables a unique identification of each tuple in a table. Based on a
primary key, the database system ensures that no duplicates appear in a table.

Example:

Check Constraints: - Often columns in a table must have values that are within
a certain range or that satisfy certain conditions. Check constraints allow users to
restrict possible attribute values for a column to admissible ones. They can be
specified as column constraints or table constraints. The syntax for a check
constraint is

[<constraint name>] check(<condition>)


If a check constraint is specified as a column constraint, the condition can only
refer that column.

Example:

If a check constraint is specified as a table constraint, condition can refer to all


columns of the table. It is not allowed to refer to columns of other tables or to
formulate queries as check conditions. Furthermore, the functions sysdate and
user cannot be used in a condition. In principle, thus only simple attribute
comparisons and logical connectives such as and, or, and not are allowed. A
check condition, however, can include a not null constraint Example: The
database system automatically checks the specified conditions each time a
database modification is performed on this relation.

Foreign Key Constraints: - A foreign key constraint (or referential integrity


constraint) can be specified as a column constraint or as a table constraint:

[<constraint name>] [foreign key (<column(s)>)] references


<table>[(<column(s)>)] [on delete cascade]

This constraint specifies a column or a list of columns as a foreign key of the


referencing table. The referencing table is called the child-table, and the
referenced table is called the parent-table. In other words, one cannot define a
referential integrity constraint that refers to a table R before that table R has been
created. The clause foreign key has to be used in addition to the clause
references if the foreign key includes more than one column. In this case, the
constraint has to be specified as a table constraint. The clause references
defines which columns of the parent-table are referenced. If only the name of the
parent-table is given, the list of attributes that build the primary key of that table is
assumed.

Example:

In order to satisfy a foreign key constraint, each row in the child-table has to
satisfy one of the following two conditions: " The attribute value (list of attribute
values) of the foreign key must appear as a primary key value in the parent-table,
or " The attribute value of the foreign key is null (in case of a composite foreign
key, at least one attribute value of the foreign key is null)

Example:

Disabling and Enabling Constraints: - If a constraint is defined within the


create table command or added using the alter table command the constraint is
automatically enabled. A constraint can be disabled using the command
alter table <table> disable <constraint name> | primary key |
unique[<column(s)>] [cascade];

To disable a primary key, one must disable all foreign key constraints that
depend on this primary key. The clause cascade automatically disables foreign
key constraints that depend on the (disabled) primary key.

Example:

In order to enable an integrity constraint, the clause enable is used instead of


disable. A constraint can only be enabled successfully if no tuple in the table
violates the constraint. Otherwise an error message is displayed. Note that for
enabling/disabling an integrity constraint it is important that you have named the
constraints.

INSERT INTO: - It is used to insert records in the table.

Syntax: -

insert into <table name> [(<column i, . . . , column j>)]values (<value i, . . . , value j>);

Examples: -

Insert data in Teacher Table: -

Insert into Teacher (TeacherID, TeacherName, Qualification, Subject,


ContactNumber)Values(1, "Harris", "M.Sc. (Math)", "Math", 4235678);

OR

Insert into Teacher Values (1, "Harris", "M.Sc. (Math)", "Math", 4235678);

In the above examples data will be inserted in the corresponding fields. And there will be
one tuple (row) in the table. Similarly you can insert more tuples in the table. As you can
see the components in the [ ] brackets are optional and we can insert the data without
giving the attributes.

Select: - Select is used to fetch the data from the tables in the database.
Following is the syntax for using the select statement.

Syntax: -

SELECT <Column Name> FROM <Table Name>


;
Example: -
If you want to see Teacher Name from the Teacher Table:-

Select Teacher_Name from Teacher;

The above query will fetch the names of all the teachers in the teacher table.

To fetch all the details of the teachers we will use the following query: -

Select * from Teacher;

The above query will display all the details of the teachers. Here '*' refers to all
the columns.

To fetch the details of more than one column (not all the columns), we will use
delimeter (,) between the column names.
For example: -

Select Teacher_Name, Qualification from Teacher; will display the Teacher


Names and their qualifications.

Where Clause: - Where clause is used to fetch the data according according to
the conditions given by the user with the
help of operators. The following is the syntax for using where: -

Syntax: -
SELECT <Column Name>
FROM
<Table Name>
WHERE <Condition>

Example: -
If you want to see the ID of the students who secured percentage of marks equal
to 65%.

Select Student_ID from Marks where MarksPercentage = 65;


Similarly we can use the different operators with where clause: -

Select Student_ID from Marks where MarksPercentage > 65;

Select Student_ID from Marks where MarksPercentage < 65;

Select Student_ID from Marks where MarksPercentage < > 65;

Order By: - It is used to fetch the data in the given order (Ascending or
Descending).
The following is the syntax for order by: -
Syntax: -
SELECT <column Name>
FROM <Table Name> [WHERE ]
ORDER BY [ASC, DESC]
Example: -
If you want to see the details of the students in ascending order according to the
name.

Select * from Student order by StudentName;

In the above example we have not mentioned the type of the ordering because
by default it is ascending order but for
the descending order we have to specify the order: -

Select * from Student order by StudentName Desc; will display the data in the
descending

ORDER BY clause is used to order the data sets retrieved from a SQL database.
The ordering of the selected data can be done by one or more columns in a
table. If we want to sort our Users table by the FirstName column, we'll have to
use the following ORDER BY SQL statement:

SELECT * FROM Users ORDER BY FirstName;

The result of the ORDER BY statement above will be the following:

FirstName LastName DateOfBirth Email City


San
David Stonewall 01/03/1954 david@sql-tutorial.com
Francisco
john.smith@john-
John Smith 12/12/1969 New York
here.com
paul.oneil@pauls-
Paul O'Neil 09/17/1982 New York
email.com
Los
Stephen Grant 03/03/1974 sgrant@sgrantemail.com
Angeles
susan.grant@sql- Los
Susan Grant 03/03/1970
tutorial.com Angeles

As you can see the rows are ordered alphabetically by the FirstName column.
You can use ORDER BY to order the retrieved data by more than one column.
For example, if you want to order by both LastName and City columns, you
would do it with the following ORDER BY statement:
SELECT * FROM Users ORDER BY LastName, DateOfBirth;

Here is the result of this ORDER BY statement:

LastName DateOfBirth Email City

FirstName
susan.grant@sql- Los
Susan Grant 03/03/1970
tutorial.com Angeles
Los
Stephen Grant 03/03/1974 sgrant@sgrantemail.com
Angeles
paul.oneil@pauls-
Paul O'Neil 09/17/1982 New York
email.com
john.smith@john-
John Smith 12/12/1969 New York
here.com
San
David Stonewall 01/03/1954 david@sql-tutorial.com
Francisco

When using ORDER BY with more than one column, you need to separate the
list of columns following ORDER BY with commas. What will happen if we
reverse the order of the columns specified after the ORDER BY statement like in
the statement below?

SELECT * FROM Users ORDER BY DateOfBirth, LastName;

This ORDER BY statement will return the same results as the one with the
reversed columns order, but they will be ordered differently. Here is the result:

FirstName LastName DateOfBirth Email City


San
David Stonewall 01/03/1954 david@sql-tutorial.com
Francisco
john.smith@john-
John Smith 12/12/1969 New York
here.com
susan.grant@sql- Los
Susan Grant 03/03/1970
tutorial.com Angeles
Los
Stephen Grant 03/03/1974 sgrant@sgrantemail.com
Angeles
paul.oneil@pauls-
Paul O'Neil 09/17/1982 New York
email.com
The ORDER BY clause first sorts the retrieved data by the first column, then the
next one, and so forth. In all the ORDER BY examples so far, we were sorting
alphabetically for character columns (FirstName, LastName) and from earlier to
later date for the DateOfBirth column. What do we do if we want to order our data
alphabetically but this time backwards? In order to accomplish that we need to
use the DESC SQL keyword:

SELECT * FROM Users ORDER BY FirstName DESC;

Here is the result:

FirstName LastName DateOfBirth Email City


susan.grant@sql- Los
Susan Grant 03/03/1970
tutorial.com Angeles
Los
Stephen Grant 03/03/1974 sgrant@sgrantemail.com
Angeles
paul.oneil@pauls-
Paul O'Neil 09/17/1982 New York
email.com
john.smith@john-
John Smith 12/12/1969 New York
here.com
San
David Stonewall 01/03/1954 david@sql-tutorial.com
Francisco

CONCAT: - It returns char1 concatenated with char2. Both char1 and char2 can be any
of the datatypes CHAR, VARCHAR2, NCHAR, NVARCHAR2, CLOB, or NCLOB.
The string returned is in the same character set as char1. Its datatype depends on the
datatypes of the arguments. In concatenations of two different datatypes, Oracle returns
the datatype that results in a lossless conversion.

Example: - This example uses nesting to concatenate three character strings:

SELECT CONCAT(CONCAT(last_name, '''s job category is '), job_id) "Job" FROM


employees WHERE employee_id = 152;

Job

------------------------------------------------------

Hall's job category is SA_REP


INITCAP: - It returns char, with the first letter of each word in uppercase, all other
letters in lowercase. Words are delimited by white space or characters that are not
alphanumeric. char can be of any of the datatypes CHAR, VARCHAR2, NCHAR, or
NVARCHAR2. The return value is the same datatype as char.

Example: - The following example capitalizes each word in the string: SELECT
INITCAP(’the soap’) "Capitals" FROM DUAL;

Capitals

---------

The Soap

Note: This function does not support CLOB data directly. However, CLOBs can be
passed in as arguments through implicit data conversion.

LOWER: - It returns char, with all letters lowercase. char can be any of the datatypes
CHAR, VARCHAR2, NCHAR, NVARCHAR2, CLOB, or NCLOB. The return value is
the same datatype as char.

Example: - The following example returns a string in lowercase: SELECT


LOWER(’MR. SCOTT MCMILLAN’) "Lowercase" FROM DUAL; Lowercase

--------------------

mr. scott mcmillan

LPAD: - It returns char1, left-padded to length n with the sequence of characters in


char2; char2 defaults to a single blank. If char1 is longer than n, then this function returns
the portion of char1 that fits in n. Both char1 and char2 can be any of the datatypes
CHAR, VARCHAR2, NCHAR, NVARCHAR2, CLOB, or NCLOB. The string returned
is of VARCHAR2 datatype and is in the same character set as char1. The argument n is
the total length of the return value as it is displayed on your terminal screen.

Example: - The following example left-pads a string with the characters "*" and ".":

SELECT LPAD(’Page 1’,15,’*.’) from dual;

LTRIM: - It removes characters from the left of char, with all the leftmost characters that
appear in set removed; set defaults to a single blank. If char is a character literal, then you
must enclose it in single quotes. Oracle begins scanning char from its first character and
removes all characters that appear in set until reaching a character not in set and then
returns the result. Both char and set can be any of the datatypes CHAR, VARCHAR2,
NCHAR, NVARCHAR2, CLOB, or NCLOB. The string returned is of VARCHAR2
datatype and is in the same character set as char.

Example: - The following example trims all of the left-most x’s and y’s from a string:

SELECT LTRIM(’xyxXxyLAST WORD’,’xy’) "LTRIM example" FROM DUAL;

LTRIM example

------------

XxyLAST WORD

REPLACE: - It returns char with every occurrence of search_string replaced with


replacement_string. If replacement_string is omitted or null, then all occurrences of
search_string are removed. If search_string is null, then char is returned. Both
search_string and replacement_string, as well as char, can be any of the datatypes CHAR,
VARCHAR2, NCHAR, NVARCHAR2, CLOB, or NCLOB. The string returned is of
VARCHAR2 datatype and is in the same character set as char. REPLACE lets you
substitute one string for another as well as to remove character strings.

Example: - The following example replaces occurrences of "J" with "BL":

SELECT REPLACE(’JACK and JUE’,’J’,’BL’) "Changes" FROM DUAL;

Changes

--------------

BLACK and BLUE

RPAD: - It returns char1, right-padded to length n with char2, replicated as many times
as necessary; char2 defaults to a single blank. If char1 is longer than n, then this function
returns the portion of char1 that fits in n. Both char1 and char2 can be any of the
datatypes CHAR, VARCHAR2, NCHAR, NVARCHAR2, CLOB, or NCLOB. The
string returned is of VARCHAR2 datatype and is in the same character set as char1. The
argument n is the total length of the return value as it is displayed on your terminal
screen. In most character sets, this is also the number of characters in the return value.

Example: - The following example right-pads a name with the letters "ab" until it is 12
characters long:

SELECT RPAD(’MORRISON’,12,’ab’) "RPAD example" FROM DUAL;

RPAD example
-----------------

MORRISONabab

RTRIM: - It returns char, with all the rightmost characters that appear in set removed;
setdefaults to a single blank. If char is a character literal, then you must enclose it in
single quotes. RTRIM works similarly to LTRIM. Both char and set can be any of the
datatypes CHAR, VARCHAR2, NCHAR, NVARCHAR2, CLOB, or NCLOB. The
string returned is of VARCHAR2 datatype and is in the same character set as char.

Example: - The following example trims the letters "xy" from the right side of a string:

SELECT RTRIM(’BROWNINGyxXxy’,’xy’) "RTRIM example" FROM DUAL;

RTRIM examp

-----------

BROWNINGyxX

SUBSTR: - The "substring" functions return a portion of string, beginning at character


position, substring_length characters long. SUBSTR calculates lengths using characters
as defined by the input character set. string can be any of the datatypes CHAR,
VARCHAR2, NCHAR, NVARCHAR2, CLOB, or NCLOB. The return value is the same
datatype as string. Floating-point numbers passed as arguments to SUBSTR are
automatically converted to integers.

Example: - The following example returns several specified substrings of "ABCDEFG":

SELECT SUBSTR(’ABCDEFG’,3,4) "Substring" FROM DUAL;

Substring

---------

CDEF

SELECT SUBSTR(’ABCDEFG’,-5,4) "Substring" FROM DUAL;

Substring

---------

CDEF
TRIM: - It enables you to trim leading or trailing characters (or both) from a character
string. If trim_character or trim_source is a character literal, then you must enclose it in
single quotes. Both trim_character and trim_source can be any of the datatypes CHAR,
VARCHAR2, NCHAR, NVARCHAR2, CLOB, or NCLOB. The string returned is of
VARCHAR2 datatype and is in the same character set as trim_source.

Example: - This example trims leading and trailing zeroes from a number:

SELECT TRIM (0 FROM 0009872348900) "TRIM Example" FROM DUAL;

TRIM Example

------------

98723489

UPPER: - It returns char, with all letters uppercase. char can be any of the datatypes
CHAR, VARCHAR2, NCHAR, NVARCHAR2, CLOB, or NCLOB. The return value is
the same datatype as char.

Example: - The following example returns a string in uppercase:

SELECT UPPER(’Large’) "Uppercase" FROM DUAL;

Uppercase

-----

LARGE

INSTR: - The "in string" functions search string for substring. The function returns an
integer indicating the position of the character in string that is the first character. INSTR
calculates strings using characters as defined by the input character set. Both string and
substring can be any of the datatypes CHAR, VARCHAR2, NCHAR, NVARCHAR2,
CLOB, or NCLOB. The value returned is of NUMBER datatype. The default values of
both position and occurrence are 1, meaning Oracle begins searching at the first character
of string for the first occurrence of substring. The return value is relative to the beginning
of string, regardless of the value of position, and is expressed in characters. If the search
is unsuccessful (if substring does not appear occurrence times after the position character
of string), then the return value is 0.

Example: - The following example searches the string "CORPORATE FLOOR",


beginning with the third character, for the string "OR". It returns the position in
CORPORATE FLOOR at which the second occurrence of "OR" begins:

SELECT INSTR(’CORPORATE FLOOR’,’OR’, 3, 2) "Instring" FROM DUAL;


Instring

----------

14

LENGTH: - The "length" functions return the length of char. LENGTH calculates length
using characters as defined by the input character set. char can be any of the datatypes
CHAR, VARCHAR2, NCHAR, NVARCHAR2, CLOB, or NCLOB. The return value is
of datatype NUMBER. If char has datatype CHAR, then the length includes all trailing
blanks. If char is null, then this function returns null.

Example: - The following example uses the LENGTH function using a single-byte
database character set.

SELECT LENGTH(’CANDIDE’) "Length in characters" FROM DUAL;

Length in characters

--------------------

The SQL AND clause is used when you want to specify more than one condition
in your SQL WHERE clause, and at the same time you want all conditions to be
true. For example if you want to select all customers with FirstName "John" and
LastName "Smith", you will use the following SQL expression:

SELECT * FROM Customers WHERE FirstName = 'John' AND LastName =


'Smith'

The result of the SQL query above is:

FirstName LastName Email DOB Phone


John Smith John.Smith@yahoo.com 2/4/1968 626 222-2222

The following row in our Customer table, satisfies the second of the conditions
(LastName = 'Smith'), but not the first one (FirstName = 'John'), and that's why
it's not returned by our SQL query:

FirstName LastName Email DOB Phone


James Smith jim@supergig.co.uk 20/10/1980 416 323-8888
SQL OR
The SQL OR statement is used in similar fashion and the major difference
compared to the SQL AND is that OR clause will return all rows satisfying any of
the conditions listed in the WHERE clause. If we want to select all customers
having FirstName 'James' or FirstName 'Paula' we need to use the following SQL
statement:

SELECT * FROM Customers WHERE FirstName = 'James' OR FirstName =


'Paula';

The result of this query will be the following:

FirstName LastName Email DOB Phone


416 323-
Paula Brown pb@herowndomain.org 5/24/1978
3232
416 323-
James Smith jim@supergig.co.uk 20/10/1980
8888

You can combine AND and OR clauses anyway you want and you can use
parentheses to define your logical expressions. Here is an example of such a
SQL query, selecting all customers with LastName 'Brown' and FirstName either
'James' or 'Paula':

SELECT * FROM Customers WHERE (FirstName = 'James' OR FirstName =


'Paula') AND LastName = 'Brown';

The result of the SQL expression above will be:

FirstName LastName Email DOB Phone


Paula Brown pb@herowndomain.org 5/24/1978 416 323-3232

SQL IN
The SQL IN clause allows you to specify discrete values in your SQL WHERE
search criteria. THE SQL IN syntax looks like this:

SELECT Column1, Column2, Column3, … FROM Table1 WHERE Column1 IN


(Valu1, Value2, …) ;

Lets use the EmployeeHours table to illustrate how SQL IN works:

Employee Date Hours


John Smith 5/6/2004 8
Allan Babel 5/6/2004 8
Tina Crown 5/6/2004 8
John Smith 5/7/2004 9
Allan Babel 5/7/2004 8
Tina Crown 5/7/2004 10
John Smith 5/8/2004 8
Allan Babel 5/8/2004 8
Tina Crown 5/8/2004 9

Consider the following SQL query using the SQL IN clause:

SELECT * FROM EmployeeHours WHERE Date IN ('5/6/2004', '5/7/2004');

This SQL expression will select only the entries where the column Date has
value of '5/6/2004' or '5/7/2004', and you can see the result below:

Employee Date Hours


John Smith 5/6/2004 8
Allan Babel 5/6/2004 8
Tina Crown 5/6/2004 8
John Smith 5/7/2004 9
Allan Babel 5/7/2004 8
Tina Crown 5/7/2004 10

We can use the SQL IN statement with another column in our EmployeeHours
table:

SELECT * FROM EmployeeHours WHERE Hours IN (9, 10);

The result of the SQL query above will be:

Employee Date Hours


John Smith 5/7/2004 9
Tina Crown 5/7/2004 10
Tina Crown 5/8/2004 9

SQL BETWEEN
The SQL BETWEEN keyword define a range of data between 2 values. The SQL
BETWEEN syntax looks like this:

SELECT Column1, Column2, Column3, … FROM Table1 WHERE Column1


BETWEEN Value1 AND Value2 ;

The values defining the range for SQL BETWEEN clause can be dates, numbers
or just text. It gives you the ability to specify a range in your search criteria. We
are going to use the Customers table to show how SQL BETWEEN works:

FirstName LastName Email DOB Phone


626 222-
John Smith John.Smith@yahoo.com 2/4/1968
2222
323 455-
Steven Goldfish goldfish@fishhere.net 4/4/1974
4545
416 323-
Paula Brown pb@herowndomain.org 5/24/1978
3232
416 323-
James Smith jim@supergig.co.uk 20/10/1980
8888

Consider the following SQL BETWEEN statement:

SELECT * FROM Customers WHERE DOB BETWEEN '1/1/1975' AND


'1/1/2004' ;

The SQL BETWEEN statement above will select all Customers having DOB
column between '1/1/1975' and '1/1/2004' dates. Here is the result of this SQL
expression:

FirstName LastName Email DOB Phone


416 323-
Paula Brown pb@herowndomain.org 5/24/1978
3232
416 323-
James Smith jim@supergig.co.uk 20/10/1980
8888

ABS: - It returns the absolute value of n.

Syntax:: - ABS ( n )

Example: - The following example returns the absolute value of -15:

SELECT ABS(-15) "Absolute" FROM DUAL;


Absolute

----------

15

ACOS: - It returns the arc cosine of n. The argument nmust be in the range of -1 to 1, and
the function returns values in the range of 0 to p, expressed in radians.

Syntax: - ACOS ( n )

Example: - The following example returns the arc cosine of .3:

SELECT ACOS(.3) "Arc_Cosine" FROM DUAL;

Arc_Cosine

----------

1.26610367

ASIN: - It returns the arc sine of n. The argument n must be in the range of -1 to 1, and
the function returns values in the range of -p/2 to p/2 and are expressed in radians.

Syntax: - ASIN ( n )

Example: - The following example returns the arc sine of .3:

SELECT ASIN(.3) "Arc_Sine" FROM DUAL;

Arc_Sine

---------- .

304692654

ATAN: - It returns the arc tangent of n. The argument n can be in an unbounded range,
and the function returns values in the range of -p/2 to p/2 and are expressed in radians.

Syntax: - ATAN ( n )

Example: - The following example returns the arc tangent of .3:

SELECT ATAN(.3) "Arc_Tangent" FROM DUAL;


Arc_Tangent

---------- .

291456794

CEIL: - It returns smallest integer greater than or equal to n.

Syntax: - CEIL ( n )

Example: - The following example returns the smallest integer greater than or equal to
15.7:

SELECT CEIL(15.7) "Ceiling" FROM DUAL;

Ceiling

----------

16

COS: - It returns the cosine of n (an angle expressed in radians).

Syntax: - COS ( n )

Example: - The following example returns the cosine of 180 degrees:

SELECT COS(180 * 3.14159265359/180) "Cosine of 180 degrees" FROM DUAL;

Cosine of 180 degrees

---------------------

-1

EXP: - It returns e raised to the nth power, where e = 2.71828183 ...

Syntax: - EXP ( n )

Example: - The following example returns e to the 4th power:

SELECT EXP(4) "e to the 4th power" FROM DUAL;

e to the 4th power

------------------
54.59815

FLOOR: - It returns largest integer equal to or less than n.

Syntax: - FLOOR ( n )

Example: - The following example returns the largest integer equal to or less than 15.7:

SELECT FLOOR(15.7) "Floor" FROM DUAL;

Floor

----------

15

POWER: - It returns m raised to the nth power. The base m and the exponent n can be
any numbers, but if m is negative, then n must be an integer.

Syntax: - POWER ( m , n )

Example: - The following example returns 3 squared:

SELECT POWER(3,2) "Raised" FROM DUAL;

Raised

----------

ROUND (number): - It returns number rounded to integer places right of the decimal
point. If integer is omitted, then number is rounded to 0 places. integer can be negative to
round off digits left of the decimal point. integer must be an integer.

Syntax: - ROUND ( number , integer )

Example: - The following example rounds a number to one decimal point:

SELECT ROUND(15.193,1) "Round" FROM DUAL;

Round

----------

15.2
The following example rounds a number one digit to the left of the decimal point:

SELECT ROUND(15.193,-1) "Round" FROM DUAL;

Round

----------

20

SIGN: - It returns -1 if n<0, then . If n=0, then the function returns 0. If n>0, then SIGN
returns 1.

Syntax: - SIGN ( n )

Example: - The following example indicates that the function’s argument (-15) is <0:

SELECT SIGN(-15) "Sign" FROM DUAL;

Sign

----------

-1

SIN: - It returns the sine of n (an angle expressed in radians).

Syntax: - SIN ( n )

Example: - The following example returns the sin of 30 degrees:

SELECT SIN(30 * 3.14159265359/180) "Sine of 30 degrees" FROM DUAL;

Sine of 30 degrees

------------------

.5

SQRT: - It returns the square root of n. The value n cannot be negative. SQRT returns a
real number.

Syntax: - SQRT ( n )

Example: - The following example returns the square root of 26:


SELECT SQRT(26) "Square root" FROM DUAL;

Square root

-----------

5.09901951

TAN: - It returns the tangent of n (an angle expressed in radians).

Syntax: - TAN ( n )

Example: - The following example returns the tangent of 135 degrees:

SELECT TAN(135 * 3.14159265359/180) "Tangent of 135 degrees" FROM DUAL;

Tangent of 135 degrees

----------------------

-1

TRUNC (number): - The TRUNC (number) function returns n truncated to m decimal


places. If m is omitted, then n is truncated to 0 places. m can be negative to truncate
(make zero) m digits left of the decimal point.

Syntax: - TRUNC ( n , m )

Example: - The following example truncate numbers:

SELECT TRUNC(15.79,1) "Truncate" FROM DUAL;

Truncate

----------

15.7

SELECT TRUNC(15.79,-1) "Truncate" FROM DUAL;

Truncate

----------

10
Subqueries are similar to SELECT chaining. While SELECT chaining combines
SELECTs on the same level in a query, however, subqueries allow SELECTs to
be embedded inside other queries:

They can take the place of a constant 20 (Scalar Subqueries),


They can return a list of values for use in a comparison.
They can take the place of a constant yet vary based on the row being
processed,

Subqueries are used in the following subquery expressions which return Boolean
(true/false) results.

EXISTS ( subquery )
The argument of EXISTS is an arbitrary SELECT statement. The subquery is
evaluated to determine whether it returns any rows. If it returns at least one row,
the result of EXISTS is TRUE; if the subquery returns no rows, the result of
EXISTS is FALSE.

The subquery can refer to variables from the surrounding query, which will act as
constants during any one evaluation of the subquery.

This simple example is like an inner join on col2, but it produces at most one
output row for each tab1 row, even if there are multiple matching tab2 rows:

SELECT col1 FROM tab1 WHERE EXISTS(SELECT 1 FROM tab2 WHERE col2
= tab1.col2);

Example "Students in Projects":

SELECT name FROM stud WHERE EXISTS( SELECT 1 FROM assign WHERE
stud = stud.id ) ;

name

------

fred

john

lisa

[ NOT ] IN
IN [ NOT ] (scalar form) expression IN = (value[, ...]) The right-hand side of this
form of IN is a parenthesized list of scalar expressions. The result is TRUE if the
left-hand expression's result is equal to any of the right-hand expressions.

IN [ NOT ] (subquery form) expression IN (subquery) The right-hand side of this


form of IN is a parenthesized subquery, which must return exactly one column.
The left-hand expression is evaluated and compared to each row of the subquery
result. The result of IN is TRUE if any equal subquery row is found.

Example "Is fred in Project 1? (--Yes)":

SELECT id, name FROM = stud WHERE id in ( SELECT stud FROM assign
WHERE id = 1 ) ;

id | name

----+------

1 | fred

ANY and SOME

expression operator ANY (subquery) expression operator SOME (subquery) The


right-hand side of this form of ANY is a parenthesized subquery, which must
return exactly one column. The left-hand expression is evaluated and compared
to each row of the subquery result using the given operator, which must yield a
Boolean result. The result of ANY is TRUE if any true result is obtained.

SOME is a synonym for ANY.

ALL

expression operator ALL (subquery) The right-hand side of this form of ALL is a
parenthesized subquery, which must return exactly one column. The left-hand
expression is evaluated and compared to each row of the subquery result using
the given operator, which must yield a Boolean result. The result of ALL is TRUE
if all rows yield TRUE (including the special case where the subquery returns no
rows).

NOT IN is equivalent to <> ALL.

Views
In SQL, a VIEW is a virtual table based on the result-set of a SELECT statement.
A view contains rows and columns, just like a real table. The fields in a view are
fields from one or more real tables in the database. You can add SQL functions,
WHERE, and JOIN statements to a view and present the data as if the data were
coming from a single table.

Note: The database design and structure will NOT be affected by the functions,
where, or join statements in a view.

Syntax: -

CREATE VIEW view_name AS SELECT column_name(s) FROM table_name


WHERE condition

Note: The database does not store the view data! The database engine recreates
the data, using the view's SELECT statement, every time a user queries a view.

Using Views
A view could be used from inside a query, a stored procedure, or from inside
another view. By adding functions, joins, etc., to a view, it allows you to present
exactly the data you want to the user. The sample database Northwind has some
views installed by default. The view "Current Product List" lists all active products
(products that are not discontinued) from the Products table. The view is created
with the following SQL:

CREATE VIEW [Current Product List] AS SELECT ProductID,ProductName


FROM Products WHERE Discontinued=No

We can query the view above as follows:

SELECT * FROM [Current Product List]

Another view from the Northwind sample database selects every product in the
Products table that has a unit price that is higher than the average unit price:

CREATE VIEW [Products Above Average Price] AS SELECT


ProductName,UnitPrice FROM Products WHERE UnitPrice>(SELECT
AVG(UnitPrice) FROM Products)

We can query the view above as follows:

SELECT * FROM [Products Above Average Price]


Another example view from the Northwind database calculates the total sale for
each category in 1997. Note that this view selects its data from another view
called "Product Sales for 1997":

CREATE VIEW [Category Sales For 1997] AS SELECT DISTINCT


CategoryName,Sum(ProductSales) AS CategorySales FROM [Product Sales for
1997] GROUP BY CategoryName

We can query the view above as follows:

SELECT * FROM [Category Sales For 1997] We can also add a condition to the
query.

Now we want to see the total sale only for the category "Beverages":

SELECT * FROM [Category Sales For 1997] WHERE


CategoryName='Beverages'

Alter Table Statement

The ALTER TABLE statement is used to add, delete, or modify columns in an existing
table.

The alter statement can be used for one of the following reasons:

1. A column needs some particular constraint or a constraint on a column needs


to be dropped.
2. Data Type or Size of a column needs to be changed.
3. A column name of a table needs to be changed or table name itself needs to
be changed.
4. Some columns need to be dropped or added to the table.

Here we can’t drop the table because the table is already loaded and its data is
referred by some other object.

To overcome these issues alter table command is useful. Before looking into those
Alter table commands let us first create one test table namely ‘employee’.

Create a Dummy Table i.e. “Employee”

CREATE TABLE employee ( EMP_ID NUMBER ,EMPLOYEE_NAME


VARCHAR2(30)

,AGE NUMBER ,SALARY NUMBER(5) ,JOB_TITLE VARCHAR2(30)

);
Insert Records into Dummy Table i.e. “Employee”

INSERT INTO employee VALUES(101,'John',25,20000,'Marketing Executive') ;

INSERT INTO employee VALUES(102,'Smith',28,12000,'Service Technician') ;

INSERT INTO employee VALUES(103,'Jackson',23,15000,'Manager') ;

INSERT INTO employee VALUES(104,'Scott',30,11000,'Developer') ;

INSERT INTO employee VALUES(105,'Herison',26,13000,'Purchage Officer') ;

Select * from employee;

Fetch the Data from Dummy Table i.e. “Employee”

EMP_ID EMPLOYEE_NAME AGE SALARY JOB_TITLE

105 Harrison 26 13,000 Purchase Officer

104 Scott 30 11,000 Developer

103 Jackson 23 15,000 Manager

102 Smith 28 12,000 Service Te

101 John 25 20,000 Executive


[-] To add a constraint to a table column

Syntax: ALTER TABLE <table_name> MODIFY <column_name>


<constarint> ;

Example ALTER TABLE employee MODIFY emp_id NOT NULL;

[-] To drop a constraint on a table column

Syntax: ALTER TABLE <table_name> DROP CONSTRAINT <constraint_name>


;

(without quotes)

Example: ALTER TABLE employee DROP CONSTRAINT SYSC120000;

Note:

1. All the system defined constraints starts with 'SYS_.'.

2. If constraint name is not known then first find out the name of
constraint on a column.

Syntax:

SELECT * FROM all_constraints WHERE table_name =


UPPER(&table_name)

Example:

SELECT * FROM all_constraints WHERE table_name =


UPPER('employee') ;

[-] To drop a column from a table

Syntax: ALTER TABLE <table_name>

DROP (<column1, column2, column3, column4...>) ;

Example:

ALTER TABLE employee DROP (emp_name, emp_address) ;

[-] To add a new column to a table

Syntax: ALTER TABLE <table_name> ADD <column_name and datatype> ;

Example: ALTER TABLE employee ADD emp_name VARCHAR2(15) ;

[-] To change the column name of a table


Syntax: ALTER TABLE <table_name>

RENAME COLUMN <old_column_name> TO <new_column_name> ;

Example:

ALTER TABLE employee RENAME COLUMN emp_id TO employee_id ;

[-] To rename an existing table name

Syntax: RENAME <old_table_name> TO <new_table_name>;

Example: RENAME employee TO employee1;

There is one more syntax for this

Syntax: ALTER TABLE <old_table_name> RENAME TO <new_table_name> ;

Example: ALTER TABLE employee RENAME TO employee1;

[-] To change the data type of a column

Syntax: ALTER TABLE <table_name>

MODIFY <column_name> <new_data_type and size> ;

Example: ALTER TABLE employee MODIFY employee_name VARCHAR2(20) ;

Note:

1. DATA TYPE of a column can not be changed until the column is having values
populated i.e. to change the DATA TYPE column should not have NULL values
for all the records
2. Column SIZE always can be reduced to the maximum size of data present in
that column.
3. There is no restriction on increase in SIZE of a column.

Joins

Joins are used to retrieve data from two or more tables with relevant conditions which
uses the primary key for the table for referencing. Join operation takes two tables as
input and return another table as output. When ever we perform a JOIN, we must
specify one column that is common in both the tables that are participating in the
JOIN. Here we can use multiple joins in the same SQL statement to query data from
as many tables as we like to join.

The join return rows when there is at least one match i.e. column in the participated
tables.

There are 4 types of Joins


1] Inner Join

2] Outer Join

2.1] Left Outer Join

2.2] Right Outer Join

2.3] Full Outer Join

3] Cartesian Join

4] Self Join

Você também pode gostar