Escolar Documentos
Profissional Documentos
Cultura Documentos
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.
1. DDL (Data Definition Language) :- DDL is used to define, modify and delete the
schema (structure of the database objects).
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
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.
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.
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 Valid date range from January 1, 4712 BC to December 31, 9999 AD. 180
RAW( size) Raw binary data of length size bytes. Maximum size is 2000 bytes. You must
specify size for a RAW value.
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.
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.
.........
[<table constraint(s)>]
);
Examples: -
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.
(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: - If you want to change the size of TeacherName in the Teacher table.
You can do it with the following statement:-
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.
Example: - If you want to delete the Marks table. You can delete it using the
following statement:-
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>];
Table Constraints: - These are associated with more than one column.
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
Example:
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:
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:
Syntax: -
insert into <table name> [(<column i, . . . , column j>)]values (<value i, . . . , value j>);
Examples: -
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: -
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: -
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: -
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%.
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.
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:
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;
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?
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:
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.
Job
------------------------------------------------------
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 left-pads a string with the characters "*" and ".":
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:
LTRIM example
------------
XxyLAST WORD
Changes
--------------
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:
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:
RTRIM examp
-----------
BROWNINGyxX
Substring
---------
CDEF
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:
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.
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.
----------
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.
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:
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:
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':
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:
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:
We can use the SQL IN statement with another column in our EmployeeHours
table:
SQL BETWEEN
The SQL BETWEEN keyword define a range of data between 2 values. The SQL
BETWEEN syntax looks like this:
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:
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:
Syntax:: - ABS ( n )
----------
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 )
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 )
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 )
---------- .
291456794
Syntax: - CEIL ( n )
Example: - The following example returns the smallest integer greater than or equal to
15.7:
Ceiling
----------
16
Syntax: - COS ( n )
---------------------
-1
Syntax: - EXP ( n )
------------------
54.59815
Syntax: - FLOOR ( n )
Example: - The following example returns the largest integer equal to or less than 15.7:
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 )
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.
Round
----------
15.2
The following example rounds a number one digit to the left of the decimal point:
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:
Sign
----------
-1
Syntax: - SIN ( n )
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 )
Square root
-----------
5.09901951
Syntax: - TAN ( n )
----------------------
-1
Syntax: - TRUNC ( n , m )
Truncate
----------
15.7
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:
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);
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.
SELECT id, name FROM = stud WHERE id in ( SELECT stud FROM assign
WHERE id = 1 ) ;
id | name
----+------
1 | fred
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).
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: -
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:
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:
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":
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:
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’.
);
Insert Records into Dummy Table i.e. “Employee”
(without quotes)
Note:
2. If constraint name is not known then first find out the name of
constraint on a column.
Syntax:
Example:
Example:
Example:
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.
2] Outer Join
3] Cartesian Join
4] Self Join