What Is SQL? - SQL Introduction
What Is SQL? - SQL Introduction
- SQL Introduction
What is SQL?
SQL stands for Structured Query Language use for storing, manipulating and retrieving relational database data.
SQL queries to retrieve data from database same as you can adding and manipulating database data.
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.
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 Statements
Type of 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).
Statement Description
Statement Description
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 Statements are supported in PL/SQL only for executed dynamically. CALL a PL/SQL program or EXPLAIN
EXPLAIN PLAN PATH access the data path.
Statement Description
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.
Statement Description
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.
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.
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.
Numeric Datatypes
Character Datatypes
LONG and ROW Datatypes
ROWID Datatypes
Datetime Datatypes
Large Object Datatypes
Number Datatypes
Following are numeric data types in SQL.
Datatype Description
INT 38 digits
SMALLINT 38 digits
Character Datatypes
Character Data type use to store alphabetic/alphanumeric, following are character data types in Oracle SQL.
NCHAR [ (size) ] NCHAR data type use to store national character data within predefined length. 2000 bytes
VARCHAR2(size) VARCHAR2 data type use to store variable strings data within predefined length. 4000 bytes
You have to must specify the size of VARCHAR2 datatype.
VARCHAR2 Subtypes: This sub type define same length value.
NVARCHAR2(size) NVARCHAR2 data type use to store Unicode string data within predefined length. 4000 bytes
You have to must specify the size of NVARCHAR2 datatype.
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 type upto 2 gigabytes
use for backward compatibility. Please use CLOB instead of LONG type.
LONG RAW LONG RAW data type same as LONG type use to store variable strings data within upto 2 gigabytes
predefined length, This data type use for backward compatibility. Please use BLOB instead
of LONG RAW type.
ROWID Datatypes
ROWID data type represent actual storage address of a row. Following are ROWID datatypes in Oracle SQL.
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[(size)] UROWID data type identify as universal rowid. Same as ROWID type and use newer 4000 bytes
developing applications use UROWID data 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-MON-YY') TO_DATE values. Following are Date/Time data types in Oracle SQL.
DATE DATE data type to store valid date-time format with fixed length. Starting date from Jan 1, 4712 Jan 1, 4712 BC
BC to Dec 31, 9999 AD. to
Dec 31, 9999
AD
TIMESTAMP TIMESTAMP data type to store valid date (year, month, day) with time (hour, minute, second).
1 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.
Example:
Variable that has interval data type hold value call intervals. Following are Interval data types in SQL.
Datatype Description
INTERVAL YEAR TO INTERVAL YEAR TO MONTH data type to store and manipulate intervals of year and month.
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 INTERVAL DAY TO SECOND data type to store and manipulate intervals of days, hours, minutes,
SECOND 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.
BLOB BLOB data type same as BFILE data type to store unstructured binary object into Operating Size: 8 TB to 128 TB
System file. BLOB type fully supported transactions are recoverable and replicated. (4GB - 1) *
DB_BLOCK_SIZE
CLOB CLOB data type to store large blocks of character data into Database. Store single byte and Size: 8 TB to 128 TB
multi byte character data. CLOB type fully supported transactions are recoverable and (4GB - 1) *
replicated. DB_BLOCK_SIZE
NCLOB NCLOB data type to store large blocks of NCHAR data into Database. Store single byte and Size: 8 TB to 128 TB
multi byte character data. NCLOB type fully supported transactions are recoverable and (4GB - 1) *
replicated. DB_BLOCK_SIZE
SQL Syntax
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,
Example:
SQL> CREATE DATABASE user_data;
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)
);
Example:
SQL> INSERT INTO users_info (no,name,address)
VALUES (1, 'Opal Kole', '63 street Ct.');
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.
Example:
SQL> DELETE users_info
WHERE no = 3;
Example:
Example:
Add new column to a 'users_info' table
SQL> ALTER TABLE users_info ADD postalcode VARCHAR2(8);
Example:
SQL> DROP TABLE users_info ;
Example:
SQL> SET linesize 300;
SQL CREATE Database
SQL CREATE DATABASE statement to create new database. Oracle SQL you have to first create new database. Before
you learn how to create new database you must have to know about SQL structure.
SQL structure is hierarchically, You first create database. Select database for USE. Now you are in selected database
are. you are access all table as well as make new table and so many things you can done.
Syntax
You have to create new database use following SQL CREATE DATABASE syntax,
CREATE DATABASE database_name;
Example
SQL> CREATE DATABASE user_db;
+---------------------+
| Database |
+---------------------+
| information_schema |
| scott |
| user_db |
| demodb |
+---------------------+
4 rows in set (0.01 sec)
Syntax
USE database_name;
Example
SQL> USE user_db;
Database changed
Example
SQL> DROP DATABASE user_db;
+---------------------+
| Database |
+---------------------+
| information_schema |
| scott |
| demodb |
+---------------------+
3 rows in set (0.00 sec)
Following is SQL CREATE TABLE syntax, but now you just learn basic CREATE TABLE syntax. Once you know SQL
CONSTRAINT concept you can learn this syntax.
Syntax
CREATE TABLE [ IF NOT EXISTS ] table_name(
column_name datatype[(size)] [ NULL | NOT NULL ],
column_name datatype[(size)] [ NULL | NOT NULL ],
[ CONSTRAINT 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 )
]
...
);
Basic Syntax:
CREATE TABLE table_name(
column_name1 datatype(size),
column_name2 datatype(size)
...
);
Keep in Mind... : You can not create new table if table already exist in selected database. and another things table name
must have unique within database.
Example
Here we create new table in SQL. 4 columns specify with data type and size.
SQL> CREATE TABLE users_info(
no NUMBER(3,0),
name VARCHAR(30),
address VARCHAR(70),
contact_no VARCHAR(12)
);
Table created.
Syntax
DROP TABLE table_name;
Example
SQL> DROP TABLE users_info;
Table dropped.
Syntax
TRUNCATE TABLE table_name;
Example
SQL> TRUNCATE TABLE users_info;
Table truncated.
Column Name
Column allow NULL or NOT NULL
Datatype of the Column
With database size precision and If NUMERIC datatype scale.
When inserting data into table no need to specify the column names if values is table structure wise (column wise).
Syntax
INSERT INTO table_name VALUES (value1, value2, value3, ...);
Example
SQL> INSERT INTO users_info VALUES (1, 'Opal Kole', '63 street Ct.', '000-444-7847');
1 row created.
When you inserting data into table and you haven't know table structure you must specify the column name.
Syntax
INSERT INTO table_name [ (column_name1, column_name2, ...) ]
VALUES (value1, value2, ...);
Example
SQL> INSERT INTO users_info (name, address, no, contact_no)
VALUES ('Beccaa Moss', '2500 green city.', 3, '000-444-7142');
1 row created.
We can insert more then one record in single SQL INSERT statement.
Syntax
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.
1 row created.
SQL> /
Enter value for no: 9
Enter value for name: 'Ben Mares'
Enter value for address: '101 Candy Road'
Enter value for contact_no: '000-444-5484'
old 1: INSERT INTO users_info VALUES (&no, &name, &address, &contact_no)
new 1: INSERT INTO users_info VALUES (9, 'Ben Mares', '101 Candy Road', '000-444-5484')
1 row created.
SQL>
SQL Insert Data only in specified COLUMNS
You can insert data only specific column. When you write INSERT statement you have to specify column name to
inserting only that column data into table.
Syntax
INSERT INTO Table_Name (specific_column_name1, ...)
VALUES (value1,...);
Example
SQL> INSERT INTO users_info(no, name) VALUES (10, 'Sariya Vargas');
1 row created.
Syntax
INSERT INTO new_table_name [(column_name1,column_name2,...)]
SELECT column_name1, column_name1 ... FROM
another_table_name
[WHERE condition];
Example
SQL> CREATE TABLE demo_tbl(
no NUMBER(3),
name VARCHAR2(50)
);
Table created.
10 rows created.
SQL UPDATE
SQL UPDATE statement to update table records with in database. You can update all table row or update data only
matching conditionally WHERE clause.
10 rows updated.
10 rows selected.
UPDATE Conditionally use WHERE Clause
UPDATE table data only where WHERE Clause condition match. Use can optionally use LIMIT number to update only
limited record starting from first.
Syntax
UPDATE table_name
SET column_name1 = value1, column_name2 = value2, ...
[ WHERE condition ]
[ LIMIT number];
Example
SQL> UPDATE demo1 SET ADDRESS = '10 Texo Court.' WHERE NO = 10;
1 row updated.
10 rows selected.
SQL DELETE
SQL DELETE Statement is used to delete one or more then one row removed from table.
1 row deleted.
9 rows selected.
Remove all TABLE rows
Remove the all table row use this simple delete statement to delete all table data. after execute delete statement SELECT
statement to check table is empty or not.
Syntax
DELETE FROM table_name;
Example
SQL> DELETE FROM demo1;
9 rows deleted.
no rows selected.
SQL SELECT
SQL SELECT statement is used to viewing data from the table. This statement return list of table format table data.
We use asterisk (*) sign to fetch all table columns instead of write all column name.
Example
SQL> SELECT * FROM users_info;
Example
SQL> SELECT no, name, address FROM users_info;
NO NAME ADDRESS
--- --------------------- --------------------------------
1 Opal Kole 63 street Ct.
2 Max Miller 41 NEW ROAD.
3 Beccaa Moss 2500 green city.
4 Paul Singh 1343 Prospect St
5 Ken Myer 137 Clay Road
6 Jack Evans 1365 Grove Way
7 Reed Koch 1274 West Street
8 Gabe Hee 1220 Dallas Drive
9 Ben Mares 101 Candy Road
10 Sariya Vargas 10 Texo Court.
10 rows selected.
Example
SQL> SELECT * FROM users_info WHERE no = 3;
Example
SQL> SELECT no, name, address FROM users_info WHERE no = 3;
NO NAME ADDRESS
--- --------------------- -------------------------------
3 Beccaa Moss 2500 green city.
In this example line number 7 or 13 row are same so two of one row automatically eliminate.
Syntax
SELECT DISTINCT * FROM table_name;
Example
SQL> SELECT * FROM userinfo;
NO NAME ADDRESS
---- ----------------------------- ---------------------------
1 Opal Kole 63 street Ct.
2 Max Miller 41 NEW ROAD.
3 Beccaa Moss 2500 green city.
4 Paul Singh 1343 Prospect St
5 Ken Myer 137 Clay Road
6 Jack Evans 1365 Grove Way
7 Opal Kole 63 street Ct.
8 Max Miller 41 NEW ROAD.
3 Beccaa Moss 2500 green city.
9 rows selected.
NO NAME ADDRESS
---- ----------------------------- ---------------------------
3 Beccaa Moss 2500 green city.
6 Jack Evans 1365 Grove Way
1 Opal Kole 63 street Ct.
2 Max Miller 41 NEW ROAD.
5 Ken Myer 137 Clay Road
8 Max Miller 41 NEW ROAD.
4 Paul Singh 1343 Prospect St
7 Opal Kole 63 street Ct.
8 rows selected.
In this example line number 5,6 or 11,12 name and address column value are same so this both row automatically
eliminate.
Syntax
SELECT DISTINCT column_name1, column_name2, ... FROM table_name;
Example
SQL> SELECT * FROM userinfo;
NO NAME ADDRESS
---- ----------------------------- ---------------------------
1 Opal Kole 63 street Ct.
2 Max Miller 41 NEW ROAD.
3 Beccaa Moss 2500 green city.
4 Paul Singh 1343 Prospect St
5 Ken Myer 137 Clay Road
6 Jack Evans 1365 Grove Way
7 Opal Kole 63 street Ct.
8 Max Miller 41 NEW ROAD.
3 Beccaa Moss 2500 green city.
9 rows selected.
NAME ADDRESS
---------------------------------- ---------------------------
Opal Kole 63 street Ct.
Paul Singh 1343 Prospect St
Ken Myer 137 Clay Road
Beccaa Moss 2500 green city.
Max Miller 41 NEW ROAD.
Jack Evans 1365 Grove Way
6 rows selected.
Syntax
SELECT DISTINCT column_name1, column_name2, ... FROM table_name;
Example
SQL> SELECT * FROM userinfo;
NO NAME ADDRESS
---- ----------------------------- ---------------------------
1 Opal Kole 63 street Ct.
2 Max Miller 41 NEW ROAD.
3 Beccaa Moss 2500 green city.
4 Paul Singh 1343 Prospect St
5 Ken Myer 137 Clay Road
6 Jack Evans 1365 Grove Way
7 Opal Kole 63 street Ct.
8 Max Miller 41 NEW ROAD.
3 Beccaa Moss 2500 green city.
9 rows selected.
NAME
----------------------------------
Opal Kole
Max Miller
Beccaa Moss
Paul Singh
Jack Evans
Ken Myer
6 rows selected.
SQL ALTER TABLE
SQL ALTER TABLE Statement to rename table name, add new column, modify existing column (data type, size, etc.),
rename the column, drop the table column.
SQL ALTER TABLE statement is a powerful statement to add, manage or update table structure.
Syntax
ALTER TABLE table_name
RENAME TO new_table_name;
Example
SQL> ALTER TABLE userinfo RENAME TO user_info;
Table altered.
SQL ADD NEW COLUMN IN TABLE
You can add new column in table using this syntax,
Syntax
ALTER TABLE table_name
ADD column_name datatype[(size)];
Example
SQL> ALTER TABLE user_info ADD state VARCHAR2(12);
Table altered.
Syntax
ALTER TABLE table_name
ADD ( column_name1 datatype[(size)],
column_name2 datatype[(size)],
...
);
Example
SQL> ALTER TABLE user_info
ADD (city VARCHAR2(30),
country VARCHAR2(30)
);
Table altered.
Syntax
ALTER TABLE table_name
MODIFY column_name column_datatype[(size)];
Example
In this example DESC table structure before execute ALTER statement. ALTER Statement to MODIFY the column size.
After alter table again DESC table structure.
SQL> DESC user_info;
Name Null? Type
------------------------ -------- ---------------------
NO NUMBER(3)
NAME VARCHAR2(50)
ADDRESS VARCHAR2(70)
STATE VARCHAR2(12)
Table altered.
Same way you can modify multiple existing column in table using following syntax,
Syntax
ALTER TABLE table_name
MODIFY (column_name1 column_datatype[(size)],
column_name2 column_datatype[(size)],
...
);
Syntax
ALTER TABLE table_name
RENAME COLUMN old_column_name TO new_column_name;
Example
SQL> ALTER TABLE user_info
RENAME COLUMN no TO sno;
Table altered.
Syntax
ALTER TABLE table_name
DROP COLUMN column_name;
Example
This example line 8 country column drop using alter table statement.
SQL> DESC user_info;
Name Null? Type
------------------------------ -------- --------------------------
SNO NUMBER(3)
NAME VARCHAR2(50)
ADDRESS VARCHAR2(70)
STATE VARCHAR2(10)
COUNTRY VARCHAR2(30)
Table altered.
SQL WHERE clause we can use with SELECT, UPDATE, DELETE statements. SELECT statement with WHERE clause
execute, fetching all table rows and apply WHERE clause filtering and finally return the result data.
Notes: You can't use INSERT statement with WHERE clause. But you can use INSERT Statement with WHERE cause
only when you get the filter data from another TABLE.
Syntax
SELECT * FROM table_name WHERE condition;
Example
SQL> SELECT * FROM users_info WHERE name = 'Opal Kole';
Syntax
Example
SQL> UPDATE users_info SET address = '145 Taxo court.' WHERE no = 10;
1 row updated.
Syntax
DELTE FROM table_name WHERE condition;
Example
SQL> DELETE FROM users_info WHERE no = 10;
1 row deleted.
Syntax
INSERT INTO table_name (column_name1, column_name2, ...)
SELECT column_name1, column_name2, ...
FROM another_table_name
WHERE condition;
Example
SQL> INSERT INTO userinfo (no, name, address)
SELECT no, name, address
FROM users_info
WHERE no = 1;
1 row inserted.
WHERE clause Operators
You can use WHERE clause with following operators.
= Equal to
SQL> SELECT * FROM users_info WHERE no = 5;
9 rows selected.
6 rows selected.
2 rows selected.
IN Allows only specified
SQL> SELECT * FROM users_info WHERE no IN (1,5,10);
values
3 rows selected.
5 rows selected.
SQL AND and OR Operators
SQL AND and OR operators use for filter the records based on more than one condition.
SQL AND condition use to test more then one conditions in INSERT, UPDATE, DELETE, SELECT statement. AND
operator work is test first condition if true come to a second and so forth, otherwise not check next condition.
SQL AND Operator filter the record based table data. INSERT, UPDATE, DELETE, SELECT statement perform only
when all specified condition TRUE.
Syntax
Considering following general syntax,
WHERE condition_1
AND condition_2
AND condition_3
...
AND condtion_N;
Example
SELECT Statement: Select table data only condition matched data,
SQL> SELECT * FROM users_info WHERE name = 'Max Miller' AND no = 2;
INSERT Statement: AND operator use in INSERT statement, INSERT only condition matched data,
SQL> INSERT INTO userinfo (no, name, address)
SELECT no, name, address FROM users_info WHERE no = 1 AND name = 'Opal Kole';
1 row inserted.
UPDATE Statement: AND operator use in UPDATE statement, Update only condition matched rows,
SQL> UPDATE users_info SET address = '145 Taxo court.' WHERE no = 10 AND name = 'Sariya Vargas';
1 row updated.
DELETE Statement: AND operator use in DELETE statement, DELETE only condition matched rows but in this example
no is find but name 'Sariya' not exist in table so 0 row deleted.
SQL> DELETE FROM users_info WHERE no = 10 AND name = 'Sariya';
0 row deleted.
SQL OR Condition Statement
SQL OR Condition use to test more then one conditions in INSERT, UPDATE, DELETE, SELECT statement. OR operator
test all condition even if condition TRUE or FALSE. And return data when any one of the condition TRUE.
SQL OR Operator same as AND operator, return the record base filtered data. INSERT, UPDATE, DELETE, SELECT
statement perform only one of the specified condition TRUE.
Syntax
Considering following general syntax,
WHERE condition_1
OR condition_2
OR condition_3
...
OR condtion_N;
Example
SELECT Statement: Select table data if any one of the condition true. In this example select all table data, whose name
'Max Miller' and no is 3. Both are different condition and found in table so return both satisfied condition data.
SQL> SELECT * FROM users_info WHERE name = 'Max Miller' OR no = 3;
INSERT Statement: OR operator use in INSERT statement, INSERT when any one of the condition TRUE, In this example
new record inserted from another table only those rows whose no column value is 1 OR name value 'Max Miller'.
SQL> INSERT INTO userinfo (no, name, address)
SELECT no, name, address FROM users_info WHERE no = 1 OR name = 'Max Miller';
2 row inserted.
UPDATE Statement: OR operator use in UPDATE statement, Update when any one if the condition TRUE, In this example
address update only those rows whose no column value is 10 OR name value 'Sariya'.
SQL> UPDATE users_info SET address = '145 Taxo court.' WHERE no = 10 OR name = 'Sariya';
1 row updated.
DELETE Statement: AND operator use in DELETE statement, DELETE only condition matched rows but in this example
no is find but name 'Sariya' not exist in table so 0 row deleted.
SQL> DELETE FROM users_info WHERE no = 10 AND name = 'Sariya';
0 row deleted.
SQL Between operator support only range type value like number, dates, character. But not supporting boolean, string
value range.
Syntax
When SQL query with BETWEEN clause parse into SQL Buffer, it will automatically expand out into separate comparison
clauses.
SELECT * FROM table_name
WHERE column_name <= lower_bound_value
AND column_name >= upper_bound_value;
Example
In this example select all users_info table rows with range between no column value 1 to 5.
SQL> SELECT * FROM users_info WHERE no BETWEEN 1 AND 5;
5 rows selected.
5 rows selected.
SQL IN condition allow only specific value in INSERT, UPDATE, DELETE, SELECT statement.
Syntax
WHERE column_name IN (value1, value2, ...);
Example
SQL> SELECT * FROM users_info WHERE no IN (1,5,10);
3 rows selected.
Syntax
NOT IN condition use with WHERE clause to exclude defined multiple values from record data.
WHERE column_name NOT IN (value1, value2, ...);
5 rows selected.
Our users_info table we have to select all rows with add condition exclude no column range from 6 to 10.
SQL> SELECT * FROM users_info WHERE no NOT BETWEEN 6 AND 10;
5 rows selected.
In our users_info table not select whose name column starting with 'Be' character.
SQL> SELECT * FROM users_info WHERE name NOT LIKE 'Be%';
8 rows selected.
Following two wildcards are often used with the LIKE operator
Syntax
Pattern write inside opening or closing single delimit characters (''). Do not use double delimit characters ("") because
double delimit use as delimiter identifier.
...WHERE column_name LIKE 'pattern'; -- Correct way
...WHERE column_name LIKE "pattern"; -- Incorrect way
SQL Wildcards Characters
SQL Wildcards characters used for searching string pattern. SQL Wildcard character use with LIKE condition for
searching pattern string from database table.
Wildcard Description
10 rows selected.
SQL LIKE condition with _ (underscore) WILDCARD character to matches any exactly single character with in string.
SQL> SELECT * FROM users_info WHERE name LIKE 'Pa_l S__gh';
SQL LIKE condition with % (percentage) WILDCARD character to matches any number of characters.
SQL> SELECT * FROM users_info WHERE name LIKE 'Paul%';
1 rows selected.
SQL LIKE (_ WILDCARD character) with NOT condition to return all record only exclude pattern result.
SQL> SELECT * FROM users_info WHERE name NOT LIKE 'Pa_l S__gh';
9 rows selected.
SQL LIKE (% WILDCARD character) with NOT condition to return all record only exclude pattern result.
SQL> SELECT * FROM users_info WHERE name NOT LIKE 'Paul%';
9 rows selected.
SQL Constraints
What is SQL constraints? SQL 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.
We can create/define constraints on single or multiple columns of any table. It maintain the data integrity of the table.
SQL Constraints are help us to enter limited fixed size data. For example postal code India country size six digit no below
or no more then six digit.
Type of Data constraints
Input/Output constraints: This constraints determines the speed of which data are inserted or extracted from database table.
For example Primary key, Foreign key constraints.
Business Rule constraints: This rules are applied to data prior(first) the data being inserted into the table columns. For
example Unique, Not NULL, Default constraints.
Define Constraints
Oracle SQL allows programmers to define constraints at:
Column level
Table level
Column level constraints: Column level constraint define on column level (single column) along with other column
attributes.
Syntax
...
column_name datatype[(size)] [ NULL | NOT NULL ] [constraint_name],
....
Table level constraints: Table level constraint defining after the all table columns define.
Syntax
...
column_name datatype[(size)] [ NULL | NOT NULL ],
column_name datatype[(size)] [ NULL | NOT NULL ],
[ CONSTRAINT 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 )
],
...
ADD CONSTRAINT (ALTER TABLE)
Yes you can add constraint in existing table. But in this way when you adding new constraint, oracle check any existing
data violate the constraint rules or not. If not violate constraint added successfully otherwise you have to manually update
data to prevent constraint violating.
Syntax
ALTER TABLE table_name
ADD CONSTRAINT_NAME (column_name);
Syntax:
ALTER TABLE table_name
DROP constraint_name column_name;
SQL Primary Key constraint has been specified for certain column. we can not enter duplicate data in this column.
Syntax
CREATE TABLE table_name(
column_name datatype[(size)] [ NULL | NOT NULL ] PRIMARY KEY,
column_name datatype[(size)] [ NULL | NOT NULL ] PRIMARY KEY,
....
);
Example
SQL> CREATE TABLE emp_info(
no NUMBER(3,0) PRIMARY KEY,
name VARCHAR(30),
address VARCHAR(70),
contact_no VARCHAR(12)
);
Table created.
Defined at Table level
Same thing primary key apply in table level. Table level you can define multiple column separated by comma (,).
Syntax
CREATE TABLE table_name(
column_name datatype[(size)] [ NULL | NOT NULL ],
column_name datatype[(size)] [ NULL | NOT NULL ],
...,
PRIMARY KEY ( column_name, ... ),
...
);
Example
SQL> CREATE TABLE emp_info(
no NUMBER(3,0),
name VARCHAR(30),
address VARCHAR(70),
contact_no VARCHAR(12),
PRIMARY KEY(no)
);
Table created.
You can also specifies CONSTRAINT keyword to specify the constraint name.
Syntax
CREATE TABLE table_name(
column_name datatype[(size)] [ NULL | NOT NULL ],
column_name datatype[(size)] [ NULL | NOT NULL ],
...,
CONSTRAINT pk_constraint_name PRIMARY KEY ( column_name, ... ),
...
);
Example
SQL> CREATE TABLE emp_info(
no NUMBER(3,0),
name VARCHAR(30),
address VARCHAR(70),
contact_no VARCHAR(12),
CONSTRAINT pk_no PRIMARY KEY(no)
);
Table created.
ADD PRIMARY KEY (ALTER TABLE)
ALTER TABLE statement to add primary key in existing table. But in this way when you adding new constraint, oracle
check any existing data violate the primary key constraint or not. If not violate constraint added successfully otherwise you
have to manually update data to prevent primary key constraint violating.
Syntax
ALTER TABLE table_name
ADD PRIMARY KEY (column_name, ...);
Example
SQL> ALTER TABLE emp_info ADD PRIMARY KEY (no);
Table altered.
Syntax
ALTER TABLE table_name
DROP PRIMARY KEY;
Example
SQL> ALTER TABLE emp_info DROP PRIMARY KEY;
Table altered.
In above SQL statement you should notice for dropping PRIMARY KEY constraint in all primary key column(s). You can
not drop individual column. It's this possible in following way, You should specify the constraint name and ALTER TABLE
statement you can drop constraint name.
Example
SQL> CREATE TABLE emp_info(
no NUMBER(3,0),
name VARCHAR(30),
address VARCHAR(70),
contact_no VARCHAR(12),
CONSTRAINT pk_no PRIMARY KEY(no)
);
Table created.
Table altered.
SQL FOREIGN KEY Constraint
SQL FOREIGN KEY Constraint apply on column(s) for whose value must have reference in another table column (that
existing column must be primary key or unique key constraint).
SQL FOREIGN KEY constraints reference in another table within the same database. Using PL/SQL Trigger you can
implement to cross database referencing.
FOREIGN KEY constraint applied column must have same data type as the reference on another table column.
Value must have exist in parent column (referenced another table column).
Value may be store in NULL.
Define on Column level
A FOREIGN KEY constraint specify at column level.
Syntax
CREATE TABLE table_name(
column_name datatype[(size)] [ NULL | NOT NULL ] REFERENCES another_table_name(column_name)
[ ON UPDATE | ON DELETE
[ NO ACTION | SET NULL | SET DEFAULT | CASCADE ]
],
....
);
Example
SQL> CREATE TABLE emp_info(
no NUMBER(3,0) PRIMARY KEY,
name VARCHAR(30),
address VARCHAR(70),
contact_no NUMBER(12,0)
);
Table created.
Table created.
Run it... »
Syntax
CREATE TABLE table_name(
column_name datatype[(size)] [ NULL | NOT NULL ],
column_name datatype[(size)] [ NULL | NOT NULL ],
...,
CONSTRAINT fk_constraint_name
FOREIGN KEY (column_name) REFERENCES another_table_name(column_name)
[ ON UPDATE | ON DELETE
[ NO ACTION | SET NULL | SET DEFAULT | CASCADE ]
],
...
);
Example
SQL> CREATE TABLE emp_info(
no NUMBER(3,0) PRIMARY KEY,
name VARCHAR(30),
address VARCHAR(70),
contact_no NUMBER(12,0)
);
Table created.
Table created.
Composite FOREIGN KEY Constraint
Composite FOREIGN KEY constraint specified one or more columns reference in another table columns separated by
comma (,).
Syntax
REFERENCES another_table_name(column_name1, column_name2)
Syntax
ALTER TABLE table_name
ADD FOREIGN KEY (column_name, ...) REFERENCES another_table_name(column_name, ...);
Example
SQL> ALTER TABLE emp_salary ADD FOREIGN KEY (users_no) REFERENCES emp_info(no);
Table altered.
DROP FOREIGN KEY (ALTER TABLE)
ALTER TABLE statement to drop foreign key in existing table.
Syntax
ALTER TABLE table_name
DROP CONSTRAINT fk_constraint_name;
Example
SQL> ALTER TABLE emp_salary DROP CONSTRAINT fk_userno;
Table altered.
SQL NOT NULL Constraint applied only at column level. You should manually define NOT NULL constraint because table
column set NULL value.
SQL NOT NULL Constraint Rules
A NULL values is different from a blank or zero.
A NULL value can be inserted into the columns of any Datatype.
Syntax
CREATE TABLE table_name(
column_name datatype[(size)] NOT NULL,
column_name datatype[(size)] NOT NULL,
....
);
Example
SQL> CREATE TABLE emp_info(
no NUMBER(3,0) PRIMARY KEY,
name VARCHAR(30) NOT NULL,
address VARCHAR(70)
);
Table created.
Syntax
ALTER TABLE table_name
MODIFY column_name datatype[(size)] NOT NULL;
Example
SQL> ALTER TABLE emp_info MODIFY address VARCHAR2(70) NOT NULL;
Table altered.
Syntax
ALTER TABLE table_name
MODIFY column_name datatype[(size)] NULL;
Example
SQL> ALTER TABLE emp_info MODIFY address VARCHAR2(70) NULL;
Table altered.
Primary key characteristics automatic include UNIQUE key constraint that can not store duplicated by any other row.
Syntax
CREATE TABLE table_name(
column_name datatype[(size)] [ NULL | NOT NULL ] UNIQUE,
column_name datatype[(size)] [ NULL | NOT NULL ] UNIQUE,
....
);
Example Statement
SQL> CREATE TABLE stu_info(
no NUMBER(3,0) PRIMARY KEY,
name VARCHAR(30) UNIQUE,
address VARCHAR(70),
contact_no VARCHAR(12)
);
Table created.
Defined at Table level
Unique key apply in table level. Table level you can define multiple column separated by comma (,).
Syntax
CREATE TABLE table_name(
column_name datatype[(size)] [ NULL | NOT NULL ],
column_name datatype[(size)] [ NULL | NOT NULL ],
...,
UNIQUE ( column_name, ... ),
...
);
Example
SQL> CREATE TABLE stu_info(
no NUMBER(3,0) PRIMARY KEY,
name VARCHAR(30),
address VARCHAR(70),
contact_no VARCHAR(12),
UNIQUE(name)
);
Table created.
You can also specifies CONSTRAINT keyword to specify the constraint name.
Syntax
CREATE TABLE table_name(
column_name datatype[(size)] [ NULL | NOT NULL ],
column_name datatype[(size)] [ NULL | NOT NULL ],
...,
CONSTRAINT uk_constraint_name UNIQUE ( column_name, ... ),
...
);
Example
SQL> CREATE TABLE stu_info1(
no NUMBER(3,0) PRIMARY KEY,
name VARCHAR(30),
address VARCHAR(70),
contact_no VARCHAR(12),
CONSTRAINT uk_name UNIQUE(name)
);
Table created.
Now we are inserting record into this table to check unique key how to work for example try to insert same name as soon
as fire error for unique constraint violated.
SQL> INSERT INTO stu_info(no,name) VALUES(1,'Opal');
1 row created.
Syntax
ALTER TABLE table_name
ADD CONSTRAINT uk_constraint_name UNIQUE (column_name, ...);
Example
SQL> ALTER TABLE stu_info1 ADD CONSTRAINT uk_name UNIQUE(name);
Table altered.
Syntax
ALTER TABLE table_name
DROP CONSTRAINT uk_constraint_name;
Example
SQL> ALTER TABLE stu_info1 DROP CONSTRAINT uk_name;
Table altered.
SQL CHECK Constraint must be specified as a logical expression that evaluated specific condition either TRUE or
FALSE.
SQL CHECK constraint define at column level that allow only specified values for a column and Whereas define at table
level that allow specified values as well as use other column value for checking specific condition.
Syntax
CREATE TABLE table_name(
column_name datatype[(size)] [ NULL | NOT NULL ] CHECK (column_name condition),
column_name datatype[(size)] [ NULL | NOT NULL ] CHECK (column_name condition),
....
);
Example
SQL> CREATE TABLE student_info(
no NUMBER(3) PRIMARY KEY,
stu_code VARCHAR(10) CHECK (stu_code like 'j%'),
name VARCHAR(30) CHECK ( name = upper(name) ),
city VARCHAR(30) CHECK (city IN ('Houston','San Antonio','Boston','Miami'))
scholarship NUMBER(5) CHECK (scholarship BETWEEN 5000 AND 20000)
);
Table created.
SQL> INSERT INTO student_info VALUES (1,'j001', 'JAMES KENON', 'Miami', 8900);
1 row created.
Values inserted into stu_code column must be start with the lower letter 'j'.
Values inserted into name column must be capitalize.
Values inserted into city column only allow 'Houston','San Antonio','Boston','Miami' as valid legitimate values.
Values inserted into scholarship column between 5000 and 20000.
CHECK CONSTRAINT defined at Table level
CHECK constraint apply in table level. Table level you must specified separately.
Syntax
CREATE TABLE table_name(
column_name datatype[(size)] [ NULL | NOT NULL ],
column_name datatype[(size)] [ NULL | NOT NULL ],
...,
CHECK ( column_name condition),
CHECK ( column_name condition),
...
);
Example
SQL> CREATE TABLE student_info(
no NUMBER(3) PRIMARY KEY,
stu_code VARCHAR(10),
name VARCHAR(30),
city VARCHAR(30),
scholarship NUMBER(5),
CHECK (stu_code like 'j%'),
CHECK (name = upper(name)),
CHECK (city IN ('Houston','San Antonio','Boston','Miami')),
CHECK (scholarship BETWEEN 5000 AND 20000)
);
Table created.
1 row created.
You can also specifies CONSTRAINT keyword to specify the constraint name. Specifies constraint name is recommended
way for creating table with CHECK constraint.
Syntax
CREATE TABLE table_name(
column_name datatype[(size)] [ NULL | NOT NULL ],
column_name datatype[(size)] [ NULL | NOT NULL ],
...,
CONSTRAINT check_constraint_name CHECK ( column_name condition),
CONSTRAINT check_constraint_name CHECK ( column_name condition),
...
);
Example
SQL> CREATE TABLE student_info(
no NUMBER(3) PRIMARY KEY,
stu_code VARCHAR(10),
name VARCHAR(30),
city VARCHAR(30),
scholarship NUMBER(5),
CONSTRAINT check_stucode CHECK (stu_code like 'j%'),
CONSTRAINT check_name CHECK (name = upper(name)),
CONSTRAINT check_city CHECK (city IN ('Houston','San Antonio','Boston','Miami')),
CONSTRAINT check_scholarship CHECK (scholarship BETWEEN 5000 AND 20000)
);
Table created.
Syntax
ALTER TABLE table_name
ADD CONSTRAINT check_constraint_name CHECK (column_name condition);
Example
SQL> ALTER TABLE student_info ADD CONSTRAINT check_name CHECK (name = upper(name));
Table altered.
Syntax
ALTER TABLE table_name
DROP CONSTRAINT check_constraint_name;
Example
SQL> ALTER TABLE student_info DROP CONSTRAINT check_name;
Table altered.
Syntax
CREATE TABLE table_name(
column_name datatype[(size)] [ NULL | NOT NULL ] DEFAULT default_value,
column_name datatype[(size)] [ NULL | NOT NULL ] DEFAULT default_value,
....
);
Example
SQL> CREATE TABLE stu_info(
no NUMBER(3,0) PRIMARY KEY,
name VARCHAR(30) NOT NULL,
std VARCHAR(18) DEFAULT 'M.Sc.(CS)',
fees_pay NUMBER(5) DEFAULT 2000
);
Table created.
ADD DEFAULT constraint (ALTER TABLE)
ALTER TABLE statement to add DEFAULT constraint in existing table column.
Syntax
ALTER TABLE table_name
MODIFY column_name datatype[(size)] [ NOT NULL ] DEFAULT default_value;
Example
SQL> ALTER TABLE stu_info MODIFY std VARCHAR(18) DEFAULT 'M.Sc.(CS)';
Table altered.
Syntax
ALTER TABLE table_name
MODIFY column_name datatype[(size)];
Example
SQL> ALTER TABLE emp_info MODIFY std VARCHAR2(18);
Table altered.
Above statement execute on oracle SQL that return to table altered but still default value assigned if not specify any
specific value.
SQL GROUP BY
SQL GROUP BY clause use with SELECT statement for fetching data (result groups) according to a matching values for
one or more columns.
SELECT statement fetching all of the rows together that have specific data in specific columns for applying GROUP BY
clause on one or more columns.
Syntax
SELECT
column_name1, column_name2, aggregate_function(column_name), ....
FROM table_name
[ WHERE condition ]
GROUP BY column_name1, ...;
Example
12 rows selected.
Run it... »
Example
SQL> SELECT name
FROM employee_hour
GROUP BY name;
NAME
--------------------
Opal Kole
Beccaa Moss
Paul Singh
Max Miller
Run it... »
GROUP By clause apply only single column that return group of employee name.
Example
SQL> SELECT name,SUM(hours)
FROM employee_hour
GROUP BY name;
NAME SUM(HOURS)
-------------------- ----------
Opal Kole 24
Beccaa Moss 29
Paul Singh 29
Max Miller 23
Run it... »
GROUP By clause apply on name column with use SUM aggregate function to summation the total working hours.
Example
SQL> SELECT name,AVG(hours)
FROM employee_hour
GROUP BY name;
NAME AVG(HOURS)
-------------------- ----------
Opal Kole 8
Beccaa Moss 9.66666667
Paul Singh 9.66666667
Max Miller 7.66666667
Run it... »
GROUP By clause apply on name column with use AVG aggregate function to average the total working hours divide by
number of day.
SQL HAVING Clause use with GROUP BY clause. without GROUP BY clause you can't use HAVING clause.
Syntax
Example
12 rows selected.
Run it... »
Example
SQL> SELECT name,SUM(hours)
FROM employee_hour
GROUP BY name
HAVING SUM(hours) > 25;
NAME SUM(HOURS)
-------------------- ----------
Beccaa Moss 29
Paul Singh 29
Run it... »
GROUP By clause apply on name column with use SUM aggregate function to summation the total working hours. Also
with HAVING clause condition allow only sum of hours grater than 25.
Example
SQL> SELECT name,AVG(hours)
FROM employee_hour
GROUP BY name
HAVING AVG(hours) > 8;
NAME AVG(HOURS)
-------------------- ----------
Beccaa Moss 9.66666667
Paul Singh 9.66666667
Run it... »
GROUP By clause apply on name column with use AVG aggregate function to average the total working hours divide by
number of day. Also with HAVING clause condition allow only avg of hours grater than 8.
SQL ORDER BY
SQL ORDER BY Clause used to sorting SQL result set either ascending or descending order.
SQL ORDER BY Clause default record set sorting ascending order. Using DESC keyword to result set sorting in
descending order.
Syntax
Example
12 rows selected.
Run it... »
Example
SQL> SELECT *
FROM employee_hour
ORDER BY hours;
12 rows selected.
Run it... »
ORDER BY clause apply on hours column, result set return into ascending order.
Example
SQL> SELECT *
FROM employee_hour
ORDER BY hours DESC;
12 rows selected.
Run it... »
Same thing as above but ORDER BY clause apply on hours column, result set return into descending order.
SQL TOP clause use always with SELECT statement. When you SELECT statement to select records, but you need only
first 3 records you just use TOP clause to return only first 3 records.
Syntax
Example Table
12 rows selected.
Run it... »
Example
SQL> SELECT TOP 3 *
FROM employee_hour
ORDER BY hours DESC;
3 rows selected.
I'm not sure this is working or not but I was finding TOP clause work on Oracle 8i, 9i. And now TOP clause replace with
ROWNUM clause to fetch number of rows.
Example Statement :
SQL> SELECT *
FROM employee_hour
WHERE ROWNUM <= 3;
Run it... »
Example
SQL> SELECT *
FROM ( SELECT * FROM employee_hour ORDER BY hours DESC)
WHERE ROWNUM <= 3;
Run it... »
ROWNUM clause use with sub query to fetching record hours descending order and filter top 3 records.
SQL Alias
SQL Alias are the temporary names given to table or column for the purpose of a specific SQL query.
SQL Alias name specifies to make table or column name are more readable. Alias assigning is optional not a compulsory.
You can temporary assign another name to a table or a column name for a duration of SELECT query using as alias
name.
When you joining one or more table that time assign alias name of a table or a column name to make easier to read.
Syntax
Look this syntax column_name AS alias_column_name and table_name alias_table_name no need AS keyword.
Considering following syntax that help you to understanding Alias,
SELECT
column_name [AS alias_column_name], aggregate_function(column_name) [AS alias_name], ...
FROM table_name [ alias_table_name ];
Example Table
12 rows selected.
Example
SQL> SELECT
name AS Employee_Name, SUM(hours) AS Total_Hours
FROM employee_hour emp_hours
GROUP BY name;
EMPLOYEE_NAME TOTAL_HOURS
-------------------- -----------
Opal Kole 24
Beccaa Moss 29
Paul Singh 29
Max Miller 23
SQL COMMIT
SQL COMMIT command save new changes store into database.
Syntax
COMMIT;
Example
SQL> COMMIT;
Commit complete.
SQL SAVEPOINT
SQL SAVEPOINT command create new save point. SAVEPOINT command save the current point with the unique name
in the processing of a transaction.
Syntax
SAVEPOINT savepoint_name;
Example
SQL> CREATE TABLE emp_data (
no NUMBER(3),
name VARCHAR(50),
code VARCHAR(12)
);
Table created.
Savepoint created.
1 row created.
Savepoint created.
1 row created.
SQL> SAVEPOINT insert_2;
Savepoint created.
NO NAME CODE
---------- ------------------------------------------ ------------
1 Opal e1401
2 Becca e1402
SQL ROLLBACK
SQL ROLLBACK command execute at the end of current transaction and undo/undone any changes made since the
begin transaction.
Syntax
ROLLBACK [To SAVEPOINT_NAME];
Example
Above example we are create 3 SAVEPOINT table_create, insert_1 and insert_2. Now we are rollback to insert_1
SAVEPOINT.
SQL> ROLLBACK TO insert_1;
Rollback complete.
NO NAME CODE
---------- ------------------------------------------ ------------
1 Opal e1401
SQL TRUNCATE command is faster and use some transaction log resources.
SQL TRUNCATE command logically equivalent to a DELETE command that deletes all rows, but they are practically
different under some rules.
SQL TRUNCATE command Rules
TRUNCATE operation use for dropping or re-create table, which is much faster than deleting rows one by one.
TRUNCATE operation not rollback, It means truncated can not be returned.
TRUNCATE operation is not a safe.
Syntax
Example
SQL> TRUNCATE TABLE emp_data;
Table Truncated.
1 If we want to delete all the records from the table, then our Whereas Truncate command is used to delete all records from
SQL query is: the table. Our SQL query is:
SQL> TRUNCATE TABLE table_name;
SQL> DELETE FROM table_name;
2 DELETE statement with WHERE clause you can remove Whereas TRUNCATE statement use for remove all record in a
specific record in a table. table.
SQL> DELETE FROM table_name
WHERE condition;
3 DELETE statement is a DML (Data Manipulation Language) Whereas TRUNCATE statement is a DDL (Data Definition
command. Language) command.
4 Executed DELETE statement you can UNDO the changes Whereas executed TRUNCATE statement you can't return
and return back to deleted data. back.
SQL INDEX
What is an index in SQL? SQL INDEX are used to quickly find data without searching every rows in a database table.
SQL INDEX is improve the speed of search operation on a database table. But additional you need more storage space to
maintain duplicate copy of the database.
INDEX is a copy of the selected column of the database table to store additionally duplicate copy of the data.
End users does not know for indexes is created on table, only they are searching data more quickly and efficiently.
Syntax
CREATE INDEX index_name
ON table_name (column_name)
[ storage_setting ];
Storage setting specifies the table space explicitly. This are the optional storage setting if you are not specifies
automatically default storage setting used.
Example
SQL> CREATE INDEX index_user_name
ON userinfo (name);
We are creating simple index on name column of the userinfo table. In this column allow duplicate values of the column.
Composite INDEX
Composite INDEX create on multiple selected column of the database table.
Syntax
CREATE INDEX index_name
ON table_name (column_name, column_name)
[ storage_setting ];
Example
SQL> CREATE INDEX index_userinfo
ON userinfo (no, name);
We are creating composite index on no, name column of the userinfo table. Duplicate values are allowing for creating
indexes.
Unique INDEX
Unique INDEX create on selected column of the database table and does not allow duplicate values of that indexes
column.
Syntax
CREATE UNIQUE INDEX index_name
ON table_name (column_name)
[ storage_setting ];
Example
SQL> CREATE UNIQUE INDEX index_user_name
ON userinfo (name);
We are create unique index on name column of the userinfo table. Duplicate name value are does not allow again for
creating indexes.
RENAME INDEX
Syntax
ALTER INDEX index_name
RENAME TO new_index_name;
Example
SQL> ALTER INDEX user_name
RENAME TO index_username;
We are renaming the above created index name index_user_name to a new index name index_username.
DROP INDEX
Syntax
DROP INDEX index_name;
Example
SQL> DROP INDEX index_username;
SQL JOIN
SQL JOIN four different types: INNER JOIN, OUTER JOIN, SELF JOIN, CROSS JOIN.
SQL JOIN clause use when select records rows from two or more tables from the database. It's depend on certain
columns from two table. Matching columns are evaluate and if predicated TRUE return a records set data in specified
format.
Equi Join: Equiv join is a same as inner join but different is check condition only specific type comparison (not
allowing comparison operator such as <, > etc).
Natural Join: Natural join is a same as Equi join but different is resulting contains allow only one column for each pair of same
columns named. Record set contains haven't same name columns are found.
Outer Join: Outer Join is a join two table involving common attributes from two tables. But tables (Table A) does not
require to have a matching value to other table (Table B).
Left Join/Left Outer Join: Left Outer Join always contains all records of left table (Table A) even of join condition
does not find any matching record in right table (Table B).
Right Join/Right Outer Join: Right Outer Join always contains all records of right table (Table B) even of join
condition does not find any matching record in left table (Table A).
Full Join/Full Outer Join: Full Outer Join always contains all records of left table (Table A) and right table (Table B) even of
join condition does not find any matching record in both left or right table. Returned result contains set NULL value for all
column that are lack of value in matching rows.
Example Table
Considering following category, product is our example table. In this following tables category_id column
of category table is primary key and product table category_id foreign key.
CREATE TABLE category(
category_id number(3) PRIMARY KEY,
category_name VARCHAR(25)
);
INSERT INTO category VALUES (1,'Mobiles');
INSERT INTO category VALUES (2,'Laptops');
INSERT INTO category VALUES (3,'Tablet');
INSERT INTO category VALUES (4,'Cameras');
INSERT INTO category VALUES (5,'Gaming');
CREATE TABLE product(
category_id number(3) REFERENCES category(category_id),
product_name VARCHAR(25)
);
SQL INNER JOIN check join condition (including other comparison operator such as <, > etc) and create record set result
that are combining columns value from the tables (two or more table).
SQL INNER JOIN compare each row of Table A with each row of Table B which are satisfied the join predicate and return
record set rows.
SQL INNER JOIN write two different way:
Example Table
Considering following category, product is our example table.
1 Mobiles 1 Nokia
2 Laptops 1 Samsung
3 Laptops 2 HP
4 Cameras 2 Dell
5 Gaming 3 Apple
4 Nikon
Null Playstation
Run it... »
Example
SQL> SELECT *
FROM product INNER JOIN category
ON product.category_id = category.category_id;
6 rows selected.
Run it... »
Example
SQL> SELECT *
FROM product, category
WHERE product.category_id = category.category_id;
6 rows selected.
1 Mobiles 1 Nokia
2 Laptops 1 Samsung
3 Laptops 2 HP
4 Cameras 2 Dell
5 Gaming 3 Apple
4 Nikon
Null Playstation
Run it... »
SQL Equi join use JOIN keyword specify table name and ON keyword specify the join predicate condition.
Example
SQL> SELECT *
FROM product JOIN category
ON product.category_id = category.category_id;
6 rows selected.
Run it... »
Example
SQL> SELECT *
FROM product, category
WHERE product.category_id = category.category_id;
6 rows selected.
Run it... »
If join predicate condition both table column name are same, then you can write this query shorthand way by using USING
Keyword.
Example
SQL> SELECT *
FROM product
INNER JOIN category USING (category_id);
6 rows selected.
SQL NATURAL JOIN
SQL NATURAL JOIN is a same as EQUI JOIN but different is resulting contains allow only one column for each pair of
same columns named. Record set contains haven't same name columns are found.
Example Table
Considering following SQL NATURAL JOIN example, category, product is our example table.
1 Mobiles 1 Nokia
2 Laptops 1 Samsung
3 Laptops 2 HP
4 Cameras 2 Dell
5 Gaming 3 Apple
4 Nikon
Null Playstation
Run it... »
SQL Natural join query use NATURAL JOIN keyword to specify table name.
Example
SQL> SELECT *
FROM product NATURAL JOIN category;
CATEGORY_ID PRODUCT_NAME CATEGORY_ID CATEGORY_NAME
----------- ------------------ ----------- -------------------
1 Nokia 1 Mobiles
1 Samsung 1 Mobiles
2 HP 2 Laptops
2 Dell 2 Laptops
3 Apple 3 Tablet
4 Nikon 4 Cameras
6 rows selected.
SQL OUTER JOIN - OUTER JOIN is a join two table involving common attributes from two tables. But tables (Table A) does
not require to have a matching value to other table (Table B).
Example Table
Considering following SQL left join example, category, product is our example table.
1 Mobiles 1 Nokia
2 Laptops 1 Samsung
3 Laptops 2 HP
4 Cameras 2 Dell
5 Gaming 3 Apple
4 Nikon
Null Playstation
Run it... »
Example
SQL> SELECT *
FROM product LEFT OUTER JOIN category
ON product.category_id = category.category_id;
7 rows selected.
Run it... »
Example
SQL> SELECT *
FROM product, category
WHERE product.category_id = category.category_id(+);
7 rows selected.
SQL OUTER JOIN - OUTER JOIN is a join two table involving common attributes from two tables. But tables (Table A) does
not require to have a matching value to other table (Table B).
Example Table
Considering following SQL left join example, category, product is our example table.
1 Mobiles 1 Nokia
2 Laptops 1 Samsung
3 Laptops 2 HP
4 Cameras 2 Dell
5 Gaming 3 Apple
4 Nikon
Null Playstation
Run it... »
Example
SQL> SELECT *
FROM product RIGHT OUTER JOIN category
ON product.category_id = category.category_id;
7 rows selected
Example Table
Considering following SQL FULL JOIN example, category, product is our example table.
1 Mobiles 1 Nokia
2 Laptops 1 Samsung
3 Laptops 2 HP
4 Cameras 2 Dell
5 Gaming 3 Apple
4 Nikon
Null Playstation
Run it... »
Example
SQL> SELECT *
FROM product FULL OUTER JOIN category
ON product.category_id = category.category_id;
8 rows selected.
You must use table alias name otherwise you can't distinguish columns name (referenced of which table's).
Logically assume that same table have two different copies but not actually different copies.
Example Table
Considering following orders table is our example table.
SQL> CREATE TABLE orders(
order_id number(3),
product_name VARCHAR(25),
customer_name VARCHAR(25),
order_amount number(5)
);
10 rows selected.
Run it... »
Run it... »
And last WHERE clause A.order_id < B.order_id means eliminate pairings where order_id Table A is not less than
to order_id of Table B.
SQL CROSS JOIN
SQL CROSS JOIN joining tables rows and return Cartesian product(each row from Table A with each row of Table B)
record set result.
Example Table
Considering following category, product is our example table.
SQL> SELECT * FROM category; SQL> SELECT * FROM product;
1 Mobiles 1 Nokia
2 Laptops 1 Samsung
3 Laptops 2 HP
4 Cameras 2 Dell
5 Gaming 3 Apple
4 Nikon
Null Playstation
Run it... »
Explicit Example
SQL> SELECT *
FROM product
CROSS JOIN category;
35 rows selected.
Run it... »
Implicit Example
SQL> SELECT *
FROM product, category;
SQL UNION clause is useful when you want to select distinct values (in selected columns) from the tables.
SQL UNION ALL clause used to select all values including duplicates from the tables.
Performance difference between UNION vs UNION ALL - SQL engine do some additional work for removing do additional
work to eliminates the duplicated rows.
UNION clause does not support BLOB or CLOB data type columns where as the UNION ALL support this data types.
Examples
Considering following product, out_of_stock_product is our example table. Both table have same column
name product_name. Execute this for creating table.
Example Table
CREATE TABLE product(
category_id number(3),
product_name VARCHAR(25)
);
Run it... »
1 Nokia 1 Samsung
2 Samsung 2 LG
3 HP 3 HTC
4 Dell 4 HP
5 Apple 5 Dell
6 Nikon 6 Apple
7 Playstation 7 Canon
8 Nikon
9 Xbox
10 Playstation
PRODUCT_NAME
-------------------------
Apple
Cameras
Dell
Gaming
HP
Laptops
Mobiles
Nikon
Nokia
Playstation
Samsung
Tablet
12 rows selected.
Run it... »
PRODUCT_NAME
-------------------------
Apple
Cameras
Dell
Gaming
HP
Laptops
Mobiles
Nikon
Nokia
Playstation
Samsung
Tablet
12 rows selected.
SQL Functions
Built-in Oracle SQL functions are following,
Oracle SQL provide buit-in SQL functions. SQL Functions take some values as a arguments, perform some function logic
and returning some values. SQL inbuilt function are so many that all are help us for no need to implementing your own
logic.
SQL Numeric Functions
SQL numeric function take numeric value (maximum 38 digit) and return numeric value (maximum 38 digit). SQL numeric
function return single row single column values. Following are some SQL numeric function.
BITAND BITAND Function take bitwise vector value and return the bitwise AND vector
value.
BIN_TO_NUM BIN_TO_NUM(n, ...) Function take any number of bit values. every value is must be either 0 or
1. This all bit values convert to a hexadecimal numeric value.
CEIL CEIL(n) Function return smallest integer round value that is greater then or equal
to a parameter value (n).
MOD MOD(n1,n2) Function return the reminder value of n1 divide by n2. Where n1 and n2 is
natural value.
NANVL NANVL(value,alternative_value) Function return the alternative value if the specified value is NaN (Not a
number). If value not NaN then return original value.
POWER POWER(n1,n2) Function return n1 raised to a n2 power. n1 is base value and n2 is any
numbers.
RAND RAND() Function generate random number between 0 to 1, but no longer support.
Optionally use Rownum to fetch random record from database table.
REMAINDER REMAINDER(n1,n2) Function return the remainder value of n1 divide by n2. Where n1 and n2
is natural value.
ROUND ROUND(n, decimal_number) Function return the round number of specified nth number of decimal
place.
SQRT SQRT(n) Function return the square root of the n number. SQRT function return the
real number.
TRUNC TRUNC(n, decimal_number) Function return the truncated number of specified nth number of decimal
place.
SQL String Functions
SQL String function take some value and return string value. Function return data type VARCHAR2 if parameter argument
CHAR or VARCHAR2 data type. Following are some SQL String function.
ASCII ASCII( character ) Function return the ASCII values of given argument.
CHR CHR( number ) Function return the ASCII value of the given argument value.
CONCAT CONCAT( string1, string2 ) Function concatenated string1 with string2 and return to a
concatenated string.
INITCAP INITCAP( char/string ) Function return capitalize string/char (capitalize first letter of
each word).
INSTR INSTR( original_string, sub_string ) Function return sub string position from the original string.
LTRIM LTRIM( string, trim_char ) Function remove all specified trim char from left side of the
string.
NCHR NCHR( ascii_number ) Function return the ASCII value of the given argument value.
REPLACE REPLACE( string, match_string, Function return the string/char of every matched string replace
replace_string ) with new string.
REGEXP_REPLACE REGEXP_REPLACE( original_string, Function original string represent to a regular expression pattern.
pattern )
REGEXP_SUBSTR REGEXP_SUBSTR( original_string, Function return substring from the original string using regular
pattern ) expression pattern.
REGEXP_LIKE REGEXP_LIKE( original_string, Function same as like condition but matching regular expression
pattern ) pattern to perform like condition.
RTRIM RTRIM( string, trim_char ) Function remove all specified trim char from right side of the
string.
SUBSTR SUBSTR( string, start_position, Function return a selected string character from a full string.
substr_length )
TRANSLATE TRANSLATE( string, match_char, Function return the string/char of every matched character
replace_char ) replace with new character.
TRIM TRIM( string ) Function remove all specified trim char from beginning and
ending of the string.