SlideShare a Scribd company logo
SQL
SQL stands for "Structured Query Language". It is used by Relational DataBase technologies
such as Oracle, Microsoft Access, and Sybase, among others. SQL lets you access and
manipulate databases. SQL is an ANSI (American National Standards Institute) standard. SQL
can execute queries against a database. SQL can retrieve data from a database. SQL can insert
records in a database. SQL can update records in a database. SQL can delete records from a
database. SQL can create new databases. SQL can create new tables in a database. SQL can
create stored procedures in a database. SQL can create views in a database. SQL can set
permissions on tables, procedures, and views. Although SQL is an ANSI (American National
Standards Institute) standard, there are many different versions of the SQL language. However,
to be compliant with the ANSI standard, they all support at least the major commands (such as
SELECT, UPDATE, DELETE, INSERT, WHERE) in a similar manner.
Note: Most of the SQL database programs also have their own proprietary extensions in addition
to the SQL standard! sequel – (Structured English Query Language)”.
RDBMS
RDBMS stands for Relational Database Management System. RDBMS is the basis for SQL, and
for all modern database systems like MS SQL Server, IBM DB2, Oracle, MySQL, and Microsoft
Access. The data in RDBMS is stored in database objects called tables. A table is a collections of
related data entries and it consists of columns and rows.
SQL Commands
SQL commands are instructions used to communicate with the database to perform specific
task that work with data. SQL commands can be used not only for searching the database
but also to perform various other functions like, for example, you can create tables, add
data to tables, or modify data, drop the table, set permissions for users. SQL commands are
grouped into four major categories depending on their functionality:
 Data Definition Language (DDL) - These SQL commands are used for creating,
modifying, and dropping the structure of database objects. The commands are
CREATE, ALTER, DROP, RENAME, and TRUNCATE.
 Data Manipulation Language (DML) - These SQL commands are used for
storing, retrieving, modifying, and deleting data. These commands are SELECT,
INSERT, UPDATE, and DELETE.
 Transaction Control Language (TCL) - These SQL commands are used for
managing changes affecting the data. These commands are COMMIT, ROLLBACK,
and SAVEPOINT.
 Data Control Language (DCL) - These SQL commands are used for providing
security to database objects. These commands are GRANT and REVOKE.
SQL SELECT Statement
The most commonly used SQL command is SELECT statement. The SQL SELECT
statement is used to query or retrieve data from a table in the database. A query may
retrieve information from specified columns or from all of the columns in the table. To
create a simple SQL SELECT Statement, you must specify the column(s) name and the
table name. The whole query is called SQL SELECT Statement.
Syntax of SQL SELECT Statement:
SELECT column_list FROM table_name
[WHERE Clause]
[GROUP BY Clause]
[HAVING Clause]
[ORDER BY Clause];
DataBase Table “student_details”:
ID FIRST_NAME LAST_NAME AGE SUBJECT GAMES
1 Pravesh Shrivastava 24 CSE Football
2 Nitin Singh 25 CSE Cricket
3 Akhilesh Kumar 25 CSE Cricket
4 Abhishek Tripathi 26 CSE Cricket
5 Priyanka Ghosh 25 CSE Basketball
To select the First Name of all the students the query would be like:
select first_name from student_details;
Output:
FIRST_NAME
Pravesh
Priyanka
Nitin
Akhilesh
Abhishek
You can also retrieve data from more than one column. For example, to select First Name
and Last Name of all the students.
select first_name, last_name from student_details;
Output:
FIRST_NAME LAST_NAME
Pravesh Shrivastava
Priyanka Ghosh
Nitin singh
Akhilesh Kumar
If we want to display the First and Last Name of a student combined together, the SQL Select
Statement would be like:
select first_name ||’’|| last_name from student_details;
Output:
FIRST_NAME||''||LAST_NAME
Pravesh Shrivastava
Nitin Singh
Akhilesh Kumar
Abhishek Tripathi
Priyanka Ghosh
You can also provide Alias as below.
select first_name ||’’|| last_name as Name from student_details;
Output:
NAME
Pravesh Shrivastava
Nitin Singh
Akhilesh Kumar
Abhishek Tripathi
Priyanka Ghosh
SQL DISTINCT STATEMENT
In a table, some of the columns may contain duplicate values. This is not a problem, however,
sometimes you will want to list only the different (distinct) values in a table. The DISTINCT
keyword can be used to return only distinct (different) values.
SQL SELECT DISTINCT Syntax
SELECT DISTINCT column_name(s) FROM table_name
To select all distinct subject names from student_details table, the query would be:
select distinct subject from student_details;
Output:
SUBJECT
CSE
SQL WHERE Clause
The WHERE Clause is used when you want to retrieve specific information from a table
excluding other irrelevant data. So SQL offers a feature called WHERE clause, which we
can use to restrict the data that is retrieved. The condition you provide in the WHERE
clause filters the rows retrieved from the table and gives you only those rows which you
expected to see. WHERE clause can be used along with SELECT, DELETE, UPDATE
statements.
Syntax of SQL WHERE Clause:
SELECT column_list FROM table_name WHERE condition;
To find the first name of a student with id 1, the query would be like:
select first_name from student_details where id=1;
Output:
FIRST_NAME
Pravesh
SQL Operators
There are two type of Operators, namely Comparison Operators and Logical Operators.
These operators are used mainly in the WHERE clause, HAVING clause to filter the data to
be selected.
Comparison Operators:
Comparison operators are used to compare the column data with specific values in a
condition.
Comparison Operators are also used along with the SELECT statement to filter data based
on specific conditions.
The below table describes each comparison operator.
Comparison
Operators
Description
= equal to
<>, != is not equal to
< less than
> greater than
>=
greater than or equal
to
<= less than or equal to
Logical Operators:
There are three Logical Operators namely, AND, OR, and NOT. These operators
compare two conditions at a time to determine whether a row can be selected for the output.
When retrieving data using a SELECT statement, you can use logical operators in the
WHERE clause, which allows you to combine more than one condition.
Logical
Operators
Description
OR
For the row to be selected at least one of
the conditions must be true.
AND
For a row to be selected all the specified
conditions must be true.
NOT
For a row to be selected the specified
condition must be false.
"OR" Logical Operator:
If you want to select rows that satisfy at least one of the given conditions, you can use the
logical operator, OR.
For example: if you want to find the names of students who are studying either CSE or
ECE, the query would be like,
SELECT first_name, last_name, subject
FROM student_details
WHERE subject = 'CSE' OR subject = 'ECE';
Output:
FIRST_NAME LAST_NAME SUBJECT
Pravesh Shrivastava CSE
Nitin Singh CSE
Akhilesh Kumar CSE
Abhishek Tripathi CSE
Priyanka Ghosh CSE
"AND" Logical Operator:
If you want to select rows that must satisfy all the given conditions, you can use the logical
operator, AND.
For Example: To find the names of the students between the age 24 to 26 years, the query
would be like:
SELECT first_name, last_name, age
FROM student_details
WHERE age >= 24 AND age <= 26;
Output:
FIRST_NAME LAST_NAME AGE
Pravesh Shrivastava 24
Nitin Singh 25
Akhilesh Kumar 25
Abhishek Tripathi 26
Priyanka Ghosh 25
"NOT" Logical Operator:
If you want to find rows that do not satisfy a condition, you can use the logical operator,
NOT. NOT results in the reverse of a condition. That is, if a condition is satisfied, then the
row is not returned.
For example: If you want to find out the names of the students who do not play football,
the query would be like:
SELECT first_name, last_name, games
FROM student_details
WHERE NOT games = 'Football'
Output:
FIRST_NAME LAST_NAME GAMES
Nitin Singh Cricket
Akhilesh Kumar Cricket
Abhishek Tripathi Cricket
Priyanka Ghosh Basketball
Nested Logical Operators:
You can use multiple logical operators in an SQL statement. When you combine the logical
operators in a SELECT statement, the order in which the statement is processed is
1) NOT
2) AND
3) OR
For example: If you want to select the names of the students who age is between 24 and 26
years, or those who do not play football, the SELECT statement would be
SELECT first_name, last_name, age, games
FROM student_details
WHERE age >= 24 AND age <= 26
OR NOT games = 'Football';
Output:
FIRST_NAME LAST_NAME AGE GAMES
Pravesh Shrivastava 24 Football
Nitin Singh 25 Cricket
Akhilesh Kumar 25 Cricket
Abhishek Tripathi 26 Cricket
Priyanka Ghosh 25 Basketball
SQL ORDER BY
The ORDER BY clause is used in a SELECT statement to sort results either in ascending or
descending order. Oracle sorts query results in ascending order by default.
Syntax for using SQL ORDER BY clause to sort data is:
SELECT column-list
FROM table_name [WHERE condition]
[ORDER BY [column1, column2, .. columnN] [DESC];
Database Table "student_details":
select id,first_name,last_name,age,subject,games from student_details order by id
Output:
ID FIRST_NAME LAST_NAME AGE SUBJECT GAMES
1 Pravesh Shrivastava 24 CSE Football
2 Nitin Singh 25 CSE Cricket
3 Akhilesh Kumar 25 CSE Cricket
4 Abhishek Tripathi 26 CSE Cricket
5 Priyanka Ghosh 25 CSE Basketball
If you want to sort the student_details table by the name and age, the query would be like,
SELECT first_name, age FROM student_details ORDER BY first_name, age;
Output:
FIRST_NAME AGE
Abhishek 26
Akhilesh 25
Nitin 25
Pravesh 24
Priyanka 25
NOTE:The columns specified in ORDER BY clause should be one of the columns selected
in the SELECT column list.
You can represent the columns in the ORDER BY clause by specifying the position of a
column in the SELECT list, instead of writing the column name.
The above query can also be written as given below,
SELECT first_name, age FROM student_details ORDER BY 1, 2;
Output:
FIRST_NAME AGE
Abhishek 26
Akhilesh 25
Nitin 25
Pravesh 24
Priyanka 25
By default, the ORDER BY Clause sorts data in ascending order. If you want to sort the
data in descending order, you must explicitly specify it as shown below.
SELECT first_name, age FROM student_details ORDER BY first_name, age
desc;
Output:
FIRST_NAME AGE
Abhishek 26
Akhilesh 25
Nitin 25
Pravesh 24
Priyanka 25
The above query sorts only the column 'age' in descending order and the column 'first_name'
by ascending order.
If you want to select both first_name and age in descending order, the query would be as
given below.
SELECT first_name, age FROM student_details ORDER BY first_name
desc, age desc;
Output:
FIRST_NAME AGE
Priyanka 25
Pravesh 24
Nitin 25
Akhilesh 25
Abhishek 26
How to use expressions in the ORDER BY Clause?
For example: If you want to display student_details first_name, age, and a 20% increase in the
age for only those students for whom the percentage increase in age is greater than 30, the
SELECT statement can be written as shown below
SELECT first_name, age, age*1.2 AS new_age
FROM student_details
WHERE age*1.2 > 30
ORDER BY new_age DESC;
Output:
FIRST_NAME AGE NEW_AGE
Abhishek 26 31.2
NOTE: Aliases defined in the SELECT Statement can be used in ORDER BY Clause.
SQL INSERT Statement
The INSERT Statement is used to add new rows of data to a table.
We can insert data to a table in two ways,
1) Inserting the data directly to a table.
Syntax for SQL INSERT is
INSERT INTO TABLE_NAME
[ (col1, col2, col3,...colN)]
VALUES (value1, value2, value3,...valueN);
While inserting a row, if you are adding value for all the columns of the table you need not
specify the column(s) name in the sql query. But you need to make sure the order of the values
is in the same order as the columns in the table. The sql insert query will be as follows
INSERT INTO TABLE_NAME
VALUES (value1, value2, value3,...valueN);
For Example: If you want to insert a row to the employee table, the query would be like,
insert into student_details (id,first_name,last_name,age,subject,games)
values(1,'Pravesh','Shrivastava',24,'CSE','Football')
Output:
ID FIRST_NAME LAST_NAME AGE SUBJECT GAMES
1 Pravesh Shrivastava 24 CSE Football
NOTE: When adding a row, only the characters or date values should be enclosed with single
quotes.
If you are inserting data to all the columns, the column names can be omitted. The above insert
statement can also be written as,
insert into student_details values (3,’Nitin’,’Singh’,24,’CSE’,’Cricket’);
Output:
ID FIRST_NAME LAST_NAME AGE SUBJECT GAMES
1 Pravesh Shrivastava 24 CSE Football
2 Priyanka Ghosh 25 CSE Basketball
3 Nitin Singh 24 CSE Cricket
Inserting data to a table through a select statement:
Syntax for SQL INSERT is:
INSERT INTO table_name
[(column1, column2, ... columnN)]
SELECT column1, column2, ...columnN
FROM table_name [WHERE condition];
For Example: To insert a row into the student_details table from emp_net table, the sql insert
into query would be like,
emp_net table:
EMP_ID EMP_NAME
1 Ranjita
INSERT INTO student_details (id, first_name) SELECT emp_id, emp_name
FROM emp_net;
Output:
ID FIRST_NAME LAST_NAME AGE SUBJECT GAMES
1 Pravesh Shrivastava 24 CSE Football
2 Priyanka Ghosh 25 CSE Basketball
3 Nitin Singh 24 CSE Cricket
1 Ranjita - - - -
If you are inserting data to all the columns, the above insert statement can also be written as,
stu_net table:
STU_ID STU_F_NAME STU_L_NAME STU_AGE STU_SUB STU_GAMES
4 Akhilesh Kumar 25 CSE Cricket
INSERT INTO student_details
SELECT * FROM stu_net;
Output:
NOTE:We have assumed the stu_net table has columns stu_id, stu_f_name, stu_l_name,
stu_age, stu_sub, stu_ games the above given order and the same datatype.
IMPORTANT NOTE:
1) When adding a new row, you should ensure the datatype of the value and the column
matches
2) You follow the integrity constraints, if any, defined for the table.
ID FIRST_NAME LAST_NAME AGE SUBJECT GAMES
1 Pravesh Shrivastava 24 CSE Football
2 Priyanka Ghosh 25 CSE Basketball
3 Nitin Singh 24 CSE Cricket
1 Ranjita - - - -
4 Akhilesh Kumar 25 CSE Cricket
SQL UPDATE Statement
The UPDATE statement is used to update existing records in a table.
SQL UPDATE Syntax:
UPDATE table_name
SET column1=value2, column2=value2,...
WHERE some_column=some_value;
If we are updating the table student_details where first_name is Ranjita. The query would be
like:
update student_details set last_name='Kapoor', age=25,
subject='BSC',games='Badminton' where first_name='Ranjita';
Output:
ID FIRST_NAME LAST_NAME AGE SUBJECT GAMES
1 Pravesh Shrivastava 24 CSE Football
2 Priyanka Ghosh 25 CSE Basketball
3 Nitin Singh 24 CSE Cricket
1 Ranjita Kapoor 25 BSC Badminton
4 Akhilesh Kumar 25 CSE Cricket
Note: Notice the WHERE clause in the UPDATE syntax. The WHERE clause specifies which
record or records that should be updated. If you omit the WHERE clause, all records will be
updated!
update student_details set last_name='Kapoor', age=25;
Output:
ID FIRST_NAME LAST_NAME AGE SUBJECT GAMES
1 Pravesh Kapoor 25 CSE Football
2 Priyanka Kapoor 25 CSE Basketball
3 Nitin Kapoor 25 CSE Cricket
1 Ranjita Kapoor 25 BSC Badminton
4 Akhilesh Kapoor 25 CSE Cricket
To change the salaries of all the employees, the query would be,
update employee set salary=salary*2;
employee table:
ID NAME SALARY
1 Pravesh 19000
2 Nitin 19000
3 aaa 500
Output:
ID NAME SALARY
1 Pravesh 38000
2 Nitin 38000
3 aaa 1000
SQL DELETE Statement
The DELETE statement is used to delete records in a table. The DELETE statement is used to
delete rows in a table.
SQL DELETE Syntax:
DELETE FROM table_name
WHERE some_column=some_value;
If we want to delete the record where first name is Ranjita, the query would be like:
delete from student_details where first_name='Ranjita';
Output:
Note: Notice the
WHERE clause in the DELETE syntax. The WHERE clause specifies which record or records
that should be deleted. If you omit the WHERE clause, all records will be deleted!
Delete All Rows
It is possible to delete all rows in a table without deleting the table. This means that the table
structure, attributes, and indexes will be intact:
DELETE FROM table_name;
or
DELETE * FROM table_name;
Example:
delete from student_details;
Or
delete * from student_details;
Note: Be very careful when deleting records. You cannot undo this statement!
ID FIRST_NAME LAST_NAME AGE SUBJECT GAMES
1 Pravesh Shrivastava 24 CSE Tennis
2 Priyanka Ghosh 25 CSE Basketball
3 Nitin singh 25 CSE Cricket
4 Akhilesh Kumar 25 CSE Cricket
You may wish to check for the number of rows that will be deleted. You can determine the
number of rows that will be deleted by running the following SQL statement before performing
the delete.
SELECT count(*)
FROM student_details
WHERE first_name = 'Pravesh';
Output:
COUNT(*)
1
The ROWNUM Clause
The ROWNUM clause is used to specify the number of records to return. The ROWNUM clause
can be very useful on large tables with thousands of records. Returning a large number of records
can impact on performance.
Note: Not all database systems support the TOP clause.
Syntax:
SELECT column_name(s)
FROM table_name
WHERE ROWNUM <= number;
Example:
Now we want to select only the two first records in the table. We use the following SELECT
statement:
select * from student_details where rownum <=3;
Output:
ID FIRST_NAME LAST_NAME AGE SUBJECT GAMES
1 Pravesh Shrivastava 24 CSE Tennis
2 Priyanka Ghosh 25 CSE Basketball
3 Nitin singh 25 CSE Cricket
SQL LIKE Operator
The LIKE operator is used to list all rows in a table whose column values match a specified
pattern. It is useful when you want to search rows to match a specific pattern, or when you do not
know the entire value. The LIKE condition allows you to use wildcards in the where clause of an
SQL statement. This allows you to perform pattern matching. The LIKE condition can be used in
any valid SQL statement - select, insert, update, or delete. The patterns that you can choose from
are:
% allows you to match any string of any length (including zero length).
_ allows you to match on a single character.
Examples using % wildcard:
We are going to try to find all of the person whose first name begins with 'Pr'.
select* from student_details
where first_name like 'Pr%';
Output:
ID FIRST_NAME LAST_NAME AGE SUBJECT GAMES
1 Pravesh Shrivastava 24 CSE Tennis
2 Priyanka Ghosh 25 CSE Basketball
You can also using the wildcard multiple times within the same string. For example,
In this example, we are looking for all persons whose first name contains the characters 'Pra'.
select * from student_details
where first_name like '%Pra%';
Output:
ID FIRST_NAME LAST_NAME AGE SUBJECT GAMES
1 Pravesh Shrivastava 24 CSE Tennis
You could also use the LIKE condition to find persons whose first name does not start with 'P'.
For example,
select * from student_details
where first_name not like 'P%';
By placing the not keyword in front of the LIKE condition, you are able to retrieve all suppliers
whose name does not start with 'P'.
Output:
ID FIRST_NAME LAST_NAME AGE SUBJECT GAMES
3 Nitin singh 25 CSE Cricket
4 Akhilesh Kumar 25 CSE Cricket
Examples using _ wildcard:
Remember that the _ is looking for only one character. For example,
select * from student_details where first_name like 'Pr_yanka%';
Output:
ID FIRST_NAME LAST_NAME AGE SUBJECT GAMES
2 Priyanka Ghosh 25 CSE Basketball
Examples using Escape Characters:
Next, in Oracle, let's say you wanted to search for a % or a _ character in a LIKE
condition. You can do this using an Escape character. Please note that you can define an escape
character as a single character (length of 1) ONLY. For example,
select * from student_details where first_name like '%' escape '!';
This example returns all persons whose first name starts with any of the words and ends
in %. For example, it would return a value such as 'Pravesh%'.
Output:
ID FIRST_NAME LAST_NAME AGE SUBJECT GAMES
1 Pravesh Shrivastava 24 CSE Tennis
2 Priyanka Ghosh 25 CSE Basketball
3 Nitin singh 25 CSE Cricket
4 Akhilesh Kumar 25 CSE Cricket
select * from student_details where first_name like 'P%' escape '!';
This example returns all persons whose first name starts with P and ends in _. For
example, it would return a value such as 'Pravesh_'.
Output:
ID FIRST_NAME LAST_NAME AGE SUBJECT GAMES
1 Pravesh Shrivastava 24 CSE Tennis
2 Priyanka Ghosh 25 CSE Basketball
SQL Wildcards
SQL wildcards can substitute for one or more characters when searching for data in a database.
SQL wildcards must be used with the SQL LIKE operator. With SQL, the following wildcards
can be used:
Wildcard Description
% A substitute for zero or more characters
_ A substitute for exactly one character
[charlist] Any single character in charlist
SQL Wildcard Examples
Using the % Wildcard:
Now we want to select the students whose first names start with "Pr" from the
"student_details" table. We use the following SELECT statement:
select * from student_details where first_name like 'Pr%';
Output:
Next, we want to select the students whose subjects contain the pattern "CSE" from the
"student_details" table. We use the following SELECT statement:
select * from student_details where subject like '%CSE%';
Output:
ID FIRST_NAME LAST_NAME AGE SUBJECT GAMES
1 Pravesh Shrivastava 24 CSE Tennis
2 Priyanka Ghosh 25 CSE Basketball
3 Nitin singh 25 CSE Cricket
4 Akhilesh Kumar 25 CSE Cricket
Using the _ Wildcard:
Now we want to select the students with the first name that starts with any character,
followed by "ravesh" from the "student_details" table. We use the following SELECT statement:
select * from student_details where first_name LIKE '_ravesh%';
ID FIRST_NAME LAST_NAME AGE SUBJECT GAMES
1 Pravesh Shrivastava 24 CSE Tennis
2 Priyanka Ghosh 25 CSE Basketball
Output:
ID FIRST_NAME LAST_NAME AGE SUBJECT GAMES
1 Pravesh Shrivastava 24 CSE Tennis
SQL IN Function
The IN function helps reduce the need to use multiple OR conditions. The syntax for the IN
function is:
SELECT columns
FROM tables
WHERE column1 in (value1, value2, .... value_n);
This SQL statement will return the records where column1 is value1, value2..., or value_n. The
IN function can be used in any valid SQL statement - select, insert, update, or delete.
Example:
The following is an SQL statement that uses the IN function:
select * from student_details where first_name in ('Pravesh','Priyanka','Santosh');
Output:
ID FIRST_NAME LAST_NAME AGE SUBJECT GAMES
1 Pravesh Shrivastava 24 CSE Tennis
2 Priyanka Ghosh 25 CSE Basketball
This would return all rows where the first name is either Pravesh, Priyanka, or Santosh.
Because the * is used in the select, all fields from the student_details table would appear in the
result set.
It is equivalent to the following statement:
select * from student_details where first_name = 'Pravesh' OR first_name =
'Priyanka' OR first_name = 'Santosh';
Output:
ID FIRST_NAME LAST_NAME AGE SUBJECT GAMES
1 Pravesh Shrivastava 24 CSE Tennis
2 Priyanka Ghosh 25 CSE Basketball
As you can see, using the IN function makes the statement easier to read and more efficient.
Example:
You can also use the IN function with numeric values.
select * from student_details where id in (1,2,3,4,5,6);
Output:
ID FIRST_NAME LAST_NAME AGE SUBJECT GAMES
1 Pravesh Shrivastava 24 CSE Tennis
2 Priyanka Ghosh 25 CSE Basketball
3 Nitin singh 25 CSE Cricket
4 Akhilesh Kumar 25 CSE Cricket
This SQL statement would return all students where the id is either 1, 2, 3, 5, or 6.
It is equivalent to the following statement:
select * from student_details where id=1 or id=2 or id=3 or id=4 or id=5 or id=6;
Output:
ID FIRST_NAME LAST_NAME AGE SUBJECT GAMES
1 Pravesh Shrivastava 24 CSE Tennis
2 Priyanka Ghosh 25 CSE Basketball
3 Nitin singh 25 CSE Cricket
4 Akhilesh Kumar 25 CSE Cricket
Example:
The IN function can also be combined with the NOT operator.
select * from student_details where first_name not in ('Pravesh', 'Santosh', 'Nitin');
Output:
ID FIRST_NAME LAST_NAME AGE SUBJECT GAMES
2 Priyanka Ghosh 25 CSE Basketball
4 Akhilesh Kumar 25 CSE Cricket
This would return all rows where the first_name is neither Pravesh, Santosh, nor Nitin.
Sometimes, it is more efficient to list the values that you do not want, as opposed to the values
that you do want.
SQL BETWEEN Operator
The BETWEEN operator is used in a WHERE clause to select a range of data between two
values. The values can be numbers, text, or dates.
SQL BETWEEN Syntax:
SELECT column_name(s)
FROM table_name
WHERE column_name
BETWEEN value1 AND value2;
Now we want to select the students with a last name alphabetically between "Kumar" and
"Shrivastava" from the table above. We use the following SELECT statement:
select * from student_details where last_name between 'Kumar'and 'Shrivastava';
Output:
Note: The BETWEEN operator is treated differently in different databases. In Oracle, persons
with the Last Name of "Kumar" or "Shrivastava" will be listed, because the BETWEEN operator
selects fields that are between and including the test values.
To display the students outside the range in the previous example, use NOT BETWEEN:
select * from student_details where last_name not between 'Kumar' and
'Shrivastava';
Output:
ID FIRST_NAME LAST_NAME AGE SUBJECT GAMES
2 Priyanka Ghosh 25 CSE Basketball
3 Nitin singh 25 CSE Cricket
ID FIRST_NAME LAST_NAME AGE SUBJECT GAMES
1 Pravesh Shrivastava 24 CSE Tennis
4 Akhilesh Kumar 25 CSE Cricket
SQL Alias
With SQL, an alias name can be given to a table or to a column. You can give a table or a
column another name by using an alias. This can be a good thing to do if you have very long or
complex table names or column names. An alias name could be anything, but usually it is short.
SQL Alias Syntax for Tables:
SELECT column_name(s)
FROM table_name
AS alias_name;
SQL Alias Syntax for Columns:
SELECT column_name AS alias_name
FROM table_name;
Or
SELECT column_name ALIAS_NAME FROM table_name;
Table level alias:
select s.id,s.first_name from student_details s;
Output:
Column Level alias:
select id, first_name as name from student_details;
Output:
The above query is same like:
ID FIRST_NAME
1 Pravesh
2 Priyanka
3 Nitin
4 Akhilesh
ID NAME
1 Pravesh
2 Priyanka
3 Nitin
4 Akhilesh
select student_details.id, student_details.first_name from student_details;
Output:
ID FIRST_NAME
1 Pravesh
2 Priyanka
3 Nitin
4 Akhilesh
SQL Joins
The JOIN keyword is used in an SQL statement to query data from two or more tables, based on
a relationship between certain columns in these tables. Tables in a database are often related to
each other with keys. A primary key is a column (or a combination of columns) with a unique
value for each row. Each primary key value must be unique within the table. The purpose is to
bind data together, across tables, without repeating all of the data in every table.
Or
SQL Joins are used to relate information in different tables. A Join condition is a part of the sql
query that retrieves rows from two or more tables. A SQL Join condition is used in the SQL
WHERE Clause of select, update, delete statements. If a sql join condition is omitted or if it is
invalid the join operation will result in a Cartesian product. The Cartesian product returns a
number of rows equal to the product of all rows in all the tables being joined. For example, if the
first table has 20 rows and the second table has 10 rows, the result will be 20 * 10, or 200 rows.
This query takes a long time to execute.
Or
A join is used to combine rows from multiple tables. A join is performed whenever two or more
tables is listed in the FROM clause of an SQL statement.
Different SQL JOINs:
 JOIN: Return rows when there is at least one match in both tables.
 LEFT JOIN: Return all rows from the left table, even if there are no matches in the right
table.
 RIGHT JOIN: Return all rows from the right table, even if there are no matches in the
left table.
 FULL JOIN: Return rows when there is a match in one of the tables.
1) SQL Equi Joins:
An equi-join is further classified into two categories:
a) SQL Inner Join
b) SQL Outer Join
(a)SQL INNER JOIN
The INNER JOIN keyword return rows when there is at least one match in both tables. All
the rows returned by the sql query satisfy the sql join condition specified. It is the most
common type of join. Inner joins return all rows from multiple tables where the join
condition is met.
Table: suppliers:
Table: orders:
All the rows returned by the sql query satisfy the sql join condition specified.
For example: If you want to display the product information for each order the query will
be as given below. Since you are retrieving the data from two tables, you need to identify
the common column between these two tables, which is the supplier_id. The query for this
type of sql joins would be like,
select order_id, supplier_name from suppliers, orders where orders.supplier_id =
suppliers.supplier_id;
Output:
ORDER_ID SUPPLIER_NAME
50012 IBM
50013 Hewlett Packard
The rows for Microsoft and NVIDIA from the supplier table would be omitted, since the
supplier_id's 10002 and 10003 do not exist in both tables.
SUPPLIER_ID SUPPLIER_NAME
10000 IBM
10001 Hewlett Packard
10002 Microsoft
10003 NVIDIA
ORDER_ID SUPPLIER_ID ORDER_DATE
50012 10000 17-AUG-11
50013 10001 18-AUG-11
The columns must be referenced by the table name in the join condition, because
supplier_id is a column in both the tables and needs a way to be identified. This avoids
ambiguity in using the columns in the SQL SELECT statement.
The number of join conditions is (n-1), if there are more than two tables joined in a query
where 'n' is the number of tables involved. The rule must be true to avoid Cartesian product.
We can also use aliases to reference the column name, then the above query would be like,
select o.order_id, s.supplier_name from suppliers s, orders o where o.supplier_id =
s.supplier_id;
Output:
The rows for Microsoft and NVIDIA from the supplier table would be omitted, since the
supplier_id's 10002 and 10003 do not exist in both tables.
INNER JOIN (SQL SERVER)
select suppliers.supplier_name, orders.order_date, orders.order_id from orders inner
join suppliers on orders.supplier_Id=suppliers.supplier_Id;
Or
select suppliers.supplier_name, orders.order_date, orders.order_id from suppliers
inner join orders on suppliers.supplier_Id=orders.supplier_Id;
Or
select supplier_name, order_date, order_id from orders inner join suppliers
on orders.supplier_Id=suppliers.supplier_Id;
Or (With Alias)
select s.supplier_name, o.order_date, o.order_id from orders o inner join suppliers s
on o.supplier_Id=s.supplier_Id;
ORDER_ID SUPPLIER_NAME
50012 IBM
50013 Hewlett Packard
Output:
SUPPLIER_NAME ORDER_DATE ORDER_ID
IBM 17-AUG-11 50012
Hewlett Packard 18-AUG-11 50013
(b)SQL OUTER JOIN
This sql join condition returns all rows from both tables which satisfy the join
condition along with rows which do not satisfy the join condition from one of the
tables. The sql outer join operator in Oracle is (+) and is used on one side of the join
condition only. This type of join returns all rows from one table and only those rows
from a secondary table where the joined fields are equal (join condition is met).
Note: The syntax differs for different RDBMS implementation. Few of them represent
the join conditions as "sql left outer join", "sql right outer join".
(a)Left Outer Join
If you want to display all the suppliers data along with orders data, with null values
displayed for orders if a supplier has no order_id, the sql query for outer join would be
as shown below:
select s.supplier_id, s.supplier_name, o.order_id, o.order_date from orders o,
suppliers s where o.supplier_id (+) = s.supplier_id;
Output:
Or
The LEFT JOIN keyword returns all rows from the left table, even if there are no
matches in the right table.
SQL Server Syntax:
SELECT column_name(s)FROM table_name1 LEFT JOIN table_name2
ON table_name1.column_name=table_name2.column_name;
SQL Server Query:
select suppliers.supplier_id, suppliers.supplier_name, orders.order_id from
suppliers left join orders on suppliers.supplier_Id=orders.supplier_Id order by
suppliers.supplier_name;
Output:
If we revert the query:
select suppliers.supplier_id, suppliers.supplier_name, orders.order_id from
orders left join suppliers on suppliers.supplier_id=orders.supplier_id order by
suppliers.supplier_name;
Output:
SUPPLIER_ID SUPPLIER_NAME ORDER_ID ORDER_DATE
10000 IBM 50012 17-AUG-11
10001 Hewlett Packard 50013 18-AUG-11
10002 Microsoft - -
10003 NVIDIA - -
SUPPLIER_ID SUPPLIER_NAME ORDER_ID
10001 Hewlett Packard 50013
10000 IBM 50012
10002 Microsoft -
10003 NVIDIA -
SUPPLIER_ID SUPPLIER_NAME ORDER_ID
10001 Hewlett Packard 50013
10000 IBM 50012
(b)RIGHT OUTER JOIN
The RIGHT JOIN keyword Return all rows from the right table, even if there are no matches in the left
table.
NOTE: If the (+) operator is used in the left side of the join condition it is equivalent to left outer join.
If used on the right side of the join condition it is equivalent to right outer join.
select s.supplier_id, s.supplier_name, o.order_id, o.order_date from suppliers s, orders o
where o.supplier_id = s.supplier_id(+);
Output:
SUPPLIER_ID SUPPLIER_NAME ORDER_ID ORDER_DATE
10000 IBM 50012 17-AUG-11
10001 Hewlett Packard 50013 18-AUG-11
select s.supplier_id, s.supplier_name, o.order_id, o.order_date from suppliers s, orders o
where s.supplier_id = o.supplier_id (+);
Output:
SUPPLIER_ID SUPPLIER_NAME ORDER_ID ORDER_DATE
10000 IBM 50012 17-AUG-11
10001 Hewlett Packard 50013 18-AUG-11
10002 Microsoft - -
10003 NVIDIA - -
SQL Server Syntax:
SELECT column_name(s)FROM table_name1 RIGHT JOIN table_name2 ON
table_name1.column_name=table_name2.column_name;
SQL Server Example (1):
select suppliers.supplier_id, suppliers.supplier_name, orders.order_id, orders.order_date
from suppliers right join orders on suppliers.supplier_id = orders.supplier_id;
Output:
SUPPLIER_ID SUPPLIER_NAME ORDER_ID ORDER_DATE
10000 IBM 50012 17-AUG-11
10001 Hewlett Packard 50013 18-AUG-11
SQL Server Example (2):
select suppliers.supplier_id, suppliers.supplier_name, orders.order_id, orders.order_date
from orders right join suppliers on suppliers.supplier_id = orders.supplier_id;
Output:
SUPPLIER_ID SUPPLIER_NAME ORDER_ID ORDER_DATE
10000 IBM 50012 17-AUG-11
10001 Hewlett Packard 50013 18-AUG-11
10002 Microsoft - -
10003 NVIDIA - -
SQL Server Example (3):
select suppliers.supplier_id, suppliers.supplier_name, orders.order_id, orders.order_date
from suppliers right join orders on orders.supplier_id = suppliers.supplier_id;
Output:
SUPPLIER_ID SUPPLIER_NAME ORDER_ID ORDER_DATE
10000 IBM 50012 17-AUG-11
10001 Hewlett Packard 50013 18-AUG-11
select suppliers.supplier_id, suppliers.supplier_name, orders.order_id, orders.order_date
from orders right join suppliers on orders.supplier_id = suppliers.supplier_id;
Output:
SUPPLIER_ID SUPPLIER_NAME ORDER_ID ORDER_DATE
10000 IBM 50012 17-AUG-11
10001 Hewlett Packard 50013 18-AUG-11
10002 Microsoft - -
10003 NVIDIA - -
SQL FULL Join
The FULL JOIN keyword return rows when there is a match in one of the tables.
Syntax:
SELECT column_name(s)
FROM table_name1
FULL JOIN table_name2
ON table_name1.column_name=table_name2.column_name;
Example:
Now we want to list all the suppliers and their orders, and all the orders with their persons.
select suppliers.supplier_id, suppliers.supplier_name, orders.order_id from suppliers full
join orders on suppliers.supplier_Id = orders.supplier_Id;
Output:
SUPPLIER_ID SUPPLIER_NAME ORDER_ID
10000 IBM 50012
10001 Hewlett Packard 50013
10002 Microsoft -
10003 NVIDIA -
The FULL JOIN keyword returns all the rows from the left table, and all the rows from the
right table. If there are rows in "suppliers" that do not have matches in "Orders", or if there are rows in
"Orders" that do not have matches in "suppliers", those rows will be listed as well.
SQL SELF JOIN
A Self Join is a type of sql join which is used to join a table to itself, particularly when the
table has a FOREIGN KEY that references its own PRIMARY KEY. It is necessary to
ensure that the join statement defines an alias for both copies of the table to avoid column
ambiguity.
Example:
select s.supplier_id, s.supplier_name, o.order_id from suppliers s, orders o where
s.supplier_id = o.supplier_id;
Output:
SUPPLIER_ID SUPPLIER_NAME ORDER_ID
10000 IBM 50012
10001 Hewlett Packard 50013
SQL UNION Operator
The UNION operator is used to combine the result-set of two or more SELECT statements.
Notice that each SELECT statement within the UNION must have the same number of columns.
The columns must also have similar data types. Also, the columns in each SELECT statement
must be in the same order. It removes duplicate rows between the various "select" statements.
SQL UNION Syntax:
SELECT column_name(s) FROM table_name1
UNION
SELECT column_name(s) FROM table_name2;
Example:
select supplier_id from suppliers union select supplier_id from orders;
Output:
In this example, if a supplier_id appeared in both the suppliers and orders table, it would appear
once in your result set. The UNION removes duplicates.
Example: With ORDER BY Clause
The following is a UNION query that uses an ORDER BY clause:
select supplier_id
from suppliers
where supplier_id > 200
union
select order_id
from orders
where order_id > 1000
ORDER BY 1;
Since the column names are different between the two "select" statements, it is more
advantageous to reference the columns in the ORDER BY clause by their position in the result
set. In this example, we've sorted the results by supplier_id / order_id in ascending order, as
denoted by the "ORDER BY 1".
The supplier_id / order_id fields are in position #1 in the result set.
SUPPLIER_ID
10000
10001
10002
10003
SQL UNION ALL
The UNION ALL query allows you to combine the result sets of 2 or more "select" queries. It
returns all rows (even if the row exists in more than one of the "select" statements).
Each SQL statement within the UNION ALL query must have the same number of fields in the
result sets with similar data types.
UNION ALL Syntax:
SELECT column_name(s) FROM table_name1
UNION ALL
SELECT column_name(s) FROM table_name2;
Example:
select supplier_id
from suppliers
union all
select supplier_id
from orders;
Output:
If a supplier_id appeared in both the suppliers and orders table, it would appear multiple times in
your result set. The UNION ALL does notremove duplicates.
Example:
select supplier_id from suppliers where supplier_id > 200
union all
select order_id from orders where order_id > 1000
order by 1;
Output:
SUPPLIER_ID
10000
10001
10002
10003
10000
10001
SUPPLIER_ID
10000
10001
10002
10003
50012
50013
SQL CREATE TABLE Statement
The CREATE TABLE Statement is used to create tables to store data. Integrity Constraints like
primary key, unique key, foreign key can be defined for the columns while creating the table.
The integrity constraints can be defined at column level or table level. The implementation and
the syntax of the CREATE Statements differs for different RDBMS.
CREATE TABLE Statement Syntax:
CREATE TABLE table_name
(column_name1 datatype,
column_name2 datatype,
... column_nameN datatype
);
Example: If you want to create the employee table, the statement would be like,
create table employee
( id number(5),
name char(20),
dept char(10),
age number(2),
salary number(10),
location char(10)
);
CREATE a table from another table
You can also create a table from an existing table by copying the existing table's columns.
It is important to note that when creating a table in this way, the new table will be populated with
the records from the existing table (based on the SELECT Statement).
Syntax: Copying all columns from another table
CREATE TABLE new_table
AS (SELECT * FROM old_table);
Example:
create table new_table
as (select * from company);
Syntax: Copying selected columns from another table
CREATE TABLE new_table
AS (SELECT column_1, column2, ... column_n FROM old_table);
Example:
create table supply_new
as (select id, city, state
from supply
where id = 1);
Syntax: Copying selected columns from multiple tables
CREATE TABLE new_table
AS (SELECT column_1, column2, ... column_n
FROM old_table_1, old_table_2, ... old_table_n);
Example:
create table supply_new_new
as (select supply.id, supply.address, orders.order_id from supply, orders
where orders.order_id = supply.id
and id = 1);
SQL Constraints
Constraints are used to limit the type of data that can go into a table. Constraints can be specified
when a table is created (with the CREATE TABLE statement) or after the table is created (with
the ALTER TABLE statement). We will focus on the following constraints:
 NOT NULL
 UNIQUE
 PRIMARY KEY
 FOREIGN KEY
 CHECK
 DEFAULT
Constraints can be defined in two ways:
1) The constraints can be specified immediately after the column definition. This is called
column-level definition.
2) The constraints can be specified after all the columns are defined. This is called table-level
definition.
SQL NOT NULL Constraint
The NOT NULL constraint enforces a column to NOT accept NULL values. The NOT NULL
constraint enforces a field to always contain a value. This means that you cannot insert a new
record, or update a record without adding a value to this field.
Example with Constraint:
create table employee
( id number(5),
name char(20) constraint nm_nn not null,
dept char(10),
age number(2),
salary number(10),
location char(10)
);
Or
Example without Constraint:
create table employee
( id number(5),
name char(20) not null,
dept char(10),
age number(2),
salary number(10),
location char(10)
);
SQL UNIQUE Constraint
The UNIQUE constraint uniquely identifies each record in a database table. The UNIQUE and
PRIMARY KEY constraints both provide a guarantee for uniqueness for a column or set of
columns. A PRIMARY KEY constraint automatically has a UNIQUE constraint defined on it.
Note that you can have many UNIQUE constraints per table, but only one PRIMARY KEY
constraint per table.
Example:
create table employee
( id number(5),
name char(20),
dept char(10),
age number(2),
salary number(10),
location char(10) UNIQUE
);
Or
create table employee
( id number(5)not null unique,
name char(20),
dept char(10),
age number(2),
salary number(10),
location char(10) unique
);
Or
create table employee
( id number(5),
name char(20),
dept char(10),
age number(2),
salary number(10),
location char(10) constraint loc_un unique
);
Or
create table employee
(id number(5),
name char(20),
dept char(10),
age number(2),
salary number(10),
location char(10),
constraint loc_un unique(location)
);
Or
create table employee
(id number(5),
name char(20),
dept char(10),
age number(2),
salary number(10),
location char(10),
constraint loc_un unique(location, name)
);
SQL UNIQUE Constraint on ALTER TABLE
To create a UNIQUE constraint on the "id" column when the table is already created, use the
following SQL:
Add Unique constraint without constraint:
alter table employee
add unique(id);
Add Unique constraint with constraint:
alter table employee
add constraint uc_e_id unique(id,name);
To allow naming of a UNIQUE constraint, and for defining a UNIQUE constraint on multiple
columns, use the following SQL syntax:
alter table employee
add constraint uc_e_id unique(id,name);
To DROP a UNIQUE Constraint
alter table employee
drop constraint uc_e_id;
SQL PRIMARY KEY Constraint
This constraint defines a column or combination of columns which uniquely identifies each row
in the table.
Primary Key on Create Table:
Primary Key at column level without Constraint:
create table employee
(id number(5) primary key,
name char(20),
dept char(10),
age number(2),
salary number(10),
location char(10)
);
Primary Key at column level with Constraint:
create table employee
(id number(5) constraint emp_id_pk primary key,
name char(20),
dept char(10),
age number(2),
salary number(10),
location char(10)
);
Primary Key at table level:
create table employee
(id number(5),
name char(20),
dept char(10),
age number(2),
salary number(10),
location char(10),
constraint emp_id_pk primary key(id)
);
SQL PRIMARY KEY Constraint on ALTER TABLE
Add Primary Key without Constraint:
alter table employee
add primary key (id);
Add Primary Key with Constraint:
alter table employee
add constraint p_k_e_id primary key(id);
To DROP a PRIMARY KEY Constraint
alter table employee
drop constraint p_k_e_id;
SQL Foreign key or Referential Integrity
This constraint identifies any column referencing the PRIMARY KEY in another table. It
establishes a relationship between two columns in the same table or between different
tables. For a column to be defined as a Foreign Key, it should be a defined as a Primary Key
in the table which it is referring. One or more columns can be defined as Foreign key.
Foreign Key at column level with constraint:
create table employee
(id number(5) constraint e_id_pk primary key,
name char(20),
dept char(20),
age number(10)
);
create table company
(c_id number(2) primary key,
c_name char(20),
id number(2) constraint c_e_id references employee(id)
);
Foreign Key at column level without constraint:
create table employee
(id number(5) primary key,
name char(20),
dept char(20),
age number(10)
);
create table company
(c_id number(2) primary key,
c_name char(20),
id number(2)references employee(id)
);
Table Column Data Type Length Precision Scale Primary Key Nullable Default Comment
EMPLOYEE32 ID Number - 5 0 1 - - -
NAME Char 20 - - - - -
DEPT Char 20 - - - - -
AGE Number - 10 0 - - -
Foreign Key at table level:
create table employee
(id number(5),
name char(20),
dept char(20),
age number(10),
constraint e_id primary key(id)
);
create table company
(c_id number(2),
c_name char(20),
id number(2),
constraint c_c_id primary key(c_id),
constraint c_e_id foreign key(id) references employee(id)
);
SQL FOREIGN KEY Constraint on ALTER TABLE
Add Foreign Key without constraint:
alter table company
add foreign key (order_id)
references orders(order_id);
Add Foreign Key with constraint:
alter table company
add constraint fk_o_id
foreign key (order_id)
references orders(order_id);
To DROP a FOREIGN KEY Constraint
alter table company
drop constraint fk_o_id;
SQL CHECK Constraint
The CHECK constraint is used to limit the value range that can be placed in a column.
If you define a CHECK constraint on a single column it allows only certain values for this
column. If you define a CHECK constraint on a table it can limit the values in certain columns
based on values in other columns in the row.
Column Level SQL CHECK Constraint on CREATE TABLE without constraint:
create table employee
(id number(5) primary key,
name char(20),
dept char(10),
age number(2),
gender char(1) check (gender in ('M','F')),
salary number(10),
location char(10)
);
Column Level SQL CHECK Constraint on CREATE TABLE with constraint:
create table employee
(id number(5) primary key,
name char(20),
dept char(10),
age number(2),
gender char(1) constraint c_e_id check (gender in ('M','F')),
salary number(10),
location char(10)
);
Table Level SQL CHECK Constraint on CREATE TABLE with constraint:
create table employee
(id number(5) primary key,
name char(20),
dept char(10),
age number(2),
gender char(1),salary number(10),
location char(10),
constraint c_e_id check (gender in ('M','F'))
);
SQL CHECK Constraint on ALTER TABLE
Without Constraint:
alter table employee
add check (id>0);
Or
Check on multiple columns:
alter table employee
add check (id>0 and gender='M');
With Constraint:
alter table employee
add constraint chk_emp check (id>0 and gender='M');
To DROP a CHECK Constraint
alter table employee
drop constraint chk_emp;
SQL DEFAULT Constraint
The DEFAULT constraint is used to insert a default value into a column.
The default value will be added to all new records, if no other value is specified.
SQL DEFAULT Constraint on CREATE TABLE:
create table person_details
(p_id number not null,
name char(20),
address varchar(200),
city char(255) default 'Gwalior'
);
SQL CREATE INDEX Statement
An index can be created in a table to find data more quickly and efficiently. The users cannot see
the indexes, they are just used to speed up searches/queries. Index in sql is created on existing
tables to retrieve the rows quickly. When there are thousands of records in a table, retrieving
information will take a long time. Therefore indexes are created on columns which are accessed
frequently, so that the information can be retrieved quickly. Indexes can be created on a single
column or a group of columns. When an index is created, it first sorts the data and then it assigns
a ROWID for each row.
Note: Updating a table with indexes takes more time than updating a table without (because the
indexes also need an update). So you should only create indexes on columns (and tables) that
will be frequently searched against.
SQL CREATE INDEX Syntax:
Creates an index on a table. Duplicate values are allowed:
Syntax:
CREATE INDEX index_name
ON table_name (column_name);
Example:
create index person_index on person_details(p_id);
SQL CREATE INDEX on multiple columnsSyntax:
CREATE INDEX index_name
ON table_name (column_name1,column_name2...);
SQL CREATE UNIQUE INDEX Syntax:
Creates a unique index on a table. Duplicate values are not allowed:
Syntax:
CREATE UNIQUE INDEX index_name
ON table_name (column_name);
Example:
create unique index index_person
on person_details (city,address);
In Oracle there are two types of SQL index namely, implicit and explicit.
Implicit Indexes:
They are created when a column is explicity defined with PRIMARY KEY, UNIQUE KEY
Constraint.
Explicit Indexes:
They are created using the "create index.. " syntax.
NOTE:
1) Even though sql indexes are created to access the rows in the table quickly, they slow
down DML operations like INSERT, UPDATE, DELETE on the table, because the indexes
and tables both are updated along when a DML operation is performed. So use indexes only
on columns which are used to search the table frequently.
2) Is is not required to create indexes on table which have less data.
3) In oracle database you can define up to sixteen (16) columns in an INDEX.
SQL DROP
Indexes, tables, and databases can easily be deleted/removed with the DROP statement.
The SQL DROP command is used to remove an object from the database. If you drop a table, all
the rows in the table are deleted and the table structure is removed from the database. Once a
table is dropped we cannot get it back, so be careful while using DROP command. When a table
is dropped all the references to the table will not be valid.
The DROP INDEX Statement
Syntax:
DROP INDEX index_name;
Example:
drop index index_person;
The DROP TABLE Statement
Syntax:
DROP TABLE table_name;
Example:
Drop table employee;
SQL TRUNCATE Statement
The SQL TRUNCATE command is used to delete all the rows from the table and free the space
containing the table.
Syntax:
TRUNCATE TABLE table_name;
Example:
truncate table employee;
Difference between DELETE and TRUNCATE Statements:
DELETE Statement: This command deletes only the rows from the table based on the
condition given in the where clause or deletes all the rows from the table if no condition is
specified. But it does not free the space containing the table.
TRUNCATE statement: This command is used to delete all the rows from the table and
free the space containing the table.
SQL ALTER TABLE Statement
The SQL ALTER TABLE command is used to modify the definition (structure) of a table
by modifying the definition of its columns. The ALTER command is used to perform the
following functions.
1) Add, drop, modify table columns
2) Add and drop constraints
3) Enable and Disable constraints
Syntax to add a column:
ALTER TABLE table_name ADD column_name datatype;
Example:
alter table student_details add salary number(5);
Output:
ID FIRST_NAME LAST_NAME AGE SUBJECT GAMES SALARY
1 Pravesh Shrivastava 24 CSE Tennis -
2 Priyanka Ghosh 25 CSE Basketball -
3 Nitin singh 25 CSE Cricket -
4 Akhilesh Kumar 25 CSE Cricket -
Syntax to drop a column:
ALTER TABLE table_name DROP column column_name;
Example:
alter table student_details drop column salary;
Output:
ID FIRST_NAME LAST_NAME AGE SUBJECT GAMES
1 Pravesh Shrivastava 24 CSE Tennis
2 Priyanka Ghosh 25 CSE Basketball
3 Nitin singh 25 CSE Cricket
4 Akhilesh Kumar 25 CSE Cricket
Syntax to modify a column:
ALTER TABLE table_name MODIFY column_name datatype;
Example:
alter table student_details modify salary char(20);
SQL RENAME Command
The SQL RENAME command is used to change the name of the table or a database object.
If you change the object's name any reference to the old name will be affected. You have to
manually change the old name to the new name in every reference.
Syntax:
RENAME old_table_name To new_table_name;
Example:
rename student_details to student_info;
SQL AUTO INCREMENT Field
Auto-increment allows a unique number to be generated when a new record is inserted into a
table. Very often we would like the value of the primary key field to be created automatically
every time a new record is inserted. We would like to create an auto-increment field in a table.
You will have to create an auto-increment field with the sequence object (this object generates a
number sequence).
Use the following CREATE SEQUENCE syntax:
CREATE SEQUENCE seq_name
MINVALUE min_value
START WITH start_value
INCREMENT BY increment_value
CACHE end_value;
Example:
create sequence seq_emp
minvalue 1
start with 1
increment by 1
cache 10;
The code above creates a sequence object called seq_emp, that starts with 1 and will
increment by 1. It will also cache up to 10 values for performance. The cache option specifies
how many sequence values will be stored in memory for faster access.
To insert a new record into the "emp_details" table, we will have to use the nextval
function (this function retrieves the next value from seq_emp sequence):
create table emp_details
(id number(5),
name char(20),
age number(2)
);
insert into emp_details(id,name,age) values(seq_emp.nextval,'Pravesh',25);
SQL CREATE VIEW Statement
In SQL, a view is a virtual table based on the result-set of an SQL statement. A view contains rows
and columns, just like a real table. The fields in a view are fields from one or more real tables in the
database. You can add SQL functions, WHERE, and JOIN statements to a view and present the data as
if the data were coming from one single table.
A view is, in essence, a virtual table. It does not physically exist. Rather, it is created by a query
joining one or more tables.
A VIEW is a virtual table, through which a selective portion of the data from one or more tables
can be seen. Views do not contain data of their own. They are used to restrict access to the
database or to hide data complexity. A view is stored as a SELECT statement in the database.
DML operations on a view like INSERT, UPDATE, DELETE affects the data in the original
table upon which the view is based.
SQL CREATE VIEW Syntax:
CREATE VIEW view_name AS
SELECT columns
FROM table
WHERE predicates;
Example:
create view sup_order2 as
select supplier_id, supplier_name
from suppliers;
Updating a VIEW
You can update a VIEW without dropping it by using the following syntax.
CREATE OR REPLACE VIEW view_name AS
SELECT columns
FROM table
WHERE predicates;
Example:
create or replace view sup_order2 as
select supplier_id,supplier_name
from suppliers;
Dropping a VIEW
The syntax for dropping a VIEW is:
DROP VIEW view_name;
SQL: Data Types
The following is a list of general SQL datatypes that may not be supported by all relational
databases.
Data Type Syntax Explanation (if applicable) Range
Integer integer
Smallint smallint
Numeric numeric(p,s) Where p is a precision value; s is a
scale value. For example,
numeric(6,2) is a number that has 4
digits before the decimal and 2
digits after the decimal.
Precision can
range from 1 to
38.
Decimal decimal(p,s) Where p is a precision value; s is a
scale value.
Where p is the
precision and s
is the scale.
For example,
decimal(3,1) is
a number that
has 2 digits
before the
decimal and 1
digit after the
decimal.
Real real Single-precision floating point
number
double precision double precision Double-precision floating point
number
Float float(p) Where p is a precision value.
Character char(x) Where x is the number of characters
to store. This data type is space
padded to fill the number of
characters specified.
Maximum size
of 2000 bytes.
character varying varchar2(x) Where x is the number of characters
to store. This data type does NOT
space pad.
Maximum size
of 4000 bytes
Bit bit(x) Where x is the number of bits to
store.
bit varying bit varying(x) Where x is the number of bits to
store. The length can vary up to x.
Date date Stores year, month, and day values. A date between
Jan 1, 4712 BC
and Dec 31,
9999 AD.
Time time Stores the hour, minute, and second
values.
Timestamp timestamp Stores year, month, day, hour,
minute, and second values.
fractional
seconds
precision must
be a number
time with time zone time with time zone Exactly the same as time, but also
stores an offset from UTC of the
time specified.
timestamp with time
zone
timestamp with time
zone
Exactly the same as timestamp, but
also stores an offset from UTC of
the time specified.
fractional
seconds
precision must
be a number
between 0 and
9. (default is 6)
year-month interval Contains a year value, a month
value, or both.
day-time interval Contains a day value, an hour
value, a minute value, and/or a
second value.
nchar(size) nchar(x)
Where size is the number of
characters to store. Fixed-length
NLS string Space padded.
Maximum size
of 2000 bytes.
SQL Functions
SQL has many built-in functions for performing calculations on data.
SQL Aggregate Functions:
SQL aggregate functions return a single value, calculated from values in a column.
Useful aggregate functions:
 AVG() - Returns the average value
 COUNT() - Returns the number of rows
 MAX() - Returns the largest value
 MIN() - Returns the smallest value
 SUM() - Returns the sum
SQL Scalar functions:
SQL scalar functions return a single value, based on the input value.
Useful scalar functions:
 UCASE() - Converts a field to upper case
 LCASE() - Converts a field to lower case
 MID() - Extract characters from a text field
 LEN() - Returns the length of a text field
 ROUND() - Rounds a numeric field to the number of decimals specified
 NOW() - Returns the current system date and time
 FORMAT() - Formats how a field is to be displayed
SQL AVG() Function
SQL AVG(): This function is used to get the average value of a numeric column.
SQL AVG() Syntax:
SELECT AVG(column_name) FROM table_name;
Example:
select avg(age) from student_details;
Output:
AVG( AGE)
24.75
SQL COUNT() Function
This function returns the number of rows in the table that satisfies the condition specified in the
WHERE condition. If the WHERE condition is not specified, then the query returns the total
number of rows in the table.
SQL COUNT(column_name) Syntax:
The COUNT(column_name) function returns the number of values (NULL values will not be
counted) of the specified column.
SELECT COUNT(column_name) FROM table_name;
Example:
select count(subject) from student_details;
Output:
SQL COUNT(*) Syntax:
The COUNT(*) function returns the number of records in a table:
SELECT COUNT(*) FROM table_name;
Example:
select count(*) from student_details;
Output:
COUNT(SUBJECT)
4
COUNT(*)
4
SQL MAX() Function
The MAX() function returns the largest value of the selected column.
Syntax:
SELECT MAX(column_name) FROM table_name;
Example:
select max(age) from student_details;
Output:
MAX( AGE)
25
SQL MIN() Function
The MIN() function returns the smallest value of the selected column.
Syntax:
SELECT MIN(column_name) FROM table_name;
Example:
select min(first_name) from student_details;
Output:
MIN(FIRST_NAME)
Akhilesh
SQL SUM() Function
The SUM() function returns the total sum of a numeric column.
Syntax:
SELECT SUM(column_name) FROM table_name;
Example:
Select sum(age)FROM student_details;
Output:
SUM( AGE)
99
SQL GROUP BY Clause
The SQL GROUP BY Clause is used along with the group functions to retrieve data grouped
according to one or more columns.
Syntax:
SELECT column_name, aggregate_function(column_name)
FROM table_name
WHERE column_name operator value
GROUP BY column_name;
Example:
select first_name, last_name, sum (age)
from student_details
group by first_name, last_name;
Output:
FIRST_NAME LAST_NAME SUM( AGE)
Akhilesh Kumar 25
Pravesh Shrivastava 24
Priyanka Ghosh 25
Nitin singh 25
SQL HAVING Clause
Having clause is used to filter data based on the group functions. This is similar to WHERE
condition but is used with group functions. Group functions cannot be used in WHERE Clause
but can be used in HAVING clause.
Syntax:
SELECT column_name, aggregate_function(column_name)
FROM table_name
WHERE column_name operator value
GROUP BY column_name
HAVING aggregate_function(column_name) operator value;
Example:
select first_name, sum (age)
from student_details
group BY first_name
having sum(age)> 20;
Output:
FIRST_NAME SUM( AGE)
Priyanka 25
Nitin 25
Akhilesh 25
Pravesh 24
SQL UPPER() Function
The UPPER() function converts the value of a field to uppercase.
Syntax:
SELECT UPPER(column_name) FROM table_name;
Example:
select upper(last_name) from student_details;
Output:
UPPER(LAST_NAME)
SHRIVASTAVA
GHOSH
SINGH
KUMAR
SQL LOWER() Function
The LOWER() function converts the value of a field to lowercase.
Syntax:
SELECT LOWER(column_name) FROM table_name;
Example:
select lower(last_name) from student_details;
Output:
LOWER(LAST_NAME)
shrivastava
ghosh
singh
kumar
SQL LENGTH() Function
The LENGTH() function returns the length of the value in a text field.
Syntax:
SELECT LENGTH(column_name) FROM table_name;
Example:
select length(first_name) from student_details;
Output:
LENGTH(FIRST_NAME)
20
20
20
20
SQL ROUND() Function
The ROUND() function is used to round a numeric field to the number of decimals specified.
Syntax:
SELECT ROUND(column_name,decimals) FROM table_name;
Parameter Description
column_name Required. The field to round.
Decimals Required. Specifies the number of decimals to be returned.
Example:
select first_name, round(age,0) from student_details;
Output:
FIRST_NAME ROUND( AGE,0)
Pravesh 24
Priyanka 25
Nitin 25
Akhilesh 25
SQL EXISTS Condition
The EXISTS condition is considered "to be met" if the subquery returns at least one row.
Syntax:
SELECT columns
FROM tables
WHERE EXISTS ( subquery );
The EXISTS condition can be used in any valid SQL statement - select, insert, update, or delete.
Table: student_details
ID S_F_NAME S_L_NAME S_SUB
1 Pravesh Shrivastava CSE
2 Nitin Singh CSE
3 Akhilesh Kumar CSE
4 Santosh Gupta Arts
5 Ranjita Kapoor BSC
Table: employee
E_ID E_NAME E_DEPT
1 Bindu HRM
2 Priyanka HRM
3 Abhishek Networking
Example:
select * from student_details
where exists
(select * from employee
where student_details.id = employee.e_id);
Output:
ID S_F_NAME S_L_NAME S_SUB
1 Pravesh Shrivastava CSE
2 Nitin Singh CSE
3 Akhilesh Kumar CSE
This select statement will return all records from the student_details table where there is at least
one record in the employee table with the same datatype.
Exists with Delete
Example:
delete from student_details
where exists
(select * from employee
where student_details.id = employee.e_id);
Output:
ID S_F_NAME S_L_NAME S_SUB
4 Santosh Gupta Arts
5 Ranjita Kapoor BSC
Exists with Update
Example:
update student_details
set s_f_name =( select e_name from employee
where student_details.id = employee.e_id)
where exists
(select e_name from employee
where employee.e_id = student_details.id);
Output:
ID S_F_NAME S_L_NAME S_SUB
1 Bindu Shrivastava CSE
2 Priyanka Singh CSE
4 Santosh Gupta Arts
5 Ranjita Kapoor BSC
not Exists Condition
Example:
select * from student_details
where not exists
(select * from employee
Where student_details.id = employee.e_id);
Output:
ID S_F_NAME S_L_NAME S_SUB
5 Ranjita Kapoor BSC
4 Santosh Gupta Arts
Not Exists with Delete
Example:
delete from student_details
where not exists
(select * from employee
where student_details.id = employee.e_id);
Output:
ID S_F_NAME S_L_NAME S_SUB
1 Pravesh Shrivastava CSE
2 Nitin Singh CSE
3 Akhilesh Kumar CSE
Not Exists with Update Statement
Example:
update student_details
set s_f_name = (select e_name from employee
where student_details.id = employee.e_id)
where not exists
(select e_name from employee
where employee.e_id = student_details.id);
Output:
ID S_F_NAME S_L_NAME S_SUB
1 Pravesh Shrivastava CSE
2 Nitin Singh CSE
3 Akhilesh Kumar CSE
4 - Gupta Arts
5 - Kapoor BSC
SQL INTERSECT Query
The INTERSECT query allows you to return the results of 2 or more "select" queries. However,
it only returns the rows selected by all queries. If a record exists in one query and not in the
other, it will be omitted from the INTERSECT results. Each SQL statement within the
INTERSECT query must have the same number of fields in the result sets with similar data
types.
Syntax:
SELECT field1, field2, . field_n
from TABLE1
INTERSECT
SELECT field1, field2, . field_n
from TABLE2;
Example:
select supplier_id
from suppliers
intersect
select supplier_id
from orders;
Output:
Example: With ORDER BY Clause:
select supplier_id
from suppliers
where supplier_id > 1000
intersect
select order_id
from orders
where order_id > 1000
ORDER BY 1;
Output:
SUPPLIER_ID
1000
1001
1002
SUPPLIER_ID
1001
SQL MINUS Query
The MINUS query returns all rows in the first query that are not returned in the second query.
Each SQL statement within the MINUS query must have the same number of fields in the result
sets with similar data types.
Syntax:
SELECT field1, field2, . field_n
FROM table1
MINUS
SELECT field1, field2, . field_n
FROM tables2;
Example:
select supplier_id from suppliers
minus
select supplier_id from orders;
Output:
no data found
Example: With ORDER BY Clause:
select supplier_id
from suppliers
where supplier_id > 1000
minus
select order_id
from orders
where order_id > 1000
order by 1;
Output:
GRANT & REVOKE COMMNDS
DCL commands are used to enforce database security in a multiple user database environment.
Two types of DCL commands are GRANT and REVOKE. Only Database Administrator or
owner of the database object can provide/remove privileges on a database object.
SUPPLIER_ID
1002
SQL GRANT Command
SQL GRANT is a command used to provide access or privileges on the database objects to the
users.
Syntax:
GRANT privilege_name
ON object_name
TO {user_name |PUBLIC |role_name}
[WITH GRANT OPTION];
 privilege_name is the access right or privilege granted to the user. Some of the
access rights are ALL, EXECUTE, and SELECT.
 object_name is the name of an database object like TABLE, VIEW, STORED
PROC and SEQUENCE.
 user_name is the name of the user to whom an access right is being granted.
 user_name is the name of the user to whom an access right is being granted.
 PUBLIC is used to grant access rights to all users.
 ROLES are a set of privileges grouped together.
 WITH GRANT OPTION allows a user to grant access rights to other users.
Example:
grant select on employee to user1;
This command grants a SELECT permission on employee table to user1. You should use
the WITH GRANT option carefully because for example if you GRANT SELECT privilege on
employee table to user1 using the WITH GRANT option, then user1 can GRANT SELECT
privilege on employee table to another user, such as user2 etc. Later, if you REVOKE the
SELECT privilege on employee from user1, still user2 will have SELECT privilege on employee
table.
SQL REVOKE Command
The REVOKE command removes user access rights or privileges to the database objects.
Syntax:
REVOKE privilege_name
ON object_name
FROM {user_name |PUBLIC |role_name};
Example:
REVOKE SELECT ON employee FROM user1;
This command will REVOKE a SELECT privilege on employee table from user1.
When you REVOKE SELECT privilege on a table from a user, the user will not be able to
SELECT data from that table anymore. However, if the user has received SELECT privileges
on that table from more than one users, he/she can SELECT from that table until everyone
who granted the permission revokes it. You cannot REVOKE privileges if they were not
initially granted by you.
Privileges and Roles
Privileges
Privileges define the access rights provided to a user on a database object.
There are two types of privileges:
1) System Privileges: This allows the user to CREATE, ALTER, or DROP database
objects.
2) Object Privileges: This allows the user to EXECUTE, SELECT, INSERT,
UPDATE, or DELETE data from database objects to which the privileges apply.
Few CREATE system privileges are listed below:
System Privileges Description
CREATE object
allows users to create the specified
object in their own schema.
CREATE ANY
object
allows users to create the specified
object in any schema.
The above rules also apply for ALTER and DROP system privileges.
Few of the object privileges are listed below:
Object
Privileges
Description
INSERT allows users to insert rows into a table.
SELECT allows users to select data from a
database object.
UPDATE allows user to update data in a table.
EXECUTE
allows user to execute a stored procedure
or a function.
Roles
Roles are a collection of privileges or access rights. When there are many users in a
database it becomes difficult to grant or revoke privileges to users. Therefore, if you define
roles, you can grant or revoke privileges to users, thereby automatically granting or revoking
privileges. You can either create Roles or use the system roles pre-defined by oracle.
Some of the privileges granted to the system roles are as given below:
System
Role
Privileges Granted to the Role
CONNECT
CREATE TABLE, CREATE VIEW,
CREATE SYNONYM, CREATE
SEQUENCE, CREATE SESSION etc.
RESOURCE
CREATE PROCEDURE, CREATE
SEQUENCE, CREATE TABLE,
CREATE TRIGGER etc. The primary
usage of the RESOURCE role is to
restrict access to database objects.
DBA ALL SYSTEM PRIVILEGES
Creating Roles:
Syntax:
CREATE ROLE role_name
[IDENTIFIED BY password];
Example:
To create a role called "tisting" with password as "pwd", the code will be as
follows:
create role testing
identified by pwd;
We can GRANT or REVOKE privilege to a role as below.
To grant CREATE TABLE privilege to a user by creating a testing role:
First, create a testing Role:
create role testing;
Second, grant a CREATE TABLE privilege to the ROLE testing. You can add
more privileges to the ROLE.
grant create table to testing;
Third, grant the role to a user.
Create the user:
create user user1
identified by pwd;
Grant the Role:
grant testing to user1;
To revoke a CREATE TABLE privilege from testing ROLE, you can write:
revoke create table from testing;
Syntax to drop a role from the database:
DROP ROLE role_name;
Example:
drop role testing;
Oracle Built in Functions
There are two types of functions in Oracle.
1) Single Row Functions: Single row or Scalar functions return a value for every row that
is processed in a query.
2) Group Functions: These functions group the rows of data based on the values returned
by the query. This is discussed in SQL GROUP Functions.
There are four types of single row functions. They are:
1) Numeric Functions: These are functions that accept numeric input and return
numeric values.
2) Character or Text Functions: 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.
What is a DUAL Table in Oracle?
This is a single row and single column dummy table provided by oracle. This is
used to perform mathematical calculations without using a table.
Example:
select * from dual;
Output:
Example:
select 777 * 888 from dual;
Output:
Table: netlink
DUMMY
X
777*888
689976
E_ID E_SALARY E_NAME EMP_CITY
3 10000 Pravesh Bhopal
4 8000 Abhishek Bhopal
5 8000 SONAM Indore
1 18000.5 Nitin Gurgaon
2 18000 Akhilesh Gurgaon
6 8000 Jyotsana Mishra Indore
1) Numeric Functions:
Numeric functions are used to perform operations on numbers. They accept numeric values
as input and return numeric values as output.
Function Name Return Value
ABS (x) Absolute value of the number 'x'.
CEIL (x) Integer value that is Greater than or equal to the number 'x'.
FLOOR (x) Integer value that is Less than or equal to the number 'x'.
TRUNC (x, y) Truncates value of number 'x' up to 'y' decimal places.
ROUND (x, y) Rounded off value of the number 'x' up to the number 'y' decimal places.
select abs(e_salary) from netlink;
Output:
ABS(E_SALARY)
10000
8000
select ceil(e_salary) from netlink;
Output:
select floor(e_salary) from netlink;
Output:
FLOOR(E_SALARY)
10000
8000
18000
18000
select trunc(e_salary,3) from netlink;
Output:
18000.5
18000
CEIL(E_SALARY)
10000
8000
18001
18000
TRUNC(E_SALARY,3)
10000
8000
18000.5
18000
Character or Text Functions
Character or text functions are used to manipulate text strings. They accept strings or
characters as input and can return both character and number values as output.
Function Name Return Value
INITCAP (string_value) All the letters in 'string_value' is converted to mixed case.
LTRIM (string_value,
trim_text)
All occurrences of 'trim_text' is removed from the left
of 'string_value'.
RTRIM (string_value,
trim_text)
All occurrences of 'trim_text' is removed from the right
of'string_value' .
TRIM (trim_text FROM
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) Number of characters in 'string_value'in returned.
LPAD (string_value, n,
pad_value)
Returns 'string_value' left-padded with'pad_value' . The length of the
whole string will be of 'n' characters.
RPAD (string_value, n,
pad_value)
Returns 'string_value' right-padded with 'pad_value' . The length of
the whole string will be of 'n' characters.
select initcap('Pravesh') from netlink;
Output:
INITCAP('PRAVESH')
Pravesh
Pravesh
Pravesh
Pravesh
Pravesh
Pravesh
select ltrim('Good Morning', 'Good') from emp;
Output:
LTRIM('GOODMORNING','GOOD')
Morning
select rtrim('Good Morning', 'Morning') from emp;
Output:
RTRIM('GOODMORNING','MORNING')
Good
select trim('G' from 'Good Morning') from emp;
Output:
TRIM('G'FROM'GOODMORNING')
ood Morning
select substr('Good Morning', 6, 6) from emp;
Output:
select length('Good Morning') from emp;
Output:
SUBSTR('GOODMORNING',6,6)
Mornin
LENGTH('GOODMORNING')
12
select lpad('Good',6,'*') from emp;
Output:
LPAD('GOOD',6,'*')
**Good
select rpad('Good',9,'*') from emp;
Output:
3) Date Functions
These are functions that take values that are of datatype DATE as input and return values of
datatypes DATE, except for the MONTHS_BETWEEN function, which returns a number as
output.
Function Name Return Value
ADD_MONTHS (date, n) Returns a date value after adding 'n'months to the date 'x'.
MONTHS_BETWEEN (x1,
x2)
Returns the number of months between dates x1 and x2.
NEXT_DAY (x, week_day)
Returns the next date of the 'week_day'on or after the
date 'x' occurs.
LAST_DAY (x)
It is used to determine the number of days remaining in a month
from the date 'x' specified.
SYSDATE Returns the systems current date and time.
NEW_TIME (x, zone1,
zone2)
Returns the date and time in zone2 if date 'x' represents the time
in zone1.
select add_months('7-oct-2010',3) from emp;
RPAD('GOOD',9,'*')
Good*****
Output:
ADD_MONTHS('7-OCT-2010',3)
07-JAN-11
select months_between('7-oct-2010','7-dec-2010') from emp;
Output:
MONTHS_BETWEEN('7-OCT-2010','7-DEC-2010')
-2
select next_day ('7-oct-2010','Wednesday') from emp;
Output:
NEXT_DAY('7-OCT-2010','WEDNESDAY')
13-OCT-10
select last_day('7-oct-2010') from emp;
Output:
LAST_DAY('7-OCT-2010')
31-OCT-10
select new_time('7-oct-2010','gmt','est') from emp;
Output:
NEW_TIME('7-OCT-2010','GMT','EST')
06-OCT-10
3) Conversion Functions
These are functions that help us to convert a value in one form to another form. For Ex: a
null value into an actual value, or a value from one datatype to another datatype like NVL,
TO_CHAR, TO_NUMBER, TO_DATE.
Function Name Return Value
TO_CHAR (x [,y])
Converts Numeric and Date values to a character string value. It cannot
be used for calculations since it is a string value.
TO_DATE (x ,[
date_format])
Converts a valid Numeric and Character values to a Date value. Date is
formatted to the format specified by 'date_format'.
NVL (x, y) If 'x' is NULL, replace it with 'y'. 'x' and 'y'must be of the same datatype.
select to_char(3000,'$9999') from emp;
Output:
select to_char(sysdate,'day,month yyyy') from emp;
TO_CHAR(3000,'$9999')
$3000
Output:
select to_date('01-Jun-2010') from emp;
Output:
select nvl(null,1) from emp;
Output:
Note:
Query to get the number of columns in a table:
select COUNT(*) from dba_tab_columns
where table_name = 'EMPLOYEE';
table_name should be in capital letters.
TO_CHAR(SYSDATE,'DAY,MONTHYYYY')
friday ,october 2010
TO_DATE('01-JUN-2010')
01-JUN-10
NVL(NULL,1)
1
Ad

More Related Content

What's hot (6)

Avinash database
Avinash databaseAvinash database
Avinash database
avibmas
 
Farheen abdul hameed ip project (MY SQL);
Farheen abdul hameed ip project (MY SQL);Farheen abdul hameed ip project (MY SQL);
Farheen abdul hameed ip project (MY SQL);
abdul talha
 
sql statements & joins
sql statements & joinssql statements & joins
sql statements & joins
Safva AP
 
Sql basic things
Sql basic thingsSql basic things
Sql basic things
Nishil Jain
 
Sql server 2016 queries
Sql server 2016 queriesSql server 2016 queries
Sql server 2016 queries
Seyed Ibrahim
 
Module08
Module08Module08
Module08
guest5c8fba1
 
Avinash database
Avinash databaseAvinash database
Avinash database
avibmas
 
Farheen abdul hameed ip project (MY SQL);
Farheen abdul hameed ip project (MY SQL);Farheen abdul hameed ip project (MY SQL);
Farheen abdul hameed ip project (MY SQL);
abdul talha
 
sql statements & joins
sql statements & joinssql statements & joins
sql statements & joins
Safva AP
 
Sql basic things
Sql basic thingsSql basic things
Sql basic things
Nishil Jain
 
Sql server 2016 queries
Sql server 2016 queriesSql server 2016 queries
Sql server 2016 queries
Seyed Ibrahim
 

Viewers also liked (9)

Computer graphics lab manual
Computer graphics lab manualComputer graphics lab manual
Computer graphics lab manual
Ankit Kumar
 
Computer Graphics Programes
Computer Graphics ProgramesComputer Graphics Programes
Computer Graphics Programes
Abhishek Sharma
 
Ds lab manual by s.k.rath
Ds lab manual by s.k.rathDs lab manual by s.k.rath
Ds lab manual by s.k.rath
SANTOSH RATH
 
98788885 ic-lab-maual
98788885 ic-lab-maual98788885 ic-lab-maual
98788885 ic-lab-maual
Jagadeesh Kumar
 
SE Computer, Programming Laboratory(210251) University of Pune
SE Computer, Programming Laboratory(210251) University of PuneSE Computer, Programming Laboratory(210251) University of Pune
SE Computer, Programming Laboratory(210251) University of Pune
Bhavesh Shah
 
Graphics practical lab manual
Graphics practical lab manualGraphics practical lab manual
Graphics practical lab manual
Vivek Kumar Sinha
 
Computer Graphics Lab File C Programs
Computer Graphics Lab File C ProgramsComputer Graphics Lab File C Programs
Computer Graphics Lab File C Programs
Kandarp Tiwari
 
COMPUTER GRAPHICS LAB MANUAL
COMPUTER GRAPHICS LAB MANUALCOMPUTER GRAPHICS LAB MANUAL
COMPUTER GRAPHICS LAB MANUAL
Vivek Kumar Sinha
 
Power Electronics lab manual BE EEE
Power Electronics lab manual BE EEEPower Electronics lab manual BE EEE
Power Electronics lab manual BE EEE
Dr M Muruganandam Masilamani
 
Computer graphics lab manual
Computer graphics lab manualComputer graphics lab manual
Computer graphics lab manual
Ankit Kumar
 
Computer Graphics Programes
Computer Graphics ProgramesComputer Graphics Programes
Computer Graphics Programes
Abhishek Sharma
 
Ds lab manual by s.k.rath
Ds lab manual by s.k.rathDs lab manual by s.k.rath
Ds lab manual by s.k.rath
SANTOSH RATH
 
SE Computer, Programming Laboratory(210251) University of Pune
SE Computer, Programming Laboratory(210251) University of PuneSE Computer, Programming Laboratory(210251) University of Pune
SE Computer, Programming Laboratory(210251) University of Pune
Bhavesh Shah
 
Graphics practical lab manual
Graphics practical lab manualGraphics practical lab manual
Graphics practical lab manual
Vivek Kumar Sinha
 
Computer Graphics Lab File C Programs
Computer Graphics Lab File C ProgramsComputer Graphics Lab File C Programs
Computer Graphics Lab File C Programs
Kandarp Tiwari
 
COMPUTER GRAPHICS LAB MANUAL
COMPUTER GRAPHICS LAB MANUALCOMPUTER GRAPHICS LAB MANUAL
COMPUTER GRAPHICS LAB MANUAL
Vivek Kumar Sinha
 
Ad

Similar to Oracle Notes (20)

Sql select statement
Sql select statementSql select statement
Sql select statement
Vivek Singh
 
Advanced Database Systems - Presentation 3.pptx
Advanced Database Systems - Presentation 3.pptxAdvanced Database Systems - Presentation 3.pptx
Advanced Database Systems - Presentation 3.pptx
EllenGracePorras
 
Chapter – 6 SQL Lab Tutorial.pdf
Chapter – 6 SQL Lab Tutorial.pdfChapter – 6 SQL Lab Tutorial.pdf
Chapter – 6 SQL Lab Tutorial.pdf
TamiratDejene1
 
Data Manipulation Language.pptx
Data Manipulation Language.pptxData Manipulation Language.pptx
Data Manipulation Language.pptx
EllenGracePorras
 
Complete SQL Tutorial In Hindi By Rishabh Mishra.pdf
Complete SQL Tutorial In Hindi By Rishabh Mishra.pdfComplete SQL Tutorial In Hindi By Rishabh Mishra.pdf
Complete SQL Tutorial In Hindi By Rishabh Mishra.pdf
ssuserb5bb0e
 
Lab
LabLab
Lab
neelam_rawat
 
SQL. It education ppt for reference sql process coding
SQL. It education ppt for reference  sql process codingSQL. It education ppt for reference  sql process coding
SQL. It education ppt for reference sql process coding
aditipandey498628
 
Sql – Structured Query Language
Sql – Structured Query LanguageSql – Structured Query Language
Sql – Structured Query Language
pandey3045_bit
 
Complete SQL Tutorial In Hindi By Rishabh Mishra (Basic to Advance).pdf
Complete SQL Tutorial In Hindi By Rishabh Mishra (Basic to Advance).pdfComplete SQL Tutorial In Hindi By Rishabh Mishra (Basic to Advance).pdf
Complete SQL Tutorial In Hindi By Rishabh Mishra (Basic to Advance).pdf
PreetiKushwah6
 
SQL command for daily use ddl dml dcl dql
SQL command for daily use ddl dml dcl dqlSQL command for daily use ddl dml dcl dql
SQL command for daily use ddl dml dcl dql
kashyapdaksh29
 
SQL-Tutorial.P1241112567Pczwq.powerpoint.pptx
SQL-Tutorial.P1241112567Pczwq.powerpoint.pptxSQL-Tutorial.P1241112567Pczwq.powerpoint.pptx
SQL-Tutorial.P1241112567Pczwq.powerpoint.pptx
SabrinaShanta2
 
SQL-Tutorial.P1241112567Pczwq.powerpoint.pptx
SQL-Tutorial.P1241112567Pczwq.powerpoint.pptxSQL-Tutorial.P1241112567Pczwq.powerpoint.pptx
SQL-Tutorial.P1241112567Pczwq.powerpoint.pptx
SaiMiryala1
 
Its about a sql topic for basic structured query language
Its about a sql topic for basic structured query languageIts about a sql topic for basic structured query language
Its about a sql topic for basic structured query language
IMsKanchanaI
 
SQL-Tutorial.P1241112567Pczwq.powerpoint.pptx
SQL-Tutorial.P1241112567Pczwq.powerpoint.pptxSQL-Tutorial.P1241112567Pczwq.powerpoint.pptx
SQL-Tutorial.P1241112567Pczwq.powerpoint.pptx
BhupendraShahi6
 
lect 2.pptx
lect 2.pptxlect 2.pptx
lect 2.pptx
HermanGaming
 
How did i steal your database CSCamp2011
How did i steal your database CSCamp2011How did i steal your database CSCamp2011
How did i steal your database CSCamp2011
Mostafa Siraj
 
Sql Commands_Dr.R.Shalini.ppt
Sql Commands_Dr.R.Shalini.pptSql Commands_Dr.R.Shalini.ppt
Sql Commands_Dr.R.Shalini.ppt
DrRShaliniVISTAS
 
IT Management (Information Technology Management) refers to the administratio...
IT Management (Information Technology Management) refers to the administratio...IT Management (Information Technology Management) refers to the administratio...
IT Management (Information Technology Management) refers to the administratio...
cadagjohnaron
 
Lab1 select statement
Lab1 select statementLab1 select statement
Lab1 select statement
Balqees Al.Mubarak
 
sql_data.pdf
sql_data.pdfsql_data.pdf
sql_data.pdf
VandanaGoyal21
 
Sql select statement
Sql select statementSql select statement
Sql select statement
Vivek Singh
 
Advanced Database Systems - Presentation 3.pptx
Advanced Database Systems - Presentation 3.pptxAdvanced Database Systems - Presentation 3.pptx
Advanced Database Systems - Presentation 3.pptx
EllenGracePorras
 
Chapter – 6 SQL Lab Tutorial.pdf
Chapter – 6 SQL Lab Tutorial.pdfChapter – 6 SQL Lab Tutorial.pdf
Chapter – 6 SQL Lab Tutorial.pdf
TamiratDejene1
 
Data Manipulation Language.pptx
Data Manipulation Language.pptxData Manipulation Language.pptx
Data Manipulation Language.pptx
EllenGracePorras
 
Complete SQL Tutorial In Hindi By Rishabh Mishra.pdf
Complete SQL Tutorial In Hindi By Rishabh Mishra.pdfComplete SQL Tutorial In Hindi By Rishabh Mishra.pdf
Complete SQL Tutorial In Hindi By Rishabh Mishra.pdf
ssuserb5bb0e
 
SQL. It education ppt for reference sql process coding
SQL. It education ppt for reference  sql process codingSQL. It education ppt for reference  sql process coding
SQL. It education ppt for reference sql process coding
aditipandey498628
 
Sql – Structured Query Language
Sql – Structured Query LanguageSql – Structured Query Language
Sql – Structured Query Language
pandey3045_bit
 
Complete SQL Tutorial In Hindi By Rishabh Mishra (Basic to Advance).pdf
Complete SQL Tutorial In Hindi By Rishabh Mishra (Basic to Advance).pdfComplete SQL Tutorial In Hindi By Rishabh Mishra (Basic to Advance).pdf
Complete SQL Tutorial In Hindi By Rishabh Mishra (Basic to Advance).pdf
PreetiKushwah6
 
SQL command for daily use ddl dml dcl dql
SQL command for daily use ddl dml dcl dqlSQL command for daily use ddl dml dcl dql
SQL command for daily use ddl dml dcl dql
kashyapdaksh29
 
SQL-Tutorial.P1241112567Pczwq.powerpoint.pptx
SQL-Tutorial.P1241112567Pczwq.powerpoint.pptxSQL-Tutorial.P1241112567Pczwq.powerpoint.pptx
SQL-Tutorial.P1241112567Pczwq.powerpoint.pptx
SabrinaShanta2
 
SQL-Tutorial.P1241112567Pczwq.powerpoint.pptx
SQL-Tutorial.P1241112567Pczwq.powerpoint.pptxSQL-Tutorial.P1241112567Pczwq.powerpoint.pptx
SQL-Tutorial.P1241112567Pczwq.powerpoint.pptx
SaiMiryala1
 
Its about a sql topic for basic structured query language
Its about a sql topic for basic structured query languageIts about a sql topic for basic structured query language
Its about a sql topic for basic structured query language
IMsKanchanaI
 
SQL-Tutorial.P1241112567Pczwq.powerpoint.pptx
SQL-Tutorial.P1241112567Pczwq.powerpoint.pptxSQL-Tutorial.P1241112567Pczwq.powerpoint.pptx
SQL-Tutorial.P1241112567Pczwq.powerpoint.pptx
BhupendraShahi6
 
How did i steal your database CSCamp2011
How did i steal your database CSCamp2011How did i steal your database CSCamp2011
How did i steal your database CSCamp2011
Mostafa Siraj
 
Sql Commands_Dr.R.Shalini.ppt
Sql Commands_Dr.R.Shalini.pptSql Commands_Dr.R.Shalini.ppt
Sql Commands_Dr.R.Shalini.ppt
DrRShaliniVISTAS
 
IT Management (Information Technology Management) refers to the administratio...
IT Management (Information Technology Management) refers to the administratio...IT Management (Information Technology Management) refers to the administratio...
IT Management (Information Technology Management) refers to the administratio...
cadagjohnaron
 
Ad

Recently uploaded (20)

2541William_McCollough_DigitalDetox.docx
2541William_McCollough_DigitalDetox.docx2541William_McCollough_DigitalDetox.docx
2541William_McCollough_DigitalDetox.docx
contactwilliamm2546
 
LDMMIA Reiki Master Spring 2025 Mini Updates
LDMMIA Reiki Master Spring 2025 Mini UpdatesLDMMIA Reiki Master Spring 2025 Mini Updates
LDMMIA Reiki Master Spring 2025 Mini Updates
LDM Mia eStudios
 
Ultimate VMware 2V0-11.25 Exam Dumps for Exam Success
Ultimate VMware 2V0-11.25 Exam Dumps for Exam SuccessUltimate VMware 2V0-11.25 Exam Dumps for Exam Success
Ultimate VMware 2V0-11.25 Exam Dumps for Exam Success
Mark Soia
 
Michelle Rumley & Mairéad Mooney, Boole Library, University College Cork. Tra...
Michelle Rumley & Mairéad Mooney, Boole Library, University College Cork. Tra...Michelle Rumley & Mairéad Mooney, Boole Library, University College Cork. Tra...
Michelle Rumley & Mairéad Mooney, Boole Library, University College Cork. Tra...
Library Association of Ireland
 
Unit 6_Introduction_Phishing_Password Cracking.pdf
Unit 6_Introduction_Phishing_Password Cracking.pdfUnit 6_Introduction_Phishing_Password Cracking.pdf
Unit 6_Introduction_Phishing_Password Cracking.pdf
KanchanPatil34
 
Social Problem-Unemployment .pptx notes for Physiotherapy Students
Social Problem-Unemployment .pptx notes for Physiotherapy StudentsSocial Problem-Unemployment .pptx notes for Physiotherapy Students
Social Problem-Unemployment .pptx notes for Physiotherapy Students
DrNidhiAgarwal
 
Handling Multiple Choice Responses: Fortune Effiong.pptx
Handling Multiple Choice Responses: Fortune Effiong.pptxHandling Multiple Choice Responses: Fortune Effiong.pptx
Handling Multiple Choice Responses: Fortune Effiong.pptx
AuthorAIDNationalRes
 
Anti-Depressants pharmacology 1slide.pptx
Anti-Depressants pharmacology 1slide.pptxAnti-Depressants pharmacology 1slide.pptx
Anti-Depressants pharmacology 1slide.pptx
Mayuri Chavan
 
Marie Boran Special Collections Librarian Hardiman Library, University of Gal...
Marie Boran Special Collections Librarian Hardiman Library, University of Gal...Marie Boran Special Collections Librarian Hardiman Library, University of Gal...
Marie Boran Special Collections Librarian Hardiman Library, University of Gal...
Library Association of Ireland
 
SPRING FESTIVITIES - UK AND USA -
SPRING FESTIVITIES - UK AND USA            -SPRING FESTIVITIES - UK AND USA            -
SPRING FESTIVITIES - UK AND USA -
Colégio Santa Teresinha
 
pulse ppt.pptx Types of pulse , characteristics of pulse , Alteration of pulse
pulse  ppt.pptx Types of pulse , characteristics of pulse , Alteration of pulsepulse  ppt.pptx Types of pulse , characteristics of pulse , Alteration of pulse
pulse ppt.pptx Types of pulse , characteristics of pulse , Alteration of pulse
sushreesangita003
 
Operations Management (Dr. Abdulfatah Salem).pdf
Operations Management (Dr. Abdulfatah Salem).pdfOperations Management (Dr. Abdulfatah Salem).pdf
Operations Management (Dr. Abdulfatah Salem).pdf
Arab Academy for Science, Technology and Maritime Transport
 
How to track Cost and Revenue using Analytic Accounts in odoo Accounting, App...
How to track Cost and Revenue using Analytic Accounts in odoo Accounting, App...How to track Cost and Revenue using Analytic Accounts in odoo Accounting, App...
How to track Cost and Revenue using Analytic Accounts in odoo Accounting, App...
Celine George
 
Metamorphosis: Life's Transformative Journey
Metamorphosis: Life's Transformative JourneyMetamorphosis: Life's Transformative Journey
Metamorphosis: Life's Transformative Journey
Arshad Shaikh
 
New Microsoft PowerPoint Presentation.pptx
New Microsoft PowerPoint Presentation.pptxNew Microsoft PowerPoint Presentation.pptx
New Microsoft PowerPoint Presentation.pptx
milanasargsyan5
 
World war-1(Causes & impacts at a glance) PPT by Simanchala Sarab(BABed,sem-4...
World war-1(Causes & impacts at a glance) PPT by Simanchala Sarab(BABed,sem-4...World war-1(Causes & impacts at a glance) PPT by Simanchala Sarab(BABed,sem-4...
World war-1(Causes & impacts at a glance) PPT by Simanchala Sarab(BABed,sem-4...
larencebapu132
 
Biophysics Chapter 3 Methods of Studying Macromolecules.pdf
Biophysics Chapter 3 Methods of Studying Macromolecules.pdfBiophysics Chapter 3 Methods of Studying Macromolecules.pdf
Biophysics Chapter 3 Methods of Studying Macromolecules.pdf
PKLI-Institute of Nursing and Allied Health Sciences Lahore , Pakistan.
 
GDGLSPGCOER - Git and GitHub Workshop.pptx
GDGLSPGCOER - Git and GitHub Workshop.pptxGDGLSPGCOER - Git and GitHub Workshop.pptx
GDGLSPGCOER - Git and GitHub Workshop.pptx
azeenhodekar
 
Presentation of the MIPLM subject matter expert Erdem Kaya
Presentation of the MIPLM subject matter expert Erdem KayaPresentation of the MIPLM subject matter expert Erdem Kaya
Presentation of the MIPLM subject matter expert Erdem Kaya
MIPLM
 
Odoo Inventory Rules and Routes v17 - Odoo Slides
Odoo Inventory Rules and Routes v17 - Odoo SlidesOdoo Inventory Rules and Routes v17 - Odoo Slides
Odoo Inventory Rules and Routes v17 - Odoo Slides
Celine George
 
2541William_McCollough_DigitalDetox.docx
2541William_McCollough_DigitalDetox.docx2541William_McCollough_DigitalDetox.docx
2541William_McCollough_DigitalDetox.docx
contactwilliamm2546
 
LDMMIA Reiki Master Spring 2025 Mini Updates
LDMMIA Reiki Master Spring 2025 Mini UpdatesLDMMIA Reiki Master Spring 2025 Mini Updates
LDMMIA Reiki Master Spring 2025 Mini Updates
LDM Mia eStudios
 
Ultimate VMware 2V0-11.25 Exam Dumps for Exam Success
Ultimate VMware 2V0-11.25 Exam Dumps for Exam SuccessUltimate VMware 2V0-11.25 Exam Dumps for Exam Success
Ultimate VMware 2V0-11.25 Exam Dumps for Exam Success
Mark Soia
 
Michelle Rumley & Mairéad Mooney, Boole Library, University College Cork. Tra...
Michelle Rumley & Mairéad Mooney, Boole Library, University College Cork. Tra...Michelle Rumley & Mairéad Mooney, Boole Library, University College Cork. Tra...
Michelle Rumley & Mairéad Mooney, Boole Library, University College Cork. Tra...
Library Association of Ireland
 
Unit 6_Introduction_Phishing_Password Cracking.pdf
Unit 6_Introduction_Phishing_Password Cracking.pdfUnit 6_Introduction_Phishing_Password Cracking.pdf
Unit 6_Introduction_Phishing_Password Cracking.pdf
KanchanPatil34
 
Social Problem-Unemployment .pptx notes for Physiotherapy Students
Social Problem-Unemployment .pptx notes for Physiotherapy StudentsSocial Problem-Unemployment .pptx notes for Physiotherapy Students
Social Problem-Unemployment .pptx notes for Physiotherapy Students
DrNidhiAgarwal
 
Handling Multiple Choice Responses: Fortune Effiong.pptx
Handling Multiple Choice Responses: Fortune Effiong.pptxHandling Multiple Choice Responses: Fortune Effiong.pptx
Handling Multiple Choice Responses: Fortune Effiong.pptx
AuthorAIDNationalRes
 
Anti-Depressants pharmacology 1slide.pptx
Anti-Depressants pharmacology 1slide.pptxAnti-Depressants pharmacology 1slide.pptx
Anti-Depressants pharmacology 1slide.pptx
Mayuri Chavan
 
Marie Boran Special Collections Librarian Hardiman Library, University of Gal...
Marie Boran Special Collections Librarian Hardiman Library, University of Gal...Marie Boran Special Collections Librarian Hardiman Library, University of Gal...
Marie Boran Special Collections Librarian Hardiman Library, University of Gal...
Library Association of Ireland
 
pulse ppt.pptx Types of pulse , characteristics of pulse , Alteration of pulse
pulse  ppt.pptx Types of pulse , characteristics of pulse , Alteration of pulsepulse  ppt.pptx Types of pulse , characteristics of pulse , Alteration of pulse
pulse ppt.pptx Types of pulse , characteristics of pulse , Alteration of pulse
sushreesangita003
 
How to track Cost and Revenue using Analytic Accounts in odoo Accounting, App...
How to track Cost and Revenue using Analytic Accounts in odoo Accounting, App...How to track Cost and Revenue using Analytic Accounts in odoo Accounting, App...
How to track Cost and Revenue using Analytic Accounts in odoo Accounting, App...
Celine George
 
Metamorphosis: Life's Transformative Journey
Metamorphosis: Life's Transformative JourneyMetamorphosis: Life's Transformative Journey
Metamorphosis: Life's Transformative Journey
Arshad Shaikh
 
New Microsoft PowerPoint Presentation.pptx
New Microsoft PowerPoint Presentation.pptxNew Microsoft PowerPoint Presentation.pptx
New Microsoft PowerPoint Presentation.pptx
milanasargsyan5
 
World war-1(Causes & impacts at a glance) PPT by Simanchala Sarab(BABed,sem-4...
World war-1(Causes & impacts at a glance) PPT by Simanchala Sarab(BABed,sem-4...World war-1(Causes & impacts at a glance) PPT by Simanchala Sarab(BABed,sem-4...
World war-1(Causes & impacts at a glance) PPT by Simanchala Sarab(BABed,sem-4...
larencebapu132
 
GDGLSPGCOER - Git and GitHub Workshop.pptx
GDGLSPGCOER - Git and GitHub Workshop.pptxGDGLSPGCOER - Git and GitHub Workshop.pptx
GDGLSPGCOER - Git and GitHub Workshop.pptx
azeenhodekar
 
Presentation of the MIPLM subject matter expert Erdem Kaya
Presentation of the MIPLM subject matter expert Erdem KayaPresentation of the MIPLM subject matter expert Erdem Kaya
Presentation of the MIPLM subject matter expert Erdem Kaya
MIPLM
 
Odoo Inventory Rules and Routes v17 - Odoo Slides
Odoo Inventory Rules and Routes v17 - Odoo SlidesOdoo Inventory Rules and Routes v17 - Odoo Slides
Odoo Inventory Rules and Routes v17 - Odoo Slides
Celine George
 

Oracle Notes

  • 1. SQL SQL stands for "Structured Query Language". It is used by Relational DataBase technologies such as Oracle, Microsoft Access, and Sybase, among others. SQL lets you access and manipulate databases. SQL is an ANSI (American National Standards Institute) standard. SQL can execute queries against a database. SQL can retrieve data from a database. SQL can insert records in a database. SQL can update records in a database. SQL can delete records from a database. SQL can create new databases. SQL can create new tables in a database. SQL can create stored procedures in a database. SQL can create views in a database. SQL can set permissions on tables, procedures, and views. Although SQL is an ANSI (American National Standards Institute) standard, there are many different versions of the SQL language. However, to be compliant with the ANSI standard, they all support at least the major commands (such as SELECT, UPDATE, DELETE, INSERT, WHERE) in a similar manner. Note: Most of the SQL database programs also have their own proprietary extensions in addition to the SQL standard! sequel – (Structured English Query Language)”.
  • 2. RDBMS RDBMS stands for Relational Database Management System. RDBMS is the basis for SQL, and for all modern database systems like MS SQL Server, IBM DB2, Oracle, MySQL, and Microsoft Access. The data in RDBMS is stored in database objects called tables. A table is a collections of related data entries and it consists of columns and rows.
  • 3. SQL Commands SQL commands are instructions used to communicate with the database to perform specific task that work with data. SQL commands can be used not only for searching the database but also to perform various other functions like, for example, you can create tables, add data to tables, or modify data, drop the table, set permissions for users. SQL commands are grouped into four major categories depending on their functionality:  Data Definition Language (DDL) - These SQL commands are used for creating, modifying, and dropping the structure of database objects. The commands are CREATE, ALTER, DROP, RENAME, and TRUNCATE.  Data Manipulation Language (DML) - These SQL commands are used for storing, retrieving, modifying, and deleting data. These commands are SELECT, INSERT, UPDATE, and DELETE.  Transaction Control Language (TCL) - These SQL commands are used for managing changes affecting the data. These commands are COMMIT, ROLLBACK, and SAVEPOINT.  Data Control Language (DCL) - These SQL commands are used for providing security to database objects. These commands are GRANT and REVOKE.
  • 4. SQL SELECT Statement The most commonly used SQL command is SELECT statement. The SQL SELECT statement is used to query or retrieve data from a table in the database. A query may retrieve information from specified columns or from all of the columns in the table. To create a simple SQL SELECT Statement, you must specify the column(s) name and the table name. The whole query is called SQL SELECT Statement. Syntax of SQL SELECT Statement: SELECT column_list FROM table_name [WHERE Clause] [GROUP BY Clause] [HAVING Clause] [ORDER BY Clause]; DataBase Table “student_details”: ID FIRST_NAME LAST_NAME AGE SUBJECT GAMES 1 Pravesh Shrivastava 24 CSE Football 2 Nitin Singh 25 CSE Cricket 3 Akhilesh Kumar 25 CSE Cricket 4 Abhishek Tripathi 26 CSE Cricket 5 Priyanka Ghosh 25 CSE Basketball To select the First Name of all the students the query would be like: select first_name from student_details; Output: FIRST_NAME Pravesh Priyanka Nitin Akhilesh Abhishek You can also retrieve data from more than one column. For example, to select First Name and Last Name of all the students. select first_name, last_name from student_details;
  • 5. Output: FIRST_NAME LAST_NAME Pravesh Shrivastava Priyanka Ghosh Nitin singh Akhilesh Kumar If we want to display the First and Last Name of a student combined together, the SQL Select Statement would be like: select first_name ||’’|| last_name from student_details; Output: FIRST_NAME||''||LAST_NAME Pravesh Shrivastava Nitin Singh Akhilesh Kumar Abhishek Tripathi Priyanka Ghosh You can also provide Alias as below. select first_name ||’’|| last_name as Name from student_details; Output: NAME Pravesh Shrivastava Nitin Singh Akhilesh Kumar Abhishek Tripathi Priyanka Ghosh
  • 6. SQL DISTINCT STATEMENT In a table, some of the columns may contain duplicate values. This is not a problem, however, sometimes you will want to list only the different (distinct) values in a table. The DISTINCT keyword can be used to return only distinct (different) values. SQL SELECT DISTINCT Syntax SELECT DISTINCT column_name(s) FROM table_name To select all distinct subject names from student_details table, the query would be: select distinct subject from student_details; Output: SUBJECT CSE
  • 7. SQL WHERE Clause The WHERE Clause is used when you want to retrieve specific information from a table excluding other irrelevant data. So SQL offers a feature called WHERE clause, which we can use to restrict the data that is retrieved. The condition you provide in the WHERE clause filters the rows retrieved from the table and gives you only those rows which you expected to see. WHERE clause can be used along with SELECT, DELETE, UPDATE statements. Syntax of SQL WHERE Clause: SELECT column_list FROM table_name WHERE condition; To find the first name of a student with id 1, the query would be like: select first_name from student_details where id=1; Output: FIRST_NAME Pravesh
  • 8. SQL Operators There are two type of Operators, namely Comparison Operators and Logical Operators. These operators are used mainly in the WHERE clause, HAVING clause to filter the data to be selected. Comparison Operators: Comparison operators are used to compare the column data with specific values in a condition. Comparison Operators are also used along with the SELECT statement to filter data based on specific conditions. The below table describes each comparison operator. Comparison Operators Description = equal to <>, != is not equal to < less than > greater than >= greater than or equal to <= less than or equal to Logical Operators: There are three Logical Operators namely, AND, OR, and NOT. These operators compare two conditions at a time to determine whether a row can be selected for the output. When retrieving data using a SELECT statement, you can use logical operators in the WHERE clause, which allows you to combine more than one condition. Logical Operators Description OR For the row to be selected at least one of the conditions must be true. AND For a row to be selected all the specified conditions must be true. NOT For a row to be selected the specified condition must be false.
  • 9. "OR" Logical Operator: If you want to select rows that satisfy at least one of the given conditions, you can use the logical operator, OR. For example: if you want to find the names of students who are studying either CSE or ECE, the query would be like, SELECT first_name, last_name, subject FROM student_details WHERE subject = 'CSE' OR subject = 'ECE'; Output: FIRST_NAME LAST_NAME SUBJECT Pravesh Shrivastava CSE Nitin Singh CSE Akhilesh Kumar CSE Abhishek Tripathi CSE Priyanka Ghosh CSE "AND" Logical Operator: If you want to select rows that must satisfy all the given conditions, you can use the logical operator, AND. For Example: To find the names of the students between the age 24 to 26 years, the query would be like: SELECT first_name, last_name, age FROM student_details WHERE age >= 24 AND age <= 26; Output: FIRST_NAME LAST_NAME AGE Pravesh Shrivastava 24 Nitin Singh 25 Akhilesh Kumar 25 Abhishek Tripathi 26 Priyanka Ghosh 25
  • 10. "NOT" Logical Operator: If you want to find rows that do not satisfy a condition, you can use the logical operator, NOT. NOT results in the reverse of a condition. That is, if a condition is satisfied, then the row is not returned. For example: If you want to find out the names of the students who do not play football, the query would be like: SELECT first_name, last_name, games FROM student_details WHERE NOT games = 'Football' Output: FIRST_NAME LAST_NAME GAMES Nitin Singh Cricket Akhilesh Kumar Cricket Abhishek Tripathi Cricket Priyanka Ghosh Basketball Nested Logical Operators: You can use multiple logical operators in an SQL statement. When you combine the logical operators in a SELECT statement, the order in which the statement is processed is 1) NOT 2) AND 3) OR For example: If you want to select the names of the students who age is between 24 and 26 years, or those who do not play football, the SELECT statement would be SELECT first_name, last_name, age, games FROM student_details WHERE age >= 24 AND age <= 26 OR NOT games = 'Football'; Output: FIRST_NAME LAST_NAME AGE GAMES Pravesh Shrivastava 24 Football Nitin Singh 25 Cricket Akhilesh Kumar 25 Cricket Abhishek Tripathi 26 Cricket
  • 11. Priyanka Ghosh 25 Basketball
  • 12. SQL ORDER BY The ORDER BY clause is used in a SELECT statement to sort results either in ascending or descending order. Oracle sorts query results in ascending order by default. Syntax for using SQL ORDER BY clause to sort data is: SELECT column-list FROM table_name [WHERE condition] [ORDER BY [column1, column2, .. columnN] [DESC]; Database Table "student_details": select id,first_name,last_name,age,subject,games from student_details order by id Output: ID FIRST_NAME LAST_NAME AGE SUBJECT GAMES 1 Pravesh Shrivastava 24 CSE Football 2 Nitin Singh 25 CSE Cricket 3 Akhilesh Kumar 25 CSE Cricket 4 Abhishek Tripathi 26 CSE Cricket 5 Priyanka Ghosh 25 CSE Basketball If you want to sort the student_details table by the name and age, the query would be like, SELECT first_name, age FROM student_details ORDER BY first_name, age; Output: FIRST_NAME AGE Abhishek 26 Akhilesh 25 Nitin 25 Pravesh 24 Priyanka 25 NOTE:The columns specified in ORDER BY clause should be one of the columns selected in the SELECT column list. You can represent the columns in the ORDER BY clause by specifying the position of a column in the SELECT list, instead of writing the column name. The above query can also be written as given below, SELECT first_name, age FROM student_details ORDER BY 1, 2;
  • 13. Output: FIRST_NAME AGE Abhishek 26 Akhilesh 25 Nitin 25 Pravesh 24 Priyanka 25 By default, the ORDER BY Clause sorts data in ascending order. If you want to sort the data in descending order, you must explicitly specify it as shown below. SELECT first_name, age FROM student_details ORDER BY first_name, age desc; Output: FIRST_NAME AGE Abhishek 26 Akhilesh 25 Nitin 25 Pravesh 24 Priyanka 25 The above query sorts only the column 'age' in descending order and the column 'first_name' by ascending order. If you want to select both first_name and age in descending order, the query would be as given below. SELECT first_name, age FROM student_details ORDER BY first_name desc, age desc; Output: FIRST_NAME AGE Priyanka 25 Pravesh 24 Nitin 25 Akhilesh 25 Abhishek 26
  • 14. How to use expressions in the ORDER BY Clause? For example: If you want to display student_details first_name, age, and a 20% increase in the age for only those students for whom the percentage increase in age is greater than 30, the SELECT statement can be written as shown below SELECT first_name, age, age*1.2 AS new_age FROM student_details WHERE age*1.2 > 30 ORDER BY new_age DESC; Output: FIRST_NAME AGE NEW_AGE Abhishek 26 31.2 NOTE: Aliases defined in the SELECT Statement can be used in ORDER BY Clause.
  • 15. SQL INSERT Statement The INSERT Statement is used to add new rows of data to a table. We can insert data to a table in two ways, 1) Inserting the data directly to a table. Syntax for SQL INSERT is INSERT INTO TABLE_NAME [ (col1, col2, col3,...colN)] VALUES (value1, value2, value3,...valueN); While inserting a row, if you are adding value for all the columns of the table you need not specify the column(s) name in the sql query. But you need to make sure the order of the values is in the same order as the columns in the table. The sql insert query will be as follows INSERT INTO TABLE_NAME VALUES (value1, value2, value3,...valueN); For Example: If you want to insert a row to the employee table, the query would be like, insert into student_details (id,first_name,last_name,age,subject,games) values(1,'Pravesh','Shrivastava',24,'CSE','Football') Output: ID FIRST_NAME LAST_NAME AGE SUBJECT GAMES 1 Pravesh Shrivastava 24 CSE Football NOTE: When adding a row, only the characters or date values should be enclosed with single quotes. If you are inserting data to all the columns, the column names can be omitted. The above insert statement can also be written as, insert into student_details values (3,’Nitin’,’Singh’,24,’CSE’,’Cricket’); Output: ID FIRST_NAME LAST_NAME AGE SUBJECT GAMES 1 Pravesh Shrivastava 24 CSE Football 2 Priyanka Ghosh 25 CSE Basketball
  • 16. 3 Nitin Singh 24 CSE Cricket Inserting data to a table through a select statement: Syntax for SQL INSERT is: INSERT INTO table_name [(column1, column2, ... columnN)] SELECT column1, column2, ...columnN FROM table_name [WHERE condition]; For Example: To insert a row into the student_details table from emp_net table, the sql insert into query would be like, emp_net table: EMP_ID EMP_NAME 1 Ranjita INSERT INTO student_details (id, first_name) SELECT emp_id, emp_name FROM emp_net; Output: ID FIRST_NAME LAST_NAME AGE SUBJECT GAMES 1 Pravesh Shrivastava 24 CSE Football 2 Priyanka Ghosh 25 CSE Basketball 3 Nitin Singh 24 CSE Cricket 1 Ranjita - - - - If you are inserting data to all the columns, the above insert statement can also be written as, stu_net table: STU_ID STU_F_NAME STU_L_NAME STU_AGE STU_SUB STU_GAMES 4 Akhilesh Kumar 25 CSE Cricket INSERT INTO student_details SELECT * FROM stu_net;
  • 17. Output: NOTE:We have assumed the stu_net table has columns stu_id, stu_f_name, stu_l_name, stu_age, stu_sub, stu_ games the above given order and the same datatype. IMPORTANT NOTE: 1) When adding a new row, you should ensure the datatype of the value and the column matches 2) You follow the integrity constraints, if any, defined for the table. ID FIRST_NAME LAST_NAME AGE SUBJECT GAMES 1 Pravesh Shrivastava 24 CSE Football 2 Priyanka Ghosh 25 CSE Basketball 3 Nitin Singh 24 CSE Cricket 1 Ranjita - - - - 4 Akhilesh Kumar 25 CSE Cricket
  • 18. SQL UPDATE Statement The UPDATE statement is used to update existing records in a table. SQL UPDATE Syntax: UPDATE table_name SET column1=value2, column2=value2,... WHERE some_column=some_value; If we are updating the table student_details where first_name is Ranjita. The query would be like: update student_details set last_name='Kapoor', age=25, subject='BSC',games='Badminton' where first_name='Ranjita'; Output: ID FIRST_NAME LAST_NAME AGE SUBJECT GAMES 1 Pravesh Shrivastava 24 CSE Football 2 Priyanka Ghosh 25 CSE Basketball 3 Nitin Singh 24 CSE Cricket 1 Ranjita Kapoor 25 BSC Badminton 4 Akhilesh Kumar 25 CSE Cricket Note: Notice the WHERE clause in the UPDATE syntax. The WHERE clause specifies which record or records that should be updated. If you omit the WHERE clause, all records will be updated! update student_details set last_name='Kapoor', age=25; Output: ID FIRST_NAME LAST_NAME AGE SUBJECT GAMES 1 Pravesh Kapoor 25 CSE Football 2 Priyanka Kapoor 25 CSE Basketball 3 Nitin Kapoor 25 CSE Cricket 1 Ranjita Kapoor 25 BSC Badminton 4 Akhilesh Kapoor 25 CSE Cricket
  • 19. To change the salaries of all the employees, the query would be, update employee set salary=salary*2; employee table: ID NAME SALARY 1 Pravesh 19000 2 Nitin 19000 3 aaa 500 Output: ID NAME SALARY 1 Pravesh 38000 2 Nitin 38000 3 aaa 1000
  • 20. SQL DELETE Statement The DELETE statement is used to delete records in a table. The DELETE statement is used to delete rows in a table. SQL DELETE Syntax: DELETE FROM table_name WHERE some_column=some_value; If we want to delete the record where first name is Ranjita, the query would be like: delete from student_details where first_name='Ranjita'; Output: Note: Notice the WHERE clause in the DELETE syntax. The WHERE clause specifies which record or records that should be deleted. If you omit the WHERE clause, all records will be deleted! Delete All Rows It is possible to delete all rows in a table without deleting the table. This means that the table structure, attributes, and indexes will be intact: DELETE FROM table_name; or DELETE * FROM table_name; Example: delete from student_details; Or delete * from student_details; Note: Be very careful when deleting records. You cannot undo this statement! ID FIRST_NAME LAST_NAME AGE SUBJECT GAMES 1 Pravesh Shrivastava 24 CSE Tennis 2 Priyanka Ghosh 25 CSE Basketball 3 Nitin singh 25 CSE Cricket 4 Akhilesh Kumar 25 CSE Cricket
  • 21. You may wish to check for the number of rows that will be deleted. You can determine the number of rows that will be deleted by running the following SQL statement before performing the delete. SELECT count(*) FROM student_details WHERE first_name = 'Pravesh'; Output: COUNT(*) 1
  • 22. The ROWNUM Clause The ROWNUM clause is used to specify the number of records to return. The ROWNUM clause can be very useful on large tables with thousands of records. Returning a large number of records can impact on performance. Note: Not all database systems support the TOP clause. Syntax: SELECT column_name(s) FROM table_name WHERE ROWNUM <= number; Example: Now we want to select only the two first records in the table. We use the following SELECT statement: select * from student_details where rownum <=3; Output: ID FIRST_NAME LAST_NAME AGE SUBJECT GAMES 1 Pravesh Shrivastava 24 CSE Tennis 2 Priyanka Ghosh 25 CSE Basketball 3 Nitin singh 25 CSE Cricket
  • 23. SQL LIKE Operator The LIKE operator is used to list all rows in a table whose column values match a specified pattern. It is useful when you want to search rows to match a specific pattern, or when you do not know the entire value. The LIKE condition allows you to use wildcards in the where clause of an SQL statement. This allows you to perform pattern matching. The LIKE condition can be used in any valid SQL statement - select, insert, update, or delete. The patterns that you can choose from are: % allows you to match any string of any length (including zero length). _ allows you to match on a single character. Examples using % wildcard: We are going to try to find all of the person whose first name begins with 'Pr'. select* from student_details where first_name like 'Pr%'; Output: ID FIRST_NAME LAST_NAME AGE SUBJECT GAMES 1 Pravesh Shrivastava 24 CSE Tennis 2 Priyanka Ghosh 25 CSE Basketball You can also using the wildcard multiple times within the same string. For example, In this example, we are looking for all persons whose first name contains the characters 'Pra'. select * from student_details where first_name like '%Pra%'; Output: ID FIRST_NAME LAST_NAME AGE SUBJECT GAMES 1 Pravesh Shrivastava 24 CSE Tennis You could also use the LIKE condition to find persons whose first name does not start with 'P'. For example, select * from student_details where first_name not like 'P%'; By placing the not keyword in front of the LIKE condition, you are able to retrieve all suppliers whose name does not start with 'P'.
  • 24. Output: ID FIRST_NAME LAST_NAME AGE SUBJECT GAMES 3 Nitin singh 25 CSE Cricket 4 Akhilesh Kumar 25 CSE Cricket Examples using _ wildcard: Remember that the _ is looking for only one character. For example, select * from student_details where first_name like 'Pr_yanka%'; Output: ID FIRST_NAME LAST_NAME AGE SUBJECT GAMES 2 Priyanka Ghosh 25 CSE Basketball Examples using Escape Characters: Next, in Oracle, let's say you wanted to search for a % or a _ character in a LIKE condition. You can do this using an Escape character. Please note that you can define an escape character as a single character (length of 1) ONLY. For example, select * from student_details where first_name like '%' escape '!'; This example returns all persons whose first name starts with any of the words and ends in %. For example, it would return a value such as 'Pravesh%'. Output: ID FIRST_NAME LAST_NAME AGE SUBJECT GAMES 1 Pravesh Shrivastava 24 CSE Tennis 2 Priyanka Ghosh 25 CSE Basketball 3 Nitin singh 25 CSE Cricket 4 Akhilesh Kumar 25 CSE Cricket select * from student_details where first_name like 'P%' escape '!'; This example returns all persons whose first name starts with P and ends in _. For example, it would return a value such as 'Pravesh_'.
  • 25. Output: ID FIRST_NAME LAST_NAME AGE SUBJECT GAMES 1 Pravesh Shrivastava 24 CSE Tennis 2 Priyanka Ghosh 25 CSE Basketball
  • 26. SQL Wildcards SQL wildcards can substitute for one or more characters when searching for data in a database. SQL wildcards must be used with the SQL LIKE operator. With SQL, the following wildcards can be used: Wildcard Description % A substitute for zero or more characters _ A substitute for exactly one character [charlist] Any single character in charlist SQL Wildcard Examples Using the % Wildcard: Now we want to select the students whose first names start with "Pr" from the "student_details" table. We use the following SELECT statement: select * from student_details where first_name like 'Pr%'; Output: Next, we want to select the students whose subjects contain the pattern "CSE" from the "student_details" table. We use the following SELECT statement: select * from student_details where subject like '%CSE%'; Output: ID FIRST_NAME LAST_NAME AGE SUBJECT GAMES 1 Pravesh Shrivastava 24 CSE Tennis 2 Priyanka Ghosh 25 CSE Basketball 3 Nitin singh 25 CSE Cricket 4 Akhilesh Kumar 25 CSE Cricket Using the _ Wildcard: Now we want to select the students with the first name that starts with any character, followed by "ravesh" from the "student_details" table. We use the following SELECT statement: select * from student_details where first_name LIKE '_ravesh%'; ID FIRST_NAME LAST_NAME AGE SUBJECT GAMES 1 Pravesh Shrivastava 24 CSE Tennis 2 Priyanka Ghosh 25 CSE Basketball
  • 27. Output: ID FIRST_NAME LAST_NAME AGE SUBJECT GAMES 1 Pravesh Shrivastava 24 CSE Tennis
  • 28. SQL IN Function The IN function helps reduce the need to use multiple OR conditions. The syntax for the IN function is: SELECT columns FROM tables WHERE column1 in (value1, value2, .... value_n); This SQL statement will return the records where column1 is value1, value2..., or value_n. The IN function can be used in any valid SQL statement - select, insert, update, or delete. Example: The following is an SQL statement that uses the IN function: select * from student_details where first_name in ('Pravesh','Priyanka','Santosh'); Output: ID FIRST_NAME LAST_NAME AGE SUBJECT GAMES 1 Pravesh Shrivastava 24 CSE Tennis 2 Priyanka Ghosh 25 CSE Basketball This would return all rows where the first name is either Pravesh, Priyanka, or Santosh. Because the * is used in the select, all fields from the student_details table would appear in the result set. It is equivalent to the following statement: select * from student_details where first_name = 'Pravesh' OR first_name = 'Priyanka' OR first_name = 'Santosh'; Output: ID FIRST_NAME LAST_NAME AGE SUBJECT GAMES 1 Pravesh Shrivastava 24 CSE Tennis 2 Priyanka Ghosh 25 CSE Basketball As you can see, using the IN function makes the statement easier to read and more efficient. Example: You can also use the IN function with numeric values. select * from student_details where id in (1,2,3,4,5,6); Output: ID FIRST_NAME LAST_NAME AGE SUBJECT GAMES 1 Pravesh Shrivastava 24 CSE Tennis 2 Priyanka Ghosh 25 CSE Basketball 3 Nitin singh 25 CSE Cricket 4 Akhilesh Kumar 25 CSE Cricket This SQL statement would return all students where the id is either 1, 2, 3, 5, or 6. It is equivalent to the following statement: select * from student_details where id=1 or id=2 or id=3 or id=4 or id=5 or id=6;
  • 29. Output: ID FIRST_NAME LAST_NAME AGE SUBJECT GAMES 1 Pravesh Shrivastava 24 CSE Tennis 2 Priyanka Ghosh 25 CSE Basketball 3 Nitin singh 25 CSE Cricket 4 Akhilesh Kumar 25 CSE Cricket Example: The IN function can also be combined with the NOT operator. select * from student_details where first_name not in ('Pravesh', 'Santosh', 'Nitin'); Output: ID FIRST_NAME LAST_NAME AGE SUBJECT GAMES 2 Priyanka Ghosh 25 CSE Basketball 4 Akhilesh Kumar 25 CSE Cricket This would return all rows where the first_name is neither Pravesh, Santosh, nor Nitin. Sometimes, it is more efficient to list the values that you do not want, as opposed to the values that you do want.
  • 30. SQL BETWEEN Operator The BETWEEN operator is used in a WHERE clause to select a range of data between two values. The values can be numbers, text, or dates. SQL BETWEEN Syntax: SELECT column_name(s) FROM table_name WHERE column_name BETWEEN value1 AND value2; Now we want to select the students with a last name alphabetically between "Kumar" and "Shrivastava" from the table above. We use the following SELECT statement: select * from student_details where last_name between 'Kumar'and 'Shrivastava'; Output: Note: The BETWEEN operator is treated differently in different databases. In Oracle, persons with the Last Name of "Kumar" or "Shrivastava" will be listed, because the BETWEEN operator selects fields that are between and including the test values. To display the students outside the range in the previous example, use NOT BETWEEN: select * from student_details where last_name not between 'Kumar' and 'Shrivastava'; Output: ID FIRST_NAME LAST_NAME AGE SUBJECT GAMES 2 Priyanka Ghosh 25 CSE Basketball 3 Nitin singh 25 CSE Cricket ID FIRST_NAME LAST_NAME AGE SUBJECT GAMES 1 Pravesh Shrivastava 24 CSE Tennis 4 Akhilesh Kumar 25 CSE Cricket
  • 31. SQL Alias With SQL, an alias name can be given to a table or to a column. You can give a table or a column another name by using an alias. This can be a good thing to do if you have very long or complex table names or column names. An alias name could be anything, but usually it is short. SQL Alias Syntax for Tables: SELECT column_name(s) FROM table_name AS alias_name; SQL Alias Syntax for Columns: SELECT column_name AS alias_name FROM table_name; Or SELECT column_name ALIAS_NAME FROM table_name; Table level alias: select s.id,s.first_name from student_details s; Output: Column Level alias: select id, first_name as name from student_details; Output: The above query is same like: ID FIRST_NAME 1 Pravesh 2 Priyanka 3 Nitin 4 Akhilesh ID NAME 1 Pravesh 2 Priyanka 3 Nitin 4 Akhilesh
  • 32. select student_details.id, student_details.first_name from student_details; Output: ID FIRST_NAME 1 Pravesh 2 Priyanka 3 Nitin 4 Akhilesh
  • 33. SQL Joins The JOIN keyword is used in an SQL statement to query data from two or more tables, based on a relationship between certain columns in these tables. Tables in a database are often related to each other with keys. A primary key is a column (or a combination of columns) with a unique value for each row. Each primary key value must be unique within the table. The purpose is to bind data together, across tables, without repeating all of the data in every table. Or SQL Joins are used to relate information in different tables. A Join condition is a part of the sql query that retrieves rows from two or more tables. A SQL Join condition is used in the SQL WHERE Clause of select, update, delete statements. If a sql join condition is omitted or if it is invalid the join operation will result in a Cartesian product. The Cartesian product returns a number of rows equal to the product of all rows in all the tables being joined. For example, if the first table has 20 rows and the second table has 10 rows, the result will be 20 * 10, or 200 rows. This query takes a long time to execute. Or A join is used to combine rows from multiple tables. A join is performed whenever two or more tables is listed in the FROM clause of an SQL statement. Different SQL JOINs:  JOIN: Return rows when there is at least one match in both tables.  LEFT JOIN: Return all rows from the left table, even if there are no matches in the right table.  RIGHT JOIN: Return all rows from the right table, even if there are no matches in the left table.  FULL JOIN: Return rows when there is a match in one of the tables. 1) SQL Equi Joins: An equi-join is further classified into two categories: a) SQL Inner Join b) SQL Outer Join
  • 34. (a)SQL INNER JOIN The INNER JOIN keyword return rows when there is at least one match in both tables. All the rows returned by the sql query satisfy the sql join condition specified. It is the most common type of join. Inner joins return all rows from multiple tables where the join condition is met. Table: suppliers: Table: orders: All the rows returned by the sql query satisfy the sql join condition specified. For example: If you want to display the product information for each order the query will be as given below. Since you are retrieving the data from two tables, you need to identify the common column between these two tables, which is the supplier_id. The query for this type of sql joins would be like, select order_id, supplier_name from suppliers, orders where orders.supplier_id = suppliers.supplier_id; Output: ORDER_ID SUPPLIER_NAME 50012 IBM 50013 Hewlett Packard The rows for Microsoft and NVIDIA from the supplier table would be omitted, since the supplier_id's 10002 and 10003 do not exist in both tables. SUPPLIER_ID SUPPLIER_NAME 10000 IBM 10001 Hewlett Packard 10002 Microsoft 10003 NVIDIA ORDER_ID SUPPLIER_ID ORDER_DATE 50012 10000 17-AUG-11 50013 10001 18-AUG-11
  • 35. The columns must be referenced by the table name in the join condition, because supplier_id is a column in both the tables and needs a way to be identified. This avoids ambiguity in using the columns in the SQL SELECT statement. The number of join conditions is (n-1), if there are more than two tables joined in a query where 'n' is the number of tables involved. The rule must be true to avoid Cartesian product. We can also use aliases to reference the column name, then the above query would be like, select o.order_id, s.supplier_name from suppliers s, orders o where o.supplier_id = s.supplier_id; Output: The rows for Microsoft and NVIDIA from the supplier table would be omitted, since the supplier_id's 10002 and 10003 do not exist in both tables. INNER JOIN (SQL SERVER) select suppliers.supplier_name, orders.order_date, orders.order_id from orders inner join suppliers on orders.supplier_Id=suppliers.supplier_Id; Or select suppliers.supplier_name, orders.order_date, orders.order_id from suppliers inner join orders on suppliers.supplier_Id=orders.supplier_Id; Or select supplier_name, order_date, order_id from orders inner join suppliers on orders.supplier_Id=suppliers.supplier_Id; Or (With Alias) select s.supplier_name, o.order_date, o.order_id from orders o inner join suppliers s on o.supplier_Id=s.supplier_Id; ORDER_ID SUPPLIER_NAME 50012 IBM 50013 Hewlett Packard
  • 36. Output: SUPPLIER_NAME ORDER_DATE ORDER_ID IBM 17-AUG-11 50012 Hewlett Packard 18-AUG-11 50013
  • 37. (b)SQL OUTER JOIN This sql join condition returns all rows from both tables which satisfy the join condition along with rows which do not satisfy the join condition from one of the tables. The sql outer join operator in Oracle is (+) and is used on one side of the join condition only. This type of join returns all rows from one table and only those rows from a secondary table where the joined fields are equal (join condition is met). Note: The syntax differs for different RDBMS implementation. Few of them represent the join conditions as "sql left outer join", "sql right outer join".
  • 38. (a)Left Outer Join If you want to display all the suppliers data along with orders data, with null values displayed for orders if a supplier has no order_id, the sql query for outer join would be as shown below: select s.supplier_id, s.supplier_name, o.order_id, o.order_date from orders o, suppliers s where o.supplier_id (+) = s.supplier_id; Output: Or The LEFT JOIN keyword returns all rows from the left table, even if there are no matches in the right table. SQL Server Syntax: SELECT column_name(s)FROM table_name1 LEFT JOIN table_name2 ON table_name1.column_name=table_name2.column_name; SQL Server Query: select suppliers.supplier_id, suppliers.supplier_name, orders.order_id from suppliers left join orders on suppliers.supplier_Id=orders.supplier_Id order by suppliers.supplier_name; Output: If we revert the query: select suppliers.supplier_id, suppliers.supplier_name, orders.order_id from orders left join suppliers on suppliers.supplier_id=orders.supplier_id order by suppliers.supplier_name; Output: SUPPLIER_ID SUPPLIER_NAME ORDER_ID ORDER_DATE 10000 IBM 50012 17-AUG-11 10001 Hewlett Packard 50013 18-AUG-11 10002 Microsoft - - 10003 NVIDIA - - SUPPLIER_ID SUPPLIER_NAME ORDER_ID 10001 Hewlett Packard 50013 10000 IBM 50012 10002 Microsoft - 10003 NVIDIA -
  • 39. SUPPLIER_ID SUPPLIER_NAME ORDER_ID 10001 Hewlett Packard 50013 10000 IBM 50012
  • 40. (b)RIGHT OUTER JOIN The RIGHT JOIN keyword Return all rows from the right table, even if there are no matches in the left table. NOTE: If the (+) operator is used in the left side of the join condition it is equivalent to left outer join. If used on the right side of the join condition it is equivalent to right outer join. select s.supplier_id, s.supplier_name, o.order_id, o.order_date from suppliers s, orders o where o.supplier_id = s.supplier_id(+); Output: SUPPLIER_ID SUPPLIER_NAME ORDER_ID ORDER_DATE 10000 IBM 50012 17-AUG-11 10001 Hewlett Packard 50013 18-AUG-11 select s.supplier_id, s.supplier_name, o.order_id, o.order_date from suppliers s, orders o where s.supplier_id = o.supplier_id (+); Output: SUPPLIER_ID SUPPLIER_NAME ORDER_ID ORDER_DATE 10000 IBM 50012 17-AUG-11 10001 Hewlett Packard 50013 18-AUG-11 10002 Microsoft - - 10003 NVIDIA - - SQL Server Syntax: SELECT column_name(s)FROM table_name1 RIGHT JOIN table_name2 ON table_name1.column_name=table_name2.column_name; SQL Server Example (1): select suppliers.supplier_id, suppliers.supplier_name, orders.order_id, orders.order_date from suppliers right join orders on suppliers.supplier_id = orders.supplier_id; Output: SUPPLIER_ID SUPPLIER_NAME ORDER_ID ORDER_DATE 10000 IBM 50012 17-AUG-11 10001 Hewlett Packard 50013 18-AUG-11 SQL Server Example (2): select suppliers.supplier_id, suppliers.supplier_name, orders.order_id, orders.order_date from orders right join suppliers on suppliers.supplier_id = orders.supplier_id; Output:
  • 41. SUPPLIER_ID SUPPLIER_NAME ORDER_ID ORDER_DATE 10000 IBM 50012 17-AUG-11 10001 Hewlett Packard 50013 18-AUG-11 10002 Microsoft - - 10003 NVIDIA - - SQL Server Example (3): select suppliers.supplier_id, suppliers.supplier_name, orders.order_id, orders.order_date from suppliers right join orders on orders.supplier_id = suppliers.supplier_id; Output: SUPPLIER_ID SUPPLIER_NAME ORDER_ID ORDER_DATE 10000 IBM 50012 17-AUG-11 10001 Hewlett Packard 50013 18-AUG-11 select suppliers.supplier_id, suppliers.supplier_name, orders.order_id, orders.order_date from orders right join suppliers on orders.supplier_id = suppliers.supplier_id; Output: SUPPLIER_ID SUPPLIER_NAME ORDER_ID ORDER_DATE 10000 IBM 50012 17-AUG-11 10001 Hewlett Packard 50013 18-AUG-11 10002 Microsoft - - 10003 NVIDIA - -
  • 42. SQL FULL Join The FULL JOIN keyword return rows when there is a match in one of the tables. Syntax: SELECT column_name(s) FROM table_name1 FULL JOIN table_name2 ON table_name1.column_name=table_name2.column_name; Example: Now we want to list all the suppliers and their orders, and all the orders with their persons. select suppliers.supplier_id, suppliers.supplier_name, orders.order_id from suppliers full join orders on suppliers.supplier_Id = orders.supplier_Id; Output: SUPPLIER_ID SUPPLIER_NAME ORDER_ID 10000 IBM 50012 10001 Hewlett Packard 50013 10002 Microsoft - 10003 NVIDIA - The FULL JOIN keyword returns all the rows from the left table, and all the rows from the right table. If there are rows in "suppliers" that do not have matches in "Orders", or if there are rows in "Orders" that do not have matches in "suppliers", those rows will be listed as well.
  • 43. SQL SELF JOIN A Self Join is a type of sql join which is used to join a table to itself, particularly when the table has a FOREIGN KEY that references its own PRIMARY KEY. It is necessary to ensure that the join statement defines an alias for both copies of the table to avoid column ambiguity. Example: select s.supplier_id, s.supplier_name, o.order_id from suppliers s, orders o where s.supplier_id = o.supplier_id; Output: SUPPLIER_ID SUPPLIER_NAME ORDER_ID 10000 IBM 50012 10001 Hewlett Packard 50013
  • 44. SQL UNION Operator The UNION operator is used to combine the result-set of two or more SELECT statements. Notice that each SELECT statement within the UNION must have the same number of columns. The columns must also have similar data types. Also, the columns in each SELECT statement must be in the same order. It removes duplicate rows between the various "select" statements. SQL UNION Syntax: SELECT column_name(s) FROM table_name1 UNION SELECT column_name(s) FROM table_name2; Example: select supplier_id from suppliers union select supplier_id from orders; Output: In this example, if a supplier_id appeared in both the suppliers and orders table, it would appear once in your result set. The UNION removes duplicates. Example: With ORDER BY Clause The following is a UNION query that uses an ORDER BY clause: select supplier_id from suppliers where supplier_id > 200 union select order_id from orders where order_id > 1000 ORDER BY 1; Since the column names are different between the two "select" statements, it is more advantageous to reference the columns in the ORDER BY clause by their position in the result set. In this example, we've sorted the results by supplier_id / order_id in ascending order, as denoted by the "ORDER BY 1". The supplier_id / order_id fields are in position #1 in the result set. SUPPLIER_ID 10000 10001 10002 10003
  • 45. SQL UNION ALL The UNION ALL query allows you to combine the result sets of 2 or more "select" queries. It returns all rows (even if the row exists in more than one of the "select" statements). Each SQL statement within the UNION ALL query must have the same number of fields in the result sets with similar data types. UNION ALL Syntax: SELECT column_name(s) FROM table_name1 UNION ALL SELECT column_name(s) FROM table_name2; Example: select supplier_id from suppliers union all select supplier_id from orders; Output: If a supplier_id appeared in both the suppliers and orders table, it would appear multiple times in your result set. The UNION ALL does notremove duplicates. Example: select supplier_id from suppliers where supplier_id > 200 union all select order_id from orders where order_id > 1000 order by 1; Output: SUPPLIER_ID 10000 10001 10002 10003 10000 10001 SUPPLIER_ID 10000 10001 10002 10003 50012 50013
  • 46. SQL CREATE TABLE Statement The CREATE TABLE Statement is used to create tables to store data. Integrity Constraints like primary key, unique key, foreign key can be defined for the columns while creating the table. The integrity constraints can be defined at column level or table level. The implementation and the syntax of the CREATE Statements differs for different RDBMS. CREATE TABLE Statement Syntax: CREATE TABLE table_name (column_name1 datatype, column_name2 datatype, ... column_nameN datatype ); Example: If you want to create the employee table, the statement would be like, create table employee ( id number(5), name char(20), dept char(10), age number(2), salary number(10), location char(10) );
  • 47. CREATE a table from another table You can also create a table from an existing table by copying the existing table's columns. It is important to note that when creating a table in this way, the new table will be populated with the records from the existing table (based on the SELECT Statement). Syntax: Copying all columns from another table CREATE TABLE new_table AS (SELECT * FROM old_table); Example: create table new_table as (select * from company); Syntax: Copying selected columns from another table CREATE TABLE new_table AS (SELECT column_1, column2, ... column_n FROM old_table); Example: create table supply_new as (select id, city, state from supply where id = 1); Syntax: Copying selected columns from multiple tables CREATE TABLE new_table AS (SELECT column_1, column2, ... column_n FROM old_table_1, old_table_2, ... old_table_n); Example: create table supply_new_new as (select supply.id, supply.address, orders.order_id from supply, orders where orders.order_id = supply.id and id = 1);
  • 48. SQL Constraints Constraints are used to limit the type of data that can go into a table. Constraints can be specified when a table is created (with the CREATE TABLE statement) or after the table is created (with the ALTER TABLE statement). We will focus on the following constraints:  NOT NULL  UNIQUE  PRIMARY KEY  FOREIGN KEY  CHECK  DEFAULT Constraints can be defined in two ways: 1) The constraints can be specified immediately after the column definition. This is called column-level definition. 2) The constraints can be specified after all the columns are defined. This is called table-level definition.
  • 49. SQL NOT NULL Constraint The NOT NULL constraint enforces a column to NOT accept NULL values. The NOT NULL constraint enforces a field to always contain a value. This means that you cannot insert a new record, or update a record without adding a value to this field. Example with Constraint: create table employee ( id number(5), name char(20) constraint nm_nn not null, dept char(10), age number(2), salary number(10), location char(10) ); Or Example without Constraint: create table employee ( id number(5), name char(20) not null, dept char(10), age number(2), salary number(10), location char(10) );
  • 50. SQL UNIQUE Constraint The UNIQUE constraint uniquely identifies each record in a database table. The UNIQUE and PRIMARY KEY constraints both provide a guarantee for uniqueness for a column or set of columns. A PRIMARY KEY constraint automatically has a UNIQUE constraint defined on it. Note that you can have many UNIQUE constraints per table, but only one PRIMARY KEY constraint per table. Example: create table employee ( id number(5), name char(20), dept char(10), age number(2), salary number(10), location char(10) UNIQUE ); Or create table employee ( id number(5)not null unique, name char(20), dept char(10), age number(2), salary number(10), location char(10) unique ); Or create table employee ( id number(5), name char(20), dept char(10), age number(2), salary number(10), location char(10) constraint loc_un unique ); Or create table employee (id number(5), name char(20),
  • 51. dept char(10), age number(2), salary number(10), location char(10), constraint loc_un unique(location) ); Or create table employee (id number(5), name char(20), dept char(10), age number(2), salary number(10), location char(10), constraint loc_un unique(location, name) );
  • 52. SQL UNIQUE Constraint on ALTER TABLE To create a UNIQUE constraint on the "id" column when the table is already created, use the following SQL: Add Unique constraint without constraint: alter table employee add unique(id); Add Unique constraint with constraint: alter table employee add constraint uc_e_id unique(id,name); To allow naming of a UNIQUE constraint, and for defining a UNIQUE constraint on multiple columns, use the following SQL syntax: alter table employee add constraint uc_e_id unique(id,name);
  • 53. To DROP a UNIQUE Constraint alter table employee drop constraint uc_e_id;
  • 54. SQL PRIMARY KEY Constraint This constraint defines a column or combination of columns which uniquely identifies each row in the table. Primary Key on Create Table: Primary Key at column level without Constraint: create table employee (id number(5) primary key, name char(20), dept char(10), age number(2), salary number(10), location char(10) ); Primary Key at column level with Constraint: create table employee (id number(5) constraint emp_id_pk primary key, name char(20), dept char(10), age number(2), salary number(10), location char(10) ); Primary Key at table level: create table employee (id number(5), name char(20), dept char(10), age number(2), salary number(10), location char(10), constraint emp_id_pk primary key(id) );
  • 55. SQL PRIMARY KEY Constraint on ALTER TABLE Add Primary Key without Constraint: alter table employee add primary key (id); Add Primary Key with Constraint: alter table employee add constraint p_k_e_id primary key(id);
  • 56. To DROP a PRIMARY KEY Constraint alter table employee drop constraint p_k_e_id;
  • 57. SQL Foreign key or Referential Integrity This constraint identifies any column referencing the PRIMARY KEY in another table. It establishes a relationship between two columns in the same table or between different tables. For a column to be defined as a Foreign Key, it should be a defined as a Primary Key in the table which it is referring. One or more columns can be defined as Foreign key. Foreign Key at column level with constraint: create table employee (id number(5) constraint e_id_pk primary key, name char(20), dept char(20), age number(10) ); create table company (c_id number(2) primary key, c_name char(20), id number(2) constraint c_e_id references employee(id) ); Foreign Key at column level without constraint: create table employee (id number(5) primary key, name char(20), dept char(20), age number(10) ); create table company (c_id number(2) primary key, c_name char(20), id number(2)references employee(id) ); Table Column Data Type Length Precision Scale Primary Key Nullable Default Comment EMPLOYEE32 ID Number - 5 0 1 - - - NAME Char 20 - - - - - DEPT Char 20 - - - - - AGE Number - 10 0 - - - Foreign Key at table level: create table employee
  • 58. (id number(5), name char(20), dept char(20), age number(10), constraint e_id primary key(id) ); create table company (c_id number(2), c_name char(20), id number(2), constraint c_c_id primary key(c_id), constraint c_e_id foreign key(id) references employee(id) );
  • 59. SQL FOREIGN KEY Constraint on ALTER TABLE Add Foreign Key without constraint: alter table company add foreign key (order_id) references orders(order_id); Add Foreign Key with constraint: alter table company add constraint fk_o_id foreign key (order_id) references orders(order_id);
  • 60. To DROP a FOREIGN KEY Constraint alter table company drop constraint fk_o_id; SQL CHECK Constraint The CHECK constraint is used to limit the value range that can be placed in a column. If you define a CHECK constraint on a single column it allows only certain values for this column. If you define a CHECK constraint on a table it can limit the values in certain columns based on values in other columns in the row. Column Level SQL CHECK Constraint on CREATE TABLE without constraint: create table employee (id number(5) primary key, name char(20), dept char(10), age number(2), gender char(1) check (gender in ('M','F')), salary number(10), location char(10) );
  • 61. Column Level SQL CHECK Constraint on CREATE TABLE with constraint: create table employee (id number(5) primary key, name char(20), dept char(10), age number(2), gender char(1) constraint c_e_id check (gender in ('M','F')), salary number(10), location char(10) ); Table Level SQL CHECK Constraint on CREATE TABLE with constraint: create table employee (id number(5) primary key, name char(20), dept char(10), age number(2), gender char(1),salary number(10), location char(10), constraint c_e_id check (gender in ('M','F')) );
  • 62. SQL CHECK Constraint on ALTER TABLE Without Constraint: alter table employee add check (id>0); Or Check on multiple columns: alter table employee add check (id>0 and gender='M'); With Constraint: alter table employee add constraint chk_emp check (id>0 and gender='M');
  • 63. To DROP a CHECK Constraint alter table employee drop constraint chk_emp;
  • 64. SQL DEFAULT Constraint The DEFAULT constraint is used to insert a default value into a column. The default value will be added to all new records, if no other value is specified. SQL DEFAULT Constraint on CREATE TABLE: create table person_details (p_id number not null, name char(20), address varchar(200), city char(255) default 'Gwalior' );
  • 65. SQL CREATE INDEX Statement An index can be created in a table to find data more quickly and efficiently. The users cannot see the indexes, they are just used to speed up searches/queries. Index in sql is created on existing tables to retrieve the rows quickly. When there are thousands of records in a table, retrieving information will take a long time. Therefore indexes are created on columns which are accessed frequently, so that the information can be retrieved quickly. Indexes can be created on a single column or a group of columns. When an index is created, it first sorts the data and then it assigns a ROWID for each row. Note: Updating a table with indexes takes more time than updating a table without (because the indexes also need an update). So you should only create indexes on columns (and tables) that will be frequently searched against. SQL CREATE INDEX Syntax: Creates an index on a table. Duplicate values are allowed: Syntax: CREATE INDEX index_name ON table_name (column_name); Example: create index person_index on person_details(p_id); SQL CREATE INDEX on multiple columnsSyntax: CREATE INDEX index_name ON table_name (column_name1,column_name2...); SQL CREATE UNIQUE INDEX Syntax: Creates a unique index on a table. Duplicate values are not allowed: Syntax: CREATE UNIQUE INDEX index_name ON table_name (column_name); Example: create unique index index_person on person_details (city,address);
  • 66. In Oracle there are two types of SQL index namely, implicit and explicit. Implicit Indexes: They are created when a column is explicity defined with PRIMARY KEY, UNIQUE KEY Constraint. Explicit Indexes: They are created using the "create index.. " syntax. NOTE: 1) Even though sql indexes are created to access the rows in the table quickly, they slow down DML operations like INSERT, UPDATE, DELETE on the table, because the indexes and tables both are updated along when a DML operation is performed. So use indexes only on columns which are used to search the table frequently. 2) Is is not required to create indexes on table which have less data. 3) In oracle database you can define up to sixteen (16) columns in an INDEX.
  • 67. SQL DROP Indexes, tables, and databases can easily be deleted/removed with the DROP statement. The SQL DROP command is used to remove an object from the database. If you drop a table, all the rows in the table are deleted and the table structure is removed from the database. Once a table is dropped we cannot get it back, so be careful while using DROP command. When a table is dropped all the references to the table will not be valid.
  • 68. The DROP INDEX Statement Syntax: DROP INDEX index_name; Example: drop index index_person;
  • 69. The DROP TABLE Statement Syntax: DROP TABLE table_name; Example: Drop table employee;
  • 70. SQL TRUNCATE Statement The SQL TRUNCATE command is used to delete all the rows from the table and free the space containing the table. Syntax: TRUNCATE TABLE table_name; Example: truncate table employee;
  • 71. Difference between DELETE and TRUNCATE Statements: DELETE Statement: This command deletes only the rows from the table based on the condition given in the where clause or deletes all the rows from the table if no condition is specified. But it does not free the space containing the table. TRUNCATE statement: This command is used to delete all the rows from the table and free the space containing the table.
  • 72. SQL ALTER TABLE Statement The SQL ALTER TABLE command is used to modify the definition (structure) of a table by modifying the definition of its columns. The ALTER command is used to perform the following functions. 1) Add, drop, modify table columns 2) Add and drop constraints 3) Enable and Disable constraints Syntax to add a column: ALTER TABLE table_name ADD column_name datatype; Example: alter table student_details add salary number(5); Output: ID FIRST_NAME LAST_NAME AGE SUBJECT GAMES SALARY 1 Pravesh Shrivastava 24 CSE Tennis - 2 Priyanka Ghosh 25 CSE Basketball - 3 Nitin singh 25 CSE Cricket - 4 Akhilesh Kumar 25 CSE Cricket - Syntax to drop a column: ALTER TABLE table_name DROP column column_name; Example: alter table student_details drop column salary; Output: ID FIRST_NAME LAST_NAME AGE SUBJECT GAMES
  • 73. 1 Pravesh Shrivastava 24 CSE Tennis 2 Priyanka Ghosh 25 CSE Basketball 3 Nitin singh 25 CSE Cricket 4 Akhilesh Kumar 25 CSE Cricket Syntax to modify a column: ALTER TABLE table_name MODIFY column_name datatype; Example: alter table student_details modify salary char(20); SQL RENAME Command The SQL RENAME command is used to change the name of the table or a database object. If you change the object's name any reference to the old name will be affected. You have to manually change the old name to the new name in every reference. Syntax: RENAME old_table_name To new_table_name; Example: rename student_details to student_info;
  • 74. SQL AUTO INCREMENT Field Auto-increment allows a unique number to be generated when a new record is inserted into a table. Very often we would like the value of the primary key field to be created automatically every time a new record is inserted. We would like to create an auto-increment field in a table. You will have to create an auto-increment field with the sequence object (this object generates a number sequence). Use the following CREATE SEQUENCE syntax: CREATE SEQUENCE seq_name MINVALUE min_value START WITH start_value INCREMENT BY increment_value CACHE end_value; Example: create sequence seq_emp minvalue 1 start with 1 increment by 1 cache 10; The code above creates a sequence object called seq_emp, that starts with 1 and will increment by 1. It will also cache up to 10 values for performance. The cache option specifies how many sequence values will be stored in memory for faster access. To insert a new record into the "emp_details" table, we will have to use the nextval function (this function retrieves the next value from seq_emp sequence): create table emp_details (id number(5), name char(20), age number(2) ); insert into emp_details(id,name,age) values(seq_emp.nextval,'Pravesh',25);
  • 75. SQL CREATE VIEW Statement In SQL, a view is a virtual table based on the result-set of an SQL statement. A view contains rows and columns, just like a real table. The fields in a view are fields from one or more real tables in the database. You can add SQL functions, WHERE, and JOIN statements to a view and present the data as if the data were coming from one single table. A view is, in essence, a virtual table. It does not physically exist. Rather, it is created by a query joining one or more tables. A VIEW is a virtual table, through which a selective portion of the data from one or more tables can be seen. Views do not contain data of their own. They are used to restrict access to the database or to hide data complexity. A view is stored as a SELECT statement in the database. DML operations on a view like INSERT, UPDATE, DELETE affects the data in the original table upon which the view is based. SQL CREATE VIEW Syntax: CREATE VIEW view_name AS SELECT columns FROM table WHERE predicates; Example: create view sup_order2 as select supplier_id, supplier_name from suppliers;
  • 76. Updating a VIEW You can update a VIEW without dropping it by using the following syntax. CREATE OR REPLACE VIEW view_name AS SELECT columns FROM table WHERE predicates; Example: create or replace view sup_order2 as select supplier_id,supplier_name from suppliers;
  • 77. Dropping a VIEW The syntax for dropping a VIEW is: DROP VIEW view_name;
  • 78. SQL: Data Types The following is a list of general SQL datatypes that may not be supported by all relational databases. Data Type Syntax Explanation (if applicable) Range Integer integer Smallint smallint Numeric numeric(p,s) Where p is a precision value; s is a scale value. For example, numeric(6,2) is a number that has 4 digits before the decimal and 2 digits after the decimal. Precision can range from 1 to 38. Decimal decimal(p,s) Where p is a precision value; s is a scale value. Where p is the precision and s is the scale. For example, decimal(3,1) is a number that has 2 digits before the decimal and 1 digit after the decimal. Real real Single-precision floating point number
  • 79. double precision double precision Double-precision floating point number Float float(p) Where p is a precision value. Character char(x) Where x is the number of characters to store. This data type is space padded to fill the number of characters specified. Maximum size of 2000 bytes. character varying varchar2(x) Where x is the number of characters to store. This data type does NOT space pad. Maximum size of 4000 bytes Bit bit(x) Where x is the number of bits to store. bit varying bit varying(x) Where x is the number of bits to store. The length can vary up to x. Date date Stores year, month, and day values. A date between Jan 1, 4712 BC and Dec 31, 9999 AD. Time time Stores the hour, minute, and second values. Timestamp timestamp Stores year, month, day, hour, minute, and second values. fractional seconds precision must be a number time with time zone time with time zone Exactly the same as time, but also stores an offset from UTC of the time specified. timestamp with time zone timestamp with time zone Exactly the same as timestamp, but also stores an offset from UTC of the time specified. fractional seconds precision must be a number between 0 and 9. (default is 6) year-month interval Contains a year value, a month value, or both. day-time interval Contains a day value, an hour
  • 80. value, a minute value, and/or a second value. nchar(size) nchar(x) Where size is the number of characters to store. Fixed-length NLS string Space padded. Maximum size of 2000 bytes. SQL Functions SQL has many built-in functions for performing calculations on data. SQL Aggregate Functions: SQL aggregate functions return a single value, calculated from values in a column. Useful aggregate functions:  AVG() - Returns the average value  COUNT() - Returns the number of rows  MAX() - Returns the largest value  MIN() - Returns the smallest value  SUM() - Returns the sum SQL Scalar functions: SQL scalar functions return a single value, based on the input value. Useful scalar functions:  UCASE() - Converts a field to upper case  LCASE() - Converts a field to lower case  MID() - Extract characters from a text field  LEN() - Returns the length of a text field  ROUND() - Rounds a numeric field to the number of decimals specified  NOW() - Returns the current system date and time  FORMAT() - Formats how a field is to be displayed
  • 81. SQL AVG() Function SQL AVG(): This function is used to get the average value of a numeric column. SQL AVG() Syntax: SELECT AVG(column_name) FROM table_name; Example: select avg(age) from student_details; Output: AVG( AGE) 24.75
  • 82. SQL COUNT() Function This function returns the number of rows in the table that satisfies the condition specified in the WHERE condition. If the WHERE condition is not specified, then the query returns the total number of rows in the table. SQL COUNT(column_name) Syntax: The COUNT(column_name) function returns the number of values (NULL values will not be counted) of the specified column. SELECT COUNT(column_name) FROM table_name; Example: select count(subject) from student_details; Output: SQL COUNT(*) Syntax: The COUNT(*) function returns the number of records in a table: SELECT COUNT(*) FROM table_name; Example: select count(*) from student_details; Output: COUNT(SUBJECT) 4 COUNT(*) 4
  • 83. SQL MAX() Function The MAX() function returns the largest value of the selected column. Syntax: SELECT MAX(column_name) FROM table_name; Example: select max(age) from student_details; Output: MAX( AGE) 25
  • 84. SQL MIN() Function The MIN() function returns the smallest value of the selected column. Syntax: SELECT MIN(column_name) FROM table_name; Example: select min(first_name) from student_details; Output: MIN(FIRST_NAME) Akhilesh
  • 85. SQL SUM() Function The SUM() function returns the total sum of a numeric column. Syntax: SELECT SUM(column_name) FROM table_name; Example: Select sum(age)FROM student_details; Output: SUM( AGE) 99
  • 86. SQL GROUP BY Clause The SQL GROUP BY Clause is used along with the group functions to retrieve data grouped according to one or more columns. Syntax: SELECT column_name, aggregate_function(column_name) FROM table_name WHERE column_name operator value GROUP BY column_name; Example: select first_name, last_name, sum (age) from student_details group by first_name, last_name; Output: FIRST_NAME LAST_NAME SUM( AGE) Akhilesh Kumar 25 Pravesh Shrivastava 24 Priyanka Ghosh 25 Nitin singh 25
  • 87. SQL HAVING Clause Having clause is used to filter data based on the group functions. This is similar to WHERE condition but is used with group functions. Group functions cannot be used in WHERE Clause but can be used in HAVING clause. Syntax: SELECT column_name, aggregate_function(column_name) FROM table_name WHERE column_name operator value GROUP BY column_name HAVING aggregate_function(column_name) operator value; Example: select first_name, sum (age) from student_details group BY first_name having sum(age)> 20; Output: FIRST_NAME SUM( AGE) Priyanka 25 Nitin 25 Akhilesh 25 Pravesh 24
  • 88. SQL UPPER() Function The UPPER() function converts the value of a field to uppercase. Syntax: SELECT UPPER(column_name) FROM table_name; Example: select upper(last_name) from student_details; Output: UPPER(LAST_NAME) SHRIVASTAVA GHOSH SINGH KUMAR
  • 89. SQL LOWER() Function The LOWER() function converts the value of a field to lowercase. Syntax: SELECT LOWER(column_name) FROM table_name; Example: select lower(last_name) from student_details; Output: LOWER(LAST_NAME) shrivastava ghosh singh kumar
  • 90. SQL LENGTH() Function The LENGTH() function returns the length of the value in a text field. Syntax: SELECT LENGTH(column_name) FROM table_name; Example: select length(first_name) from student_details; Output: LENGTH(FIRST_NAME) 20 20 20 20
  • 91. SQL ROUND() Function The ROUND() function is used to round a numeric field to the number of decimals specified. Syntax: SELECT ROUND(column_name,decimals) FROM table_name; Parameter Description column_name Required. The field to round. Decimals Required. Specifies the number of decimals to be returned. Example: select first_name, round(age,0) from student_details; Output: FIRST_NAME ROUND( AGE,0) Pravesh 24 Priyanka 25 Nitin 25 Akhilesh 25
  • 92. SQL EXISTS Condition The EXISTS condition is considered "to be met" if the subquery returns at least one row. Syntax: SELECT columns FROM tables WHERE EXISTS ( subquery ); The EXISTS condition can be used in any valid SQL statement - select, insert, update, or delete. Table: student_details ID S_F_NAME S_L_NAME S_SUB 1 Pravesh Shrivastava CSE 2 Nitin Singh CSE 3 Akhilesh Kumar CSE 4 Santosh Gupta Arts 5 Ranjita Kapoor BSC Table: employee E_ID E_NAME E_DEPT 1 Bindu HRM 2 Priyanka HRM 3 Abhishek Networking
  • 93. Example: select * from student_details where exists (select * from employee where student_details.id = employee.e_id); Output: ID S_F_NAME S_L_NAME S_SUB 1 Pravesh Shrivastava CSE 2 Nitin Singh CSE 3 Akhilesh Kumar CSE This select statement will return all records from the student_details table where there is at least one record in the employee table with the same datatype. Exists with Delete Example: delete from student_details where exists (select * from employee where student_details.id = employee.e_id); Output: ID S_F_NAME S_L_NAME S_SUB 4 Santosh Gupta Arts 5 Ranjita Kapoor BSC Exists with Update Example: update student_details
  • 94. set s_f_name =( select e_name from employee where student_details.id = employee.e_id) where exists (select e_name from employee where employee.e_id = student_details.id); Output: ID S_F_NAME S_L_NAME S_SUB 1 Bindu Shrivastava CSE 2 Priyanka Singh CSE 4 Santosh Gupta Arts 5 Ranjita Kapoor BSC not Exists Condition Example: select * from student_details where not exists (select * from employee Where student_details.id = employee.e_id); Output: ID S_F_NAME S_L_NAME S_SUB 5 Ranjita Kapoor BSC 4 Santosh Gupta Arts
  • 95. Not Exists with Delete Example: delete from student_details where not exists (select * from employee where student_details.id = employee.e_id); Output: ID S_F_NAME S_L_NAME S_SUB 1 Pravesh Shrivastava CSE 2 Nitin Singh CSE 3 Akhilesh Kumar CSE
  • 96. Not Exists with Update Statement Example: update student_details set s_f_name = (select e_name from employee where student_details.id = employee.e_id) where not exists (select e_name from employee where employee.e_id = student_details.id); Output: ID S_F_NAME S_L_NAME S_SUB 1 Pravesh Shrivastava CSE 2 Nitin Singh CSE 3 Akhilesh Kumar CSE 4 - Gupta Arts 5 - Kapoor BSC
  • 97. SQL INTERSECT Query The INTERSECT query allows you to return the results of 2 or more "select" queries. However, it only returns the rows selected by all queries. If a record exists in one query and not in the other, it will be omitted from the INTERSECT results. Each SQL statement within the INTERSECT query must have the same number of fields in the result sets with similar data types. Syntax: SELECT field1, field2, . field_n from TABLE1 INTERSECT SELECT field1, field2, . field_n from TABLE2; Example: select supplier_id from suppliers intersect select supplier_id from orders; Output:
  • 98. Example: With ORDER BY Clause: select supplier_id from suppliers where supplier_id > 1000 intersect select order_id from orders where order_id > 1000 ORDER BY 1; Output: SUPPLIER_ID 1000 1001 1002 SUPPLIER_ID 1001
  • 99. SQL MINUS Query The MINUS query returns all rows in the first query that are not returned in the second query. Each SQL statement within the MINUS query must have the same number of fields in the result sets with similar data types. Syntax: SELECT field1, field2, . field_n FROM table1 MINUS SELECT field1, field2, . field_n FROM tables2; Example: select supplier_id from suppliers minus select supplier_id from orders; Output: no data found Example: With ORDER BY Clause: select supplier_id from suppliers where supplier_id > 1000 minus select order_id
  • 100. from orders where order_id > 1000 order by 1; Output: GRANT & REVOKE COMMNDS DCL commands are used to enforce database security in a multiple user database environment. Two types of DCL commands are GRANT and REVOKE. Only Database Administrator or owner of the database object can provide/remove privileges on a database object. SUPPLIER_ID 1002
  • 101. SQL GRANT Command SQL GRANT is a command used to provide access or privileges on the database objects to the users. Syntax: GRANT privilege_name ON object_name TO {user_name |PUBLIC |role_name} [WITH GRANT OPTION];  privilege_name is the access right or privilege granted to the user. Some of the access rights are ALL, EXECUTE, and SELECT.  object_name is the name of an database object like TABLE, VIEW, STORED PROC and SEQUENCE.  user_name is the name of the user to whom an access right is being granted.  user_name is the name of the user to whom an access right is being granted.  PUBLIC is used to grant access rights to all users.  ROLES are a set of privileges grouped together.  WITH GRANT OPTION allows a user to grant access rights to other users. Example: grant select on employee to user1;
  • 102. This command grants a SELECT permission on employee table to user1. You should use the WITH GRANT option carefully because for example if you GRANT SELECT privilege on employee table to user1 using the WITH GRANT option, then user1 can GRANT SELECT privilege on employee table to another user, such as user2 etc. Later, if you REVOKE the SELECT privilege on employee from user1, still user2 will have SELECT privilege on employee table. SQL REVOKE Command The REVOKE command removes user access rights or privileges to the database objects. Syntax: REVOKE privilege_name ON object_name FROM {user_name |PUBLIC |role_name}; Example: REVOKE SELECT ON employee FROM user1; This command will REVOKE a SELECT privilege on employee table from user1. When you REVOKE SELECT privilege on a table from a user, the user will not be able to SELECT data from that table anymore. However, if the user has received SELECT privileges on that table from more than one users, he/she can SELECT from that table until everyone who granted the permission revokes it. You cannot REVOKE privileges if they were not initially granted by you.
  • 104. Privileges Privileges define the access rights provided to a user on a database object. There are two types of privileges: 1) System Privileges: This allows the user to CREATE, ALTER, or DROP database objects. 2) Object Privileges: This allows the user to EXECUTE, SELECT, INSERT, UPDATE, or DELETE data from database objects to which the privileges apply. Few CREATE system privileges are listed below: System Privileges Description CREATE object allows users to create the specified object in their own schema. CREATE ANY object allows users to create the specified object in any schema. The above rules also apply for ALTER and DROP system privileges. Few of the object privileges are listed below: Object Privileges Description INSERT allows users to insert rows into a table. SELECT allows users to select data from a
  • 105. database object. UPDATE allows user to update data in a table. EXECUTE allows user to execute a stored procedure or a function. Roles Roles are a collection of privileges or access rights. When there are many users in a database it becomes difficult to grant or revoke privileges to users. Therefore, if you define roles, you can grant or revoke privileges to users, thereby automatically granting or revoking privileges. You can either create Roles or use the system roles pre-defined by oracle. Some of the privileges granted to the system roles are as given below: System Role Privileges Granted to the Role CONNECT CREATE TABLE, CREATE VIEW, CREATE SYNONYM, CREATE SEQUENCE, CREATE SESSION etc. RESOURCE CREATE PROCEDURE, CREATE SEQUENCE, CREATE TABLE, CREATE TRIGGER etc. The primary usage of the RESOURCE role is to restrict access to database objects. DBA ALL SYSTEM PRIVILEGES Creating Roles: Syntax:
  • 106. CREATE ROLE role_name [IDENTIFIED BY password]; Example: To create a role called "tisting" with password as "pwd", the code will be as follows: create role testing identified by pwd; We can GRANT or REVOKE privilege to a role as below. To grant CREATE TABLE privilege to a user by creating a testing role: First, create a testing Role: create role testing; Second, grant a CREATE TABLE privilege to the ROLE testing. You can add more privileges to the ROLE. grant create table to testing; Third, grant the role to a user. Create the user: create user user1 identified by pwd; Grant the Role: grant testing to user1; To revoke a CREATE TABLE privilege from testing ROLE, you can write:
  • 107. revoke create table from testing; Syntax to drop a role from the database: DROP ROLE role_name; Example: drop role testing; Oracle Built in Functions There are two types of functions in Oracle. 1) Single Row Functions: Single row or Scalar functions return a value for every row that is processed in a query. 2) Group Functions: These functions group the rows of data based on the values returned by the query. This is discussed in SQL GROUP Functions. There are four types of single row functions. They are: 1) Numeric Functions: These are functions that accept numeric input and return numeric values. 2) Character or Text Functions: 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.
  • 108. What is a DUAL Table in Oracle? This is a single row and single column dummy table provided by oracle. This is used to perform mathematical calculations without using a table. Example: select * from dual; Output: Example: select 777 * 888 from dual; Output: Table: netlink DUMMY X 777*888 689976
  • 109. E_ID E_SALARY E_NAME EMP_CITY 3 10000 Pravesh Bhopal 4 8000 Abhishek Bhopal 5 8000 SONAM Indore 1 18000.5 Nitin Gurgaon 2 18000 Akhilesh Gurgaon 6 8000 Jyotsana Mishra Indore 1) Numeric Functions: Numeric functions are used to perform operations on numbers. They accept numeric values as input and return numeric values as output. Function Name Return Value ABS (x) Absolute value of the number 'x'. CEIL (x) Integer value that is Greater than or equal to the number 'x'. FLOOR (x) Integer value that is Less than or equal to the number 'x'. TRUNC (x, y) Truncates value of number 'x' up to 'y' decimal places. ROUND (x, y) Rounded off value of the number 'x' up to the number 'y' decimal places. select abs(e_salary) from netlink; Output: ABS(E_SALARY) 10000 8000
  • 110. select ceil(e_salary) from netlink; Output: select floor(e_salary) from netlink; Output: FLOOR(E_SALARY) 10000 8000 18000 18000 select trunc(e_salary,3) from netlink; Output: 18000.5 18000 CEIL(E_SALARY) 10000 8000 18001 18000 TRUNC(E_SALARY,3) 10000 8000 18000.5 18000
  • 111. Character or Text Functions Character or text functions are used to manipulate text strings. They accept strings or characters as input and can return both character and number values as output. Function Name Return Value INITCAP (string_value) All the letters in 'string_value' is converted to mixed case. LTRIM (string_value, trim_text) All occurrences of 'trim_text' is removed from the left of 'string_value'. RTRIM (string_value, trim_text) All occurrences of 'trim_text' is removed from the right of'string_value' . TRIM (trim_text FROM 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) Number of characters in 'string_value'in returned. LPAD (string_value, n, pad_value) Returns 'string_value' left-padded with'pad_value' . The length of the whole string will be of 'n' characters. RPAD (string_value, n, pad_value) Returns 'string_value' right-padded with 'pad_value' . The length of the whole string will be of 'n' characters.
  • 112. select initcap('Pravesh') from netlink; Output: INITCAP('PRAVESH') Pravesh Pravesh Pravesh Pravesh Pravesh Pravesh select ltrim('Good Morning', 'Good') from emp; Output: LTRIM('GOODMORNING','GOOD') Morning select rtrim('Good Morning', 'Morning') from emp; Output: RTRIM('GOODMORNING','MORNING') Good select trim('G' from 'Good Morning') from emp; Output: TRIM('G'FROM'GOODMORNING') ood Morning select substr('Good Morning', 6, 6) from emp; Output: select length('Good Morning') from emp; Output: SUBSTR('GOODMORNING',6,6) Mornin LENGTH('GOODMORNING') 12
  • 113. select lpad('Good',6,'*') from emp; Output: LPAD('GOOD',6,'*') **Good select rpad('Good',9,'*') from emp; Output: 3) Date Functions These are functions that take values that are of datatype DATE as input and return values of datatypes DATE, except for the MONTHS_BETWEEN function, which returns a number as output. Function Name Return Value ADD_MONTHS (date, n) Returns a date value after adding 'n'months to the date 'x'. MONTHS_BETWEEN (x1, x2) Returns the number of months between dates x1 and x2. NEXT_DAY (x, week_day) Returns the next date of the 'week_day'on or after the date 'x' occurs. LAST_DAY (x) It is used to determine the number of days remaining in a month from the date 'x' specified. SYSDATE Returns the systems current date and time. NEW_TIME (x, zone1, zone2) Returns the date and time in zone2 if date 'x' represents the time in zone1. select add_months('7-oct-2010',3) from emp; RPAD('GOOD',9,'*') Good*****
  • 114. Output: ADD_MONTHS('7-OCT-2010',3) 07-JAN-11 select months_between('7-oct-2010','7-dec-2010') from emp; Output: MONTHS_BETWEEN('7-OCT-2010','7-DEC-2010') -2 select next_day ('7-oct-2010','Wednesday') from emp; Output: NEXT_DAY('7-OCT-2010','WEDNESDAY') 13-OCT-10 select last_day('7-oct-2010') from emp; Output: LAST_DAY('7-OCT-2010') 31-OCT-10 select new_time('7-oct-2010','gmt','est') from emp; Output: NEW_TIME('7-OCT-2010','GMT','EST') 06-OCT-10
  • 115. 3) Conversion Functions These are functions that help us to convert a value in one form to another form. For Ex: a null value into an actual value, or a value from one datatype to another datatype like NVL, TO_CHAR, TO_NUMBER, TO_DATE. Function Name Return Value TO_CHAR (x [,y]) Converts Numeric and Date values to a character string value. It cannot be used for calculations since it is a string value. TO_DATE (x ,[ date_format]) Converts a valid Numeric and Character values to a Date value. Date is formatted to the format specified by 'date_format'. NVL (x, y) If 'x' is NULL, replace it with 'y'. 'x' and 'y'must be of the same datatype. select to_char(3000,'$9999') from emp; Output: select to_char(sysdate,'day,month yyyy') from emp; TO_CHAR(3000,'$9999') $3000
  • 116. Output: select to_date('01-Jun-2010') from emp; Output: select nvl(null,1) from emp; Output: Note: Query to get the number of columns in a table: select COUNT(*) from dba_tab_columns where table_name = 'EMPLOYEE'; table_name should be in capital letters. TO_CHAR(SYSDATE,'DAY,MONTHYYYY') friday ,october 2010 TO_DATE('01-JUN-2010') 01-JUN-10 NVL(NULL,1) 1