Documente Academic
Documente Profesional
Documente Cultură
of SQL
By,
Asmatullah Khan,
CL/CP, GIOE,
Secunderabad.
Outline
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
13.
14.
SQL
SQL is a nonprocedural language.
This means that a query formulated in SQL need not specify how a problem is to be
solved nor how data should be accessed by the computing system; instead, an SQL query
states what the query is, i.e., what data are sought.
This leaves the user free to focus on the logic of the query.
Because the DBMS makes use of its internal knowledge, in most cases, the DBMS
generates retrieval procedures that are faster than equivalent retrieval procedures
built directly by the user.
The SQL language consists of three components:
the data definition language (DDL),
the data manipulation language (DML), and
the data control language (DCL).
The first component allows the user to define the structure of the tables of the
database.
The second contains retrieval and update directives.
The last component allows the database administrator to define the access rights
to the database for various categories of users.
SQL syntax is format-free: tabs, carriage returns, and spaces can be included
anywhere a space occurs in the definition of an SQL construct.
Also, case is insignificant in table names, reserved words and keywords.
However, case is significant in character string literals.
SQL Queries can be used to retrieve large amounts of records from a database quickly and
efficiently.
SQL databases use long-established standard, which is being adopted by ANSI & ISO.
Non-SQL databases do not adhere to any clear standard.
No Coding Required:
Using standard SQL it is easier to manage database systems without having to write
substantial amount of code.
Emergence of ORDBMS:
Disadvantages of SQL:
Difficulty in Interfacing:
Interfacing an SQL database is more complex than adding a few lines of code.
More Features Implemented in Proprietary way:
Although SQL databases conform to ANSI & ISO standards, some databases go for
proprietary extensions to standard SQL to ensure vendor lock-in.
Embedded SQL
SQL provides a powerful declarative query language. However, access to
a database from a general-purpose programming language is required
because,
SQL is not as powerful as a general-purpose programming language. There
are queries that cannot be expressed in SQL, but can be programmed in C,
Fortran, Pascal, Cobol, etc.
Nondeclarative actions -- such as printing a report, interacting with a user, or
sending the result to a GUI -- cannot be done from within SQL.
The SQL standard defines embedding of SQL as embedded SQL and the
language in which SQL queries are embedded is referred as host
language.
The result of the query is made available to the program one tuple
(record) at a time.
To identify embedded SQL requests to the preprocessor, we use EXEC
SQL statement:
EXEC SQL embedded SQL statement END-EXEC
Note: A semi-colon is used instead of END-EXEC when SQL is embedded
in C or Pascal.
FROM employees;
iSQL*Plus
Oracle9i Database introduced a version of SQL*Plus you can access from your Web browser, Called
iSQL*Plus, it's a three-tier application in which the work is done on your behalf by an application service
running on the database server.
Like SQL*Plus, iSQL*Plus can be used to execute SQL*Plus commands, SQL statements, PL/SQL blocks,
and XML queries.
One benefit of iSQL*Plus is that you can provision SQL*Plus access to a group of users without having to
install client software on each user's local PC.
The enhanced SQL Workshop in Oracle Application Express 2.0 provides interactive SQL execution,
GUI-based query building (in a browser!), script editing and execution, a very nice object browser, the
easiest comma-separated-values (CSV) importing ever seen, and more.
Query Builder
the drag-and-drop version of a query
Object Browser
object browser feature is the ability to view diagrams showing groups of related tables.
Export/Import
SQL Workshop offers a useful set of utilities and canned reports, including one of the neatest utilities for importing
comma-delimited data.
The schema qualifier lets you refer to an object in a schema other than your own.
You must be granted privileges to refer to objects in other schemas.
If you omit schema, then Oracle assumes that you are referring to an object in your own
schema.
This identifier lets you refer to a part of a schema object, such as a column or a partition of a
table.
Not all types of objects have parts.
dblink applies only when you are using the Oracle Database distributed functionality.
This is the name of the database containing the object.
The dblink qualifier lets you refer to an object in a database other than your local database.
If you omit dblink, then Oracle assumes that you are referring to an object in your local
database.
Not all SQL statements allow you to access objects on remote databases.
schema.object
User roles
Public synonyms
Public database links
Tablespaces
Profiles
Parameter files (PFILEs) and server
parameter files (SPFILEs)
The statement lets you specify this information about the database link:
The name of the database link
The database connect string to access the remote database
The username and password to connect to the remote database
database should specify the name portion of the global name of the remote database to which
the database link connects.
This global name is stored in the data dictionary of the remote database;
you can see this name in the GLOBAL_NAME data dictionary view.
domain should specify the domain portion of the global name of the remote database to which
the database link connects.
If you omit domain from the name of a database link, then Oracle qualifies the database link
name with the domain of your local database as it currently exists in the data dictionary.
connect_descriptor lets you further qualify a database link.
Using connect descriptors, you can create multiple database links to the same database.
Character literals are enclosed in single quotation marks so that Oracle can distinguish
them from schema object names.
You can specify character literals with the 'text' notation, national character
literals with the N'text' notation (Standard SQL defines NCHAR or NATIONAL
CHAR as a way to indicate that a CHAR column should use some predefined
character set), and numeric literals with the integer, or number notation,
depending on the context of the literal.
Here are some valid text literals:
'Hello'
'ORACLE.dbs'
'Jackie
's raincoat'
'09-MAR-98'
N'nchar literal
Pseudo-columns
A pseudo-column is an Oracle assigned value (pseudo-field) used in the same
context as an Oracle Database column, but not stored on disk.
SQL and PL/SQL recognizes the following SQL pseudocolumns, which return
specific data items:
SYSDATE,
SYSDATE
SYSTIMESTAMP
--------- ---------------------------------------13-DEC-07
13-DEC-07 10.02.31.956842 AM +02:00
SYSTIMESTAMP,
ROWID - returns the rowid (binary address) of a row in a database table.
ROWNUM - returns a number indicating the order in which a row was selected from a table.
UID,
USER,
SQL> SELECT uid, user FROM dual;
UID
USER
---------- -----------------------------50 MICHEL
LEVEL,
CURRVAL,
NEXTVAL,
sequence_name.CURRVAL
sequence_name.NEXTVAL
INSERT INTO emp VALUES (empno_seq.NEXTVAL, my_ename, ...);
ORA_ROWSCN, etc.
There are two syntaxes that you can use to create a comment in SQL.
A comment that starts with /* symbol and ends with */ and can be
anywhere in your SQL statement.
This method of commenting can span several lines within your SQL.
2.Group Functions:
These are functions that accept numeric input and return numeric values.
These are functions that accept character input and can return both character and number
values.
3. Date Functions:
These are functions that take values that are of datatype DATE as input and return values
of datatype DATE, except for the MONTHS_BETWEEN function, which returns a
number.
4. Conversion Functions:
These are functions that help us to convert a value in one form to another form.
For Example: a null value into an actual value, or a value from one datatype to another
datatype like NVL, TO_CHAR, TO_NUMBER, TO_DATE etc.
Function
Name
ABS (x)
CEIL (x)
FLOOR (x)
Return Value
Absolute value of the number
'x'
ABS (1)
ABS (-1)
1
-1
CEIL (x)
CEIL (2.83)
CEIL (2.49)
CEIL (-1.6)
3
3
-1
FLOOR (x)
FLOOR (2.83)
FLOOR (2.49)
FLOOR (-1.6)
2
2
-2
TRUNC (x, y)
ROUND (125.456, 1)
ROUND (125.456, 0)
ROUND (124.456, -1)
125.4
125
120
ROUND (x, y)
TRUNC (140.234, 2)
TRUNC (-54, 1)
TRUNC (5.7)
TRUNC (142, -1)
140.23
54
5
140
TRUNC (x, y)
ROUND (x, y)
Return Value
Function Name
Return Value
LOWER (string_value)
UPPER (string_value)
INITCAP (string_value)
All occurrences of 'trim_text'from the left and right of string_value' , 'trim_text' can
also be only one character long .
SUBSTR (string_value, m, n)
Returns 'n' number of characters from 'string_value'starting from the 'm' position.
LENGTH (string_value)
Returns 'string_value' left-padded with 'pad_value' . The length of the whole string
will be of 'n' characters.
Returns 'string_value' right-padded with 'pad_value' . The length of the whole string
will be of 'n' characters.
Function Name
Examples
Return Value
LOWER(string_value)
LOWER('Good Morning')
good morning
UPPER(string_value)
UPPER('Good Morning')
GOOD MORNING
INITCAP(string_value)
INITCAP('GOOD MORNING')
Good Morning
LTRIM(string_value, trim_text)
Morning
Gd Mrning
SUBSTR (string_value, m, n)
Morning
LENGTH (string_value)
12
**Good
Good**
Function Name
Return Value
ADD_MONTHS (date, n)
LAST_DAY (x)
SYSDATE
Function Name
Examples
Return
Value
ADD_MONTHS ( )
ADD_MONTHS ('16-Sep-81',
3)
16-Dec-81
MONTHS_BETWEEN( )
NEXT_DAY( )
NEXT_DAY ('01-Jun-08',
'Wednesday')
04-JUN-08
LAST_DAY( )
LAST_DAY ('01-Jun-08')
30-Jun-08
NEW_TIME( )
NEW_TIME ('01-Jun-08',
'IST', 'EST')
31-May-08
Function Name
TO_CHAR (x [,y])
Return Value
Examples
Return
Value
TO_DATE (x [, date_format])
NVL (x, y)
DECODE (a, b, c, d, e,
default_value)
Function
Name
TO_CHAR
(3000, '$9999')
TO_CHAR () TO_CHAR
(SYSDATE, 'Day,
Month YYYY')
$3000
Monday,
June
2008
TO_DATE ()
TO_DATE ('01Jun-08')
01-Jun08
NVL ()
NVL (null, 1)
Group Functions
Group functions are built-in SQL functions that operate on groups of
rows and return one value for the entire group.
COUNT()
Count returns the number of rows present in the table either based on some
condition or without condition.
FIRST()
LAST()
MAX()
MAX function returns maximum value from selected column of the table.
MIN()
MIN function returns minimum value from a selected column of the table.
AVG()
SUM()
DISTINCT()
A format model is a character literal that describes the format of datetime or numeric
data stored in a character string.
A format model does not change the internal representation of the value in the database.
For example:
The datetime format model for the string '17:45:29' is 'HH24:MI:SS'.
The datetime format model for the string '11-Nov-1999' is 'DD-Mon-YYYY'.
All number format models cause the number to be rounded to the specified
number of significant digits.
If a value has more significant digits to the left of the decimal place than are
specified in the format,
then pound signs (#) replace the value.
Format
Description
Example
9999=' 123
09999=00123
9999D00=123.00
FM9999=123
Include a leading $
$999=$123
Over-ride the '0' format and replace leading 0's with blank spaces ' '
B9999=' 123'
FM
S999 =+123
999S =123+
PR999=<123>
PR999=' 123 '
999MI=123-
PR
MI
9G999=1,234
,
.
C
L
9,999=1,234
99.99=12.34
C99
L99
9.9EEEE= 1.2E+02
Text Minimum
TM9(the default) or TME (Scientific notation)
TM9=12345
TME=1.2E+02
Returns in the specified position the Euro (or other) dual currency symbol.
U9999 = 1234
Return a value multiplied by 10n, wherenis the number of 9's after the V.
(valuewill be rounded up if necessary)
RN or rn
EEEE
TM
RN99=XI
99D99=12.34
These SQL commands are used for creating, modifying, and dropping the
structure of database objects.
The commands are CREATE, ALTER, DROP, RENAME, and TRUNCATE.
These SQL commands are used for storing, retrieving, modifying, and deleting
data.
These commands are SELECT, INSERT, UPDATE, and DELETE.
These SQL commands are used for managing changes affecting the data.
These commands are COMMIT, ROLLBACK, and SAVEPOINT.
These SQL commands are used for providing security to database objects.
These commands are GRANT and REVOKE.
All the SQL statements start with any of the keywords like SELECT, INSERT,
UPDATE, DELETE, ALTER, DROP, CREATE, USE, SHOW and the entire
statements end with a semicolon (;).
Creating a Table
create table command will tell the database system to create a new table with
given table name and column information.
The above command will create a new table Student in database system with 3
columns, namely id, name and age.
Using alter command we can add a column to an existing table. Following is the Syntax,
The above command will add three new columns to the Student table
Using alter command we can even add multiple columns to an existing table. Following is the Syntax,
The above command will add a new column address to the Student table
alter command can add a new column to an existing table with default values. Following is the Syntax,
The above command will add a new column with default value to the Student table
alter command is used to modify data type of an existing column . Following is the Syntax,
The above command will modify address column of the Student table
To Rename a column
Using alter command you can rename an existing column. Following is the Syntax,
To Drop a Column
alter command is also used to drop columns also. Following is the Syntax,
The above command will drop address column from the Student table
DML command
Data Manipulation Language (DML) statements are used for managing
data in database.
DML commands are not auto-committed.
It means changes made by DML command are not permanent to
database, it can be rolled back.
SELECT Query
Select query is used to retrieve data from a tables.
It is the most used SQL query.
We can retrieve complete tables, or partial by mentioning conditions using
WHERE clause.
INSERT command
UPDATE command
DELETE command
Delete command is used to delete data from a table. Delete command can
also be used with condition to delete a particular row.
TCL Commands
Transaction Control Language(TCL) commands are
used to manage transactions in database.
These are used to manage the changes made by
DML statements.
It also allows statements to be grouped together
into logical transactions.
Commit command
Rollback command
Savepoint command
DCL Commands
Data Control Language(DCL) is used to control
privilege in Database.
To perform any operation in the database, such as for
creating tables, sequences or views we need privileges.
Privileges are of two types,
System : creating session, table etc are all types of system
privilege.
Object : any command or query to work on tables comes
under object privilege.
NOT NULL
UNIQUE
PRIMARY KEY
FOREIGN KEY
CHECK
DEFAULT
SQL Subquery
Subquery or Inner query or Nested query is a query in
a query.
SQL subquery is usually added in the WHERE Clause of the
SQL statement.
Most of the time, a subquery is used when you know how to
search for a value using a SELECT statement, but do not
know the exact value in the database.
Subqueries are an alternate way of returning data from
multiple tables.
Subqueries can be used with the following SQL statements
along with the comparison operators like =, <, >, >=, <= etc.
SELECT
INSERT
UPDATE
DELETE
Usually, a subquery should return only one record, but sometimes it can also return multiple records when used with
operators LIKE IN, NOT IN in the where clause.
The query syntax would be like,
Lets consider the student_details table which we have used earlier. If you know the name of the students who are studying
science subject, you can get their id's by using this query below,
Correlated Subquery
A query is called correlated subquery when both the
inner query and the outer query are interdependent.
For every row processed by the inner query, the outer
query is processed as well.
The inner query depends on the outer query before it
can be processed.