Sie sind auf Seite 1von 17

Advanced SQL

SQL is a very powerful and diverse database language use to storing data
into databases. SQL is loosely typed language so you can learn easily.
In this SQL tutorial, we use command line examples to know about executing
speed of SQL. It's take very bit of time for executing and retrieving result.
SQL is a greater tool with web languages such as PHP, Python, Java, ASP et
cetera to build dynamic web applications.
Before starting SQL, relational databases have several point that are
important to keep in mind.
1. RDBMS stands for Relational Database Management System.
2. Data Integrity : Store data only once and avoiding data duplication.
3. SQL Constraints : Constraints are the rules which are apply to table
columns to store valid data and prevents the user to storing/entering
invalid data into table columns.
4. Better security : Assign grant or privilege to a individual User. Using
this grant user can store confidential data into table by using
username or password.
5. Database Normalization : Database normalization is the process to
store database data very efficiently. No need to store same data more
then one time and reduce the Data redundancy.
6. Different types of relationships : One to one, One to many, Many to
many
1. One to one relationship : merging for two tables.
2. One to many relationship : create a foreign key from an parent
table to the child table.
3. Many to many relationship : create a new relation table.
Keep in your mind...

SQL is not case sensitive.

But SQL Data is a case sensitive.

SQL Process Flow

When you execute SQL query come to a SQL Server. SQL Server work is
managing database, load balancing, transaction management etc. SQL
server call to a actual physical database table and return the result. This
process is take small bit of time and depend of query and SQL server load.

Rules of Semicolon(;) or Forward Slash(/) in SQL


There is a huge difference in SQL between the meaning of a / and
a ; because they work differently.

SQL database systems require semicolon(;) at the end of statement to


know it's ending.

Use forward slash(/) once at the end of each script, to tell SQL that
there is not more lines of code. you can't use forward slash(/) at the
middle of the script.

The ; means terminate the current statement execute it and store it to


the "SQL buffer", whereas the / executes whatever statement script is in the
current "SQL buffer".

Type of SQL Statement (DDL, DML, DCL, TCS, SCS Commands)


SQL statements are divided into five different categories: Data definition
language (DDL), Data manipulation language (DML), Data Control Language
(DCL), Transaction Control Statement (TCS), Session Control Statements
(SCS).
Data Definition Language (DDL) Statements

Data definition statement are use to define the database structure or table.
Statement

Description

CREATE

Create new database/table.

ALTER

Modifies the structure of database/table.

DROP

Deletes a database/table.

TRUNCATE

Remove all table records including allocated table


spaces.

RENAME

Rename the database/table.

Data Manipulation Language (DML) Statements


Data manipulation statement are use for managing data within table object.
Statement

Description

SELECT

Retrieve data from the table.

INSERT

Insert data into a table.

UPDATE

Updates existing data with new data within a table.

DELETE

Deletes the records rows from the table.

MERGE

MERGE (also called UPSERT) statements to INSERT new


records or UPDATE existing records depending on
condition matches or not.

LOCK TABLE

LOCK TABLE statement to lock one or more tables in a


specified mode. Table access denied to a other users for
the duration of your table operation.

CALL
EXPLAIN PLAN

Statements are supported in PL/SQL only for executed


dynamically. CALL a PL/SQL program or EXPLAIN PATH
access the data path.

Data Control Language (DCL) Statements


Data control statement are use to give privileges to access limited data.
Statement

Description

GRANT

Gives privileges to user for accessing database data.

REVOKE

Take back for given privileges.

ANALYZE

ANALYZE statement to collect statistics information


about index, cluster, table.

AUDIT

To track the occurrence of a specific SQL statement or all


SQL statements during the user sessions.

COMMENT

Write comment to the data table.

Transaction Control Statement (TCS)


Transaction control statement are use to apply the changes permanently
save into database.
Statement

Description

COMMIT

Permanent work save into database.

ROLLBACK

Restore database to original form since the last COMMIT.

SAVEPOINT

Create SAVEPOINT for later use ROLLBACK the new


changes.

SET
TRANSACTION

SET TRANSACTION command set the transaction


properties such as read-write/read only access.

PL/SQL Transaction Commit, Rollback, Savepoint, Autocommit, Set


Transaction read more.
Session Control Statements (SCS)
Session control statement are manage properties dynamically of a user
session.
Statement

Description

ALTER SESSION

ALTER SESSION statement to modify conditions or


parameters that are affect to your database connection.

SET ROLE

SET ROLE statement to enable or disable the roles that


are currently enabled for the session.

Oracle database provide built-in SQL data types also you can make user
define types for letter use as data types. Every database define a column
data type for each and every tables.
SQL data types are two type scaler type or non scalar type. Scalar SQL data
types haven't internal components. It's like linear data types. Whereas non
scalar SQL data types have internal component to store multiple values and
easily you can manipulate the data.
Oracle SQL Data types
Built-in Oracle SQL data types are following,
1. Numeric Datatypes
2. Character Datatypes
3. LONG and ROW Datatypes
4. ROWID Datatypes
5. Datetime Datatypes
6. Large Object Datatypes

Number Datatypes
Following are numeric data types in SQL
Data Type

Description

NUMBER data type use to store numeric data.


NUMBER
NUMBER data type have precision and scale.
[ ( precision [, scale Storage Range : Precision range(p) : 1 to 38 and
])
Scale range(s) : -84 to 127
NUMBER Subtypes : This sub type supported ANSI,

DB2, and SQL data type define different type


storage range.
ANSI, DB2
Datatypes

Maximum
Precision

INTEGER

38 digits

INT

38 digits

SMALLINT

38 digits

FLOAT [ (size) ]

126 binary
digits

FLOAT(126)

DOUBLE PRECISION

126 binary
digits

FLOAT(126)

REAL

63 binary
digits

FLOAT(63)

DECIMAL[(precision
38 digits
[, scale ])]
NUMERIC[(precision
38 digits
[, scale ])]

Oracle Data
types

NUMBER(p,0)

NUMBER(p,s)

FLOAT data type is subtype of NUMBER datatype.


FLOAT [ ( precision )
Storage Range : Precision range(p) : 1 to 126
]
Example : col1 FLOAT(2)

BINARY_FLOAT

BINARY_FLOAT datatype use binary precision (32bit).


This data type requires 5 bytes including length
byte.
Advantages : Arithmetic calculations fast and
reduces the storage requirements.

BINARY_DOUBLE

BINARY_DOUBLE datatype use double binary


precision (64-bit).
This data type requires 9 bytes including length
byte.

Character Datatypes

Character Data type use to store alphabetic/alphanumeric, following are


character data types in Oracle SQL:
Data Type

Description

Storage(Maxim
um)

CHAR
[ (size) ]

CHAR data type use to store character


data within predefined length.

2000 bytes

NCHAR
[ (size) ]

NCHAR data type use to store national


character data within predefined length.

2000 bytes

VARCHAR2 data type use to store variable


strings data within predefined length.
You have to must specify the size of
VARCHAR2 datatype.
VARCHAR2 Subtypes : This sub type
VARCHAR2(siz define same length value.
4000 bytes
e)
Sub
Description
Datatype
VARCHAR(siz You can also use this data
e)
type.
NVARCHAR2 data type use to store
Unicode string data within predefined
NVARCHAR2(s
length.
ize)
You have to must specify the size of
NVARCHAR2 datatype.

4000 bytes

LONG and ROW Datatypes


LONG and ROW data type store variable strings data within predefined
length, This datatype use for backward compatibility. following are LONG and
ROW datatypes in Oracle SQL:
Storage(Maxim
um)

Data Type

Description

RAW(size)

RAW data type use to store binary data such


as image, graphics etc.
2000 bytes
You have to must specify the size of RAW
column data type.

LONG

LONG data type use to store variable strings


data within predefined length, This data
upto 2
type use for backward compatibility. Please gigabytes
use CLOB instead of LONG type.

LONG RAW data type same as LONG type


use to store variable strings data within
LONG RAW predefined length, This data type use for
backward compatibility. Please use BLOB
instead of LONG RAW type.

upto 2
gigabytes

ROWID Datatypes
ROWID data type represent actual storage address of a row. following are
ROWID datatypes in Oracle SQL:
Storage(Maxim
um)

Data Type

Description

ROWID

ROWID data type represent actual storage address of a row.


and table index identities as a logical rowid. This data type
use for backward compatibility. Recommended to use
UROWID data type.

UROWID data type identify as universal


rowid. Same as ROWID type and use newer
UROWID[(si developing applications use UROWID data
4000 bytes
ze)]
type.
You can specify optional size of UROWID
column type.
Date/Time Datatypes
Variable that has date/time data type hold value call datetimes. Oracle SQL
automatically converts character value in to default date format ('DD-MONYY') TO_DATE values. Following are Date/Time data types in Oracle SQL:
Data Type Description

Range
Jan 1, 4712
BC to
Dec 31,
9999 AD

DATE

DATE data type to store valid date-time format


with fixed length. Starting date from Jan 1, 4712
BC to Dec 31, 9999 AD.

TIMESTA

TIMESTAMP data type to store valid date (year, month, day)

with time (hour, minute, second).


Typ
TIMESTAMP Type
e

Syntax : TIMESTAMP [(fractional_seconds_precision)]


Example : TIMESTAMP '2014-04-13 18:10:52.124'
fractional_seconds_precision optionally specifies the
number of digits in the fractional part of
the SECOND datetime field. Range 0 to 9. The default is
6.

Syntax : TIMESTAMP [(fractional_seconds_precision) ]


WITH TIME ZONE
Example : TIMESTAMP '2014-04-13 18:10:52.124
+05:30'
WITH TIME ZONE specify the UTC time zone. Following
two values represent same instant in UTC.
TIMESTAMP '1999-04-15 8:00:00 -8:00' (8.00 AM Pacific
Standard Time) or
TIMESTAMP '1999-04-15 11:00:00 -5:00' (11:00 AM
Eastern Standard Time) both are same.

Syntax : TIMESTAMP [(fractional_seconds_precision) ]


WITH LOCAL TIME ZONE
Example : COL_NAME TIMESTAMP(3) WITH LOCAL TIME
ZONE;
WITH LOCAL TIME ZONE specify when you insert value
into database column, value is store to the database
time zone, and the time-zone displacement is not stored
in the column. When you retrieve value oracle database
returns it in your UTC local time zone.

MP

Example :
CREATE TABLE time_table(
start_time TIMESTAMP,
time1

INTERVAL DAY (6) TO SECOND (5),

time2 INTERVAL YEAR TO MONTH


);

Variable that has interval data type hold value call intervals. Following are
Interval data types in SQL:
Data Type

Description

INTERVAL
YEAR TO
MONTH

INTERVAL YEAR TO MONTH data type to store and


manipulate intervals of year and month.
Syntax : INTERVAL YEAR [ (year_precision) ] TO MONTH
Note : precision specifies number of digits in years field
range from 0 to 9 and default is 2.
Size of datatype 5 bytes fixed.

INTERVAL
DAY TO
SECOND

INTERVAL DAY TO SECOND data type to store and


manipulate intervals of days, hours, minutes, and seconds.
Syntax : INTERVAL DAY[(day_precision)] TO
SECOND[(fractional_seconds_precision)]
Note : day_precision specifies number of digits in days field
range from 0 to 9. The default is 2.
fractional_seconds_precision specifies number of digits in
days field range from 0 to 9. The default is 6.
Size of datatype 11 bytes fixed.

Large Object Datatypes (LOB types)


LOB data types use to store large object such as image, video, graphics, text,
audio. Maximum size up to 4 Gigabytes. following are LOB data types in SQL:
Data
Type

Description

Storage(Maximum
)

BFILE

BFILE data type to store large binary object


into Operating System file. This data type
variable store full file locator's path which
point to a stored binary object with in server.
BFILE data type read only, you can't modify
them.

Size: up to 4GB
(232 - 1 bytes)
Directory name:
30 character
File name: 255
characters

BLOB

BLOB data type same as BFILE data type to


store unstructured binary object into
Operating System file. BLOB type fully
supported transactions are recoverable and
replicated.

Size: 8 TB to 128
TB
(4GB - 1) *
DB_BLOCK_SIZE

CLOB

CLOB data type to store large blocks of


character data into Database. Store single
byte and multi byte character data. CLOB type
fully supported transactions are recoverable
and replicated.

Size: 8 TB to 128
TB
(4GB - 1) *
DB_BLOCK_SIZE

NCLOB data type to store large blocks of


NCHAR data into Database. Store single byte
NCLOB and multi byte character data. NCLOB type
fully supported transactions are recoverable
and replicated.

Size: 8 TB to 128
TB
(4GB - 1) *
DB_BLOCK_SIZE

SQL Syntax is easy and most of the database action you can done using SQL
statement. Following are fewer most frequently useful SQL Query syntax,
1. CREATE DATABASE Syntax
2. DROP DATABASE Syntax
3. CREATE TABLE Syntax
4. DESCRIBE TABLE Column Syntax
5. INSERT Syntax
6. UPDATE Syntax
7. DELETE Syntax
8. SELECT Syntax
9. ALTER TABLE Syntax
10.

DROP TABLE Syntax

11.

COMMIT Syntax

12.

ROLLBACK Syntax

13.

SET LINESIZE Syntax

SQL CREATE DATABASE Syntax


CREATE DATABASE database_name;
Example :
SQL> CREATE DATABASE user_data;

SQL DROP DATABASE Syntax


DROP DATABASE database_name;
Example :
SQL> DROP DATABASE user_data;

SQL CREATE TABLE Syntax


CREATE TABLE [ IF NOT EXISTS ] table_name(
column_name datatype[(size)] [ NULL | NOT NULL ],
column_name datatype[(size)] [ NULL | NOT NULL ],
[ constraint_name
PRIMARY KEY ( col1, col2, ... ) |

FOREIGN KEY ( col1, col2, ... ) REFERENCES table_2 [ ( col1,


col2, ... )
[ ON UPDATE | ON DELETE
[ NO ACTION | SET NULL | SET DEFAULT | CASCADE ]
]
]|
UNIQUE ( col1, col2, ... ) |
CHECK ( expression )
]
...
);
Example :
SQL> CREATE TABLE users_info(
no NUMBER(3) NOT NULL,
name VARCHAR(30),
address VARCHAR(70),
contact_no VARCHAR(12),
PRIMARY KEY (no)
);

SQL DESCRIBE table column Syntax


DESCRIBE table_name;

SQL INSERT Syntax


Insert one row values :
INSERT INTO table_name [ ( column_name1, column_name2, ... ) ]
VALUES ( value1_row1, value2_row1, ... );

Example :
SQL> INSERT INTO users_info (no,name,address)
VALUES (1, 'Opal Kole', '63 street Ct.');

Insert multiple row values :


INSERT ALL
INTO table_name [ (column_name1, column_name2, ...) ] VALUES
(record1_value1, record1_value2, ...)
INTO table_name [ (column_name1, column_name2, ...) ] VALUES
(record2_value1, record2_value2, ...)
INTO table_name [ (column_name1, column_name2, ...) ] VALUES
(record3_value1, record3_value2, ...)
....
SELECT * FROM dual;
Example :
SQL> INSERT ALL
INTO users_info (no, name, address, contact_no) VALUES (4, 'Paul Singh',
'1343 Prospect St', 000-444-7141)
INTO users_info (no, name, address, contact_no) VALUES (5, 'Ken Myer',
'137 Clay Road', 000-444-7084)
INTO users_info (no, name, address, contact_no) VALUES (6, 'Jack Evans',
'1365 Grove Way', 000-444-7957)
INTO users_info (no, name, address, contact_no) VALUES (7, 'Reed Koch',
'1274 West Street', 000-444-4784)
SELECT * FROM dual;

4 rows created.

SQL UPDATE Syntax

UPDATE table_name
SET column_name1 = value1, column_name2 = value2 , ...
[ WHERE condition ]
[ LIMIT number ];
Example :
SQL> UPDATE users_info
SET name = "Beccaa Moss" , address ="2500 green city."
WHERE no = 3;

SQL DELETE Syntax


DELETE FROM table_name
[ WHERE condition ]
[ LIMIT number ];
Example :
SQL> DELETE users_info
WHERE no = 3;

SQL SELECT Syntax


SELECT [ DISTINCT | ALL ]
column_name1, column_name2, aggregate_function(column_name) ....
[ FROM table_name ]
[ WHERE condition ]
[ GROUP BY groupby_column_name1, .... ]
[ HAVING having_clause ]
[ ORDER BY order_column_name1 [ ASC | DESC ], .... ];

Example :
We have to fetch all table columns using asterisk (*),
SQL> SELECT * FROM users_info WHERE no = 3;

SQL ALTER TABLE Syntax


ALTER TABLE table_name RENAME TO new_table_name;
ALTER TABLE table_name ADD column_name datatype[(size)];
ALTER TABLE table_name MODIFY column_name column_datatype[(size)];
ALTER TABLE table_name RENAME COLUMN old_column_name TO
new_column_name;
ALTER TABLE table_name DROP COLUMN column_name;
Example :
Add new column to a 'users_info' table
SQL> ALTER TABLE users_info ADD postalcode VARCHAR2(8);

SQL DROP TABLE Syntax


DROP TABLE [ IF EXISTS ]
table_name1, table_name2, ...;
Example :
SQL> DROP TABLE users_info ;

SQL COMMIT Syntax


SQL> COMMIT;

SQL ROLLBACK Syntax


SQL> ROLLBACK;

SQL SET LINESIZE Syntax


SQL Line Size command is use to set a number of character per row.
SET linesize N;
Example :
SQL> SET linesize 300;

Das könnte Ihnen auch gefallen