Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 72

UNIT – III

Working with Tables: Data Management and Retrieval:

DML

(Data Manipulation Language) - Is used to restrict or grant access to tables

Examples of DML:

• INSERT – is used to insert data into a table.

• UPDATE – is used to update existing data within a table.

• DELETE – is used to delete records from a database table.

SELECT – Retrieves data from a table

Adding a new Row/Record – Insert command

Using INSERT command

Insert command is used to add one or more rows to a table.

The values are separated commas and the values are entered in the same ORDER as specified by
the structure of the table.

Inserting records into tables can be done in different ways:

1. Inserting records into all fields

2. Inserting records into selective fields

3. Continuous Insertions.

4. Inserting records using SELECT statement.

1. Inserting records into all fields

It is used to inserting records onto all the fields in the table. This method is called as
implicit method

In the implicit method, the column’s name is omitted from the columnlist in an insert
statement.

Syntax:

INSERT INTO TABLE_NAME VALUES (value1,value2,value3,...valueN);


• INSERT INTO `table_name` is the command that tells MySQL server to add a new row
into a table named `table_name.`

• VALUES (value_1,value_2,...) specifies the values to be added into the new row

Example :

INSERT INTO Employee VALUES (1237,‘Kalai‘, ‘10 -MAR-2000’, 5000);

The message displayed will be:

Output:

I row created.

Explanation

• This command inserts the record Where the employee number is 1237, his name is kalai
and so on.

• Always character data must be entered within single quotes.

• In the above example, the column called doj contains a date datatype while inserting data
values, the values must be enclosed within quotes. The standard format of entering the
date values is DD-MON-YY'.

Note : Any value other than number must be placed within single quotes. Otherwise

Rules:

When supplying the data values to be inserted into the new table, the following should be
considered:

• String data types - all the string values should be enclosed in single quotes.

• Numeric data types- all numeric values should be supplied directly without enclosing
them in single or double-quotes.

• Date data types - enclose date values in single quotes in the format 'YYYY-MM-DD'.

SQL> CREATE TABLE myTable ( name VARCHAR2(25), price NUMBER(4,2),


start_date DATE);

Output

Table created.

SQL> INSERT INTO myTable VALUES (NULL, 2.5, '29-JUN-04');


Output:

1 row created

SQL> INSERT INTO myTable VALUES ('Product Name 3', null, '10-DEC-05');

Output:

1 row created.

SQL> INSERT INTO myTable VALUES (NULL, NULL, '31-AUG-06');

Output:

1 row created.

Example 2:

Query for create:

Create table student(student_id number(5),name varchar2(12));

Output:

Table created

In database, the table is created is shown below

Student_id Name
Query for insert:

Insert into student values(101,’akash’);


output:

1 row created

Insert into student values(102,’balaji’);

output:

1 row created

Insert into student values(103,’brindha’);

output:

1 row created

Query for desc:

Desc student;

Output;

Name Null Type

student_id number(5)

name varchar2(12)

2. Inserting records into selective fields

• If you are adding values for all the columns of the table, you do not need to specify the
column names in the SQL query. This method is called as explicit method

• However, make sure the order of the values is in the same order as the columns in the
table.

Syntax:

INSERT INTO table_name (column1, column2, column3,...)VALUES (value1, val


ue2, value3, ...);

Here, column1, column2, column3,...columnN are the names of the columns in the
table into which you want to insert the data.

Create customer table

Query
Create table customer(id int,name varchar2(12),age number(2),address varchar2(22),

salary number(4,2));

Output:

Table created

Example (insert values int o table)

The following statements would create six records in the CUSTOMERS table.

1. INSERT INTO CUSTOMERS (ID,NAME,AGE,ADDRESS,SALARY) VALUES (1,


'Ramesh', 32, 'Ahmedabad', 2000.00 );

2. INSERT INTO CUSTOMERS (AGE,ADDRESS,SALARY) VALUES (25, 'Delhi',


1500.00 );

3. INSERT INTO CUSTOMERS (ID,NAME,AGE,ADDRESS) VALUES (3, 'kaushik', 23,


'Kota', 2000.00 );

4. INSERT INTO CUSTOMERS (ID,NAME,AGE,ADDRESS,SALARY) VALUES (4,


'Chaitali', 25, 'Mumbai', 6500.00 );

5. INSERT INTO CUSTOMERS (ID,NAME,AGE,ADDRESS,SALARY) VALUES (5,


'Hardik', 27, 'Bhopal', 8500.00 );

6.INSERT INTO CUSTOMERS (ID,NAME,AGE,ADDRESS,SALARY) VALUES (6,


'Komal', 22, 'MP', 4500.00 );

You can create a record in the CUSTOMERS table by using the syntax(inserting records to all
fields) as shown below.

INSERT INTO CUSTOMERS VALUES (7, 'Muffy', 24, 'Indore', 10000.00 );


3. Continuous Insertions(substitution variables)

Consider continuous insertion of records. In order to insert continuously, use "&"


(ampersand).

Syntax :

Insert into tablename Values (&Coll, &Co12, &Co13...);

Oracle prompts the user to insert values onto all the columns of the table.

Query for insert : (with out continuous insertion)

Insert into student values(101,’akash’);

output:

1 row created

Insert into student values(102,’balaji’);

output:

1 row created

Insert into student values(103,’brindha’);

output:

1 row created

In the above method, if u want to insert three rows , three times insert statement will be given

Example :( insert values with continuous method)


INSERT INTO student VALUES (&student_id, &name);

Output will be:

Enter value: for eno: 101

Enter valuefor name: akash

Output:

old I: insert into employee values (&student_id, &name)

new I : insert into employee values (101,’akash’)

I row created.

Now the same command can be re-executed by giving /(slash)

SQL> /

Enter value: for eno: 102

Enter valuefor name: balaji

Output:

old I: insert into employee values (&student_id, &name)

new I : insert into employee values (102,’balaji’)

I row created.

SQL> /

Enter value: for eno: 103

Enter valuefor name: brindha

Output:

old I: insert into employee values (&student_id, &name)

new I : insert into employee values (103,’brindha’)

I row created.
Query for select the table

Select * from student;

Output:

Student_id Name

101 akash
102 Balaji
103 brindha
Inserting records using SELECT statement

Records can be selected and inserted from one table to another table using INSERT! SELECT
statement.

Syntax:

INSERT INTO SELECT FROM [WHERE],

Example (table creation)

SQL> Create table student3(student_id number(5),name varchar2(12));

OUTPUT

Table created

SQL>INSERT INTO student3 SELECT * FROM student;

Query for select the table

Select * from student3;

Output:

Student_id Name

101 akash

102 Balaji

103 brindha
2.Deleting an Existing Rows/Records

In Oracle, DELETE statement is used to remove or delete a single record or multiple records
from a table.

Syntax

DELETE FROM table_name WHERE conditions;

Parameters

1) table_name: It specifies the table which you want to delete.

2) conditions: It specifies the conditions that must met for the records to be deleted.

3) DELETE – delete one row from a table

For ex:

Select * from student3;

Output:

Student_id Name

101 akash

102 Balaji

103 brindha

SQl> DELETE FROM student3 WHERE student_id=102;

output:

I row deleted

To view the table , the query is

SQL> select * from student3;

Output:

Student_id Name
101 akash

103 brindha

2. DELETE – delete multiple rows from a table

Delete the rows from the table Student where Age is 20.

This will delete 2 rows(third row and fifth row).

DELETE FROM Student WHERE Age = 20;

Output:

The above query will delete two rows(third row and fifth row) and the table Student will now
look like,

3. DELETE – delete all rows from a table


It is possible to delete all rows in a table without deleting the table.

Syntax:

DELETE FROM table_name; or DELETE * FROM table_name;

Example

DELETE FROM student3; or DELETE FROM student3

Output:

2 rows deleted

SQL >select * from student3

Student_id Name

All of the records in the table will be deleted, there are no records left to display. The
table Student will become empty!

Difference between delete and truncate


Retrieving Data from Table

The SQL SELECT Statement

The SELECT statement is used to select data from a database.

SELECT Syntax

SELECT column1, column2, … FROM table_name;

Here, column1, column2, ... are the field names of the table you want to select data from.

If you want to select all the fields available in the table, use the following syntax:

SELECT * FROM table_name;

Example: table name (customer)

CustomerID CustomerName ContactNumber Address City


1 priya 3449485 kallapatti kovai

2 arun 345356464 chitra kovai

3 arthi 34564646 Anna nagar chennai

4 brindha 345345345 saravanampatti kovai

5 saran 3453535 Nehru street bangalore

Query 1:

select * from customer;

CustomerID CustomerName ContactNumber Address City

1 priya 3449485 kallapatti kovai

2 arun 345356464 chitra kovai


3 arthi 34564646 Anna nagar chennai
4 brindha 345345345 saravanampatti kovai
5 saran 3453535 Nehru street bangalore

Query 2:

select CustomerID, Address from customer;

CustomerID Address
1 kallapatti

2 chitra
3 Anna nagar
4 saravanampatti

5 Nehru street

SET LINESIZE

LINESIZE: (Definition)

The LINESIZE setting controls the number of characters SQL*Plus prints on one physical line.
The default setting is 80 (150 in iSQL*Plus). The maximum width is system-dependent, though
it’s often 32,767 characters.

Syntax:

SET LIN[ESIZE] line_width

Parameters:

SET LIN[ESIZE] Is the command, which may be abbreviated SET LIN.

line_width Is the new line width, expressed as a number of characters.

The below figure shows the output from a select query with a default line size of 80
The below figure shows the output from a select query after changing the linesize to a higher
value.

DISTINCT Function

The SELECT DISTINCT statement is used to return only distinct (different) values.

Inside a table, a column often contains many duplicate values; and sometimes you only want to
list the different (distinct) values.

Syntax:

SELECT DISTINCT column1, column2, … FROM table_name;

Example:
First, let us see how the following SELECT query returns the duplicate salary records.

SQL> SELECT SALARY FROM CUSTOMERS ORDER BY SALARY;

This would produce the following result, where the salary (2000) is coming twice which is a
duplicate record from the original table.

Now, let us use the DISTINCT keyword with the above SELECT query and then see the result.

SQL> SELECT DISTINCT SALARY FROM CUSTOMERS ORDER BY SALARY;

This would produce the following result where we do not have any duplicate entry

SQL Aliases

• SQL aliases are used to give a table, or a column in a table, a temporary name.

• Aliases are often used to make column names more readable.

• An alias only exists for the duration of the query.

• temporary alias name to be used in replacement of original column name

Two Types:

1.Column alias

2.Table alias
1.Column alias:

SELECT column as alias_name FROM table_name;

column: fields in the table

alias_name: temporary alias name to be used in replacement of original column name


table_name: name of table

Example:

To fetch ROLL_NO from Student table using CODE as alias name.

SELECT ROLL_NO AS CODE FROM Student;

Output:

Example : 2

To fetch Branch using Stream as alias name and Grade as CGPA from table Student_Details.

SELECT Branch AS Stream,Grade as CGPA FROM Student_Details;

Output:
2.Table alias:

For table alias:SELECT column FROM table_name as alias_name;

Column: fields in the table

table_name: name of table

alias_name: temporary alias name to be used in replacement of original table nam

Generally table aliases are used to fetch the data from more than just single table and connect
them through the field relations.

• To fetch Grade and NAME of Student with Age = 20.

SELECT s.NAME, d.Grade FROM Student AS s, Student_Details AS d WHERE s.Age=20


AND s.ROLL_NO=d.ROLL_NO;

Output:
Concatenation

The Oracle CONCAT() function concatenates two strings and returns the combined string.

Syntax

CONCAT(string1,string2)

Noted that the Oracle CONCAT() function concatenates two strings only. If you want to
concatenate more than two strings, you need to apply the CONCAT() function multiple times or
use the concatenation operator (||).

Arguments

The CONCAT() function accepts two arguments whose data types can by any of the data types
CHAR, VARCHAR2, NCHAR, NVARCHAR2, CLOB, or NCLOB.

String1- is the first string value to concatenate with the second string value.

String2- is the second string value to be concatenated.

Example-1

The following statement concatenates two strings 'Happy' and ' coding':

SELECT CONCAT('Happy',' coding') FROM dual;

Output:

1 happycoding

Example-2

If you want to concatenate more than two strings, you need to apply the CONCAT() function
multiple times as shown in the following example:

SELECT CONCAT( CONCAT( 'Happy', ' coding' ), ' together' ) FROM dual;

Output:

1 Happycodingtogether

In this example:

The first CONCAT() function concatenates two strings: 'Happy' and ' coding', and returns a
result string.
The second CONCAT() function concatenates the result string of the first CONCAT() function,
which is 'Happy coding', with the string ' together' that results in 'Happy coding together'

Concatenation operator ||

In addition to the CONCAT() function, Oracle also provides you with the concatenation operator
(||) that allows you to concatenate two or more strings in a more readable fashion:

string1 || string2 || string3 || ...

For example,

to concatenate three strings: 'Happy', ' coding', and ' together', you use the concatenation
operator (||) as follows:

SELECT 'Happy' || ' coding' || ' together' FROM dual;

Output:

1 Happycodingtogether

Example-2

Employee table

The following statement uses the concatenation operator to construct the full name of employees
from the first name, space, and the last name:
Arithmetic Operations

Definition:

Arithmetic operators can perform arithmetical operations on numeric operands involved.


Arithmetic operators are addition(+), subtraction(-), multiplication(*) and division(/).

Arithmetic Operators

+ - : These denote a positive or negative expression, they are unary operators.

+ - : When they add or subtract, they are binary operators.

*/ : Multiply, divide. These are binary operators.


1.Addition

Addition (+) :

It is used to perform addition operation on the data items, items include either single column or
multiple columns.

Here we have done addition of 100 to each Employee’s salary i.e, addition operation on single
column.

Perform addition of 2 columns:

Here we have done addition of 2 columns with each other i.e, each employee’s employee_id is
added with its salary.

2.subtraction

Subtraction (-) :

It is use to perform subtraction operation on the data items, items include either single column
or multiple columns.
Here we have done subtraction of 100 to each Employee’s salary i.e, subtraction operation on
single column.

perform subtraction of 2 columns:

Here we have done subtraction of 2 columns with each other i.e, each employee’s employee_id
is subtracted from its salary.

3.Multiplication

Multiplication (*) :

It is use to perform multiplication of data items.


perform multiplication of 2 columns:

4.Modulo division

Modulus ( % ) :

It is use to get remainder when one data is divided by another.


perform modulus operation between 2 columns:

2. Restricting data with WHERE clause

Restricting data with WHERE clause

Where clause is used to fetch a particular row or set of rows from a table.

This clause filters records based on given conditions and only those row(s) comes out as result
that satisfies the condition defined in WHERE clause of the SQL query.

Syntax:

SELECT Column_name1, Column_name2, .... FROM Table_name WHERE Condition;

Example:

Query 1
> operator

SELECT EMP_NAME FROM EMPLOYEES WHERE EMP_AGE > 23;

Query 2

Fetch all the details of employees having salary greater than 6000.

> OPERATOR

SELECT * FROM EMPLOYEES WHERE EMP_SALARY > 6000;

Text Field in Where clause condition

= OPERATOR

SELECT SSN, EMP_NAME FROM EMPLOYEES WHERE EMP_NAME = 'Ajeet';


Operators allowed in The WHERE Clause conditions

Operators List:

> Greater than operator


< Less than operator
= Equal operator
>= Greater than or equal
<= Less than or equal
<> Not equal.
IN To specify the set of values
BETWEEN To specify the range of values
LIKE To specify the pattern

SQL where clause with multiple conditions


Query 1

And OPERATOR

SELECT * FROM EMPLOYEES WHERE EMP_SALARY > 5000 AND EMP_AGE > 23;

Query 2

OR OPERATOR

SELECT EMP_NAME FROM EMPLOYEES WHERE EMP_SALARY < 5000 OR EMP_AGE


< 20;
Query 3

BETWEEN operator

It is used to fetch filtered data in a given range inclusive of two values.

Basic Syntax:

SELECT column1,column2 FROM table_name WHERE column_name BETWEEN value1


AND value2;

SAMPLE TABLE NAME : STUDENT


LIKE operator

It is used to fetch filtered data by searching for a particular pattern in where clause.

Basic Syntax:

SELECT column1,column2 FROM table_name WHERE column_name LIKE pattern;

LIKE: operator name

pattern: exact value extracted from the pattern to get related data in
result set.

To fetch records of students where NAME contains the patter ‘AM’.


SELECT * FROM Student WHERE NAME LIKE '%AM%';

Output:

IN operator

It is used to fetch filtered data same as fetched by ‘=’ operator just the difference is that here we
can specify multiple values for which we can get the result set.
Basic Syntax:
SELECT column1,column2 FROM table_name WHERE column_name IN
(value1,value2,..);
IS NULL And IS NOT NULL

• NULL is a special value that signifies 'no value'.

• Comparing a column to NULL using the = operator is undefined.

• Instead, use WHERE IS NULL or WHERE IS NOT NULL.

Syntax: IS NULL

SELECT column-names FROM table-name WHERE column-name IS NULL

Syntax: IS NOT NULL

SELECT column-names FROM table-name WHERE column-name IS NOT NULL

Example:
SQL IS NOT NULL in where clause Example

The following SQL statement will fetch the EmployeeName & EmployeeAddress details of
employees where the value of EmployeePhoneNo column is not null.

SELECT EmployeeName, EmployeeAddress FROM Employees WHERE


EmployeePhoneNo IS NOT NULL;

Sorting
Sorting:

• The ORDER BY keyword is used to sort the result-set in ascending or descending order.

• The ORDER BY keyword sorts the records in ascending order by default. To sort the
records in descending order, use the DESC keyword.

Sorting can be done in two ways

1. Sort according to one column

2. Sort according to multiple columns

1.Sort according to one column:

To sort in ascending or descending order we can use the keywords ASC or DESC
respectively.

Syntax:

SELECT * FROM table_name ORDER BY column_name ASC|DESC

Explanation:

table_name: name of the table.

column_name: name of the column according to which the data is needed to be arranged.

ASC: to sort the data in ascending order.

DESC: to sort the data in descending order.

Example:

Student table
Sort according to single column: In this example we will fetch all data from the
table Student and sort the result in descending order according to the column ROLL_NO.

SELECT * FROM Student ORDER BY ROLL_NO DESC;

2. Sort according to multiple column:

To sort in ascending or descending order we can use the keywords ASC or DESC
respectively. To sort according to multiple columns, separate the names of columns by (,)
operator.

Syntax:

SELECT * FROM table_name ORDER BY column1 ASC|DESC , column2 ASC|DESC

Explanation:

table_name: name of the table.


column_name: name of the column according to which the data is needed to be arranged.

ASC: to sort the data in ascending order.

DESC: to sort the data in descending order.

example

Sort according to multiple columns:In this example we will fetch all data from the
table Student and then sort the result in ascending order first according to the column Age. and
then in descending order according to the column ROLL_NO.

SELECT * FROM Student ORDER BY Age ASC , ROLL_NO DESC;

where:

DEF[INE]: Is the command, which may be abbreviated to DEF.

variable_name :Is the name of the variable you want to create.

Text :Is the text you want to assign to that variable. This may optionally be enclosed by single or
double quotes, which you should use any time the value contains spaces or any other
nonalphabetic character.

Defining a variable

SQL> DEFINE year = 1998

SQL> DEFINE name= “akash”

SQL> DEFINE friendname =anil kumar

Output:

SQL> DEFINE year

DEFINE YEAR = "1998" (CHAR)


SQL> DEFINE name

DEFINE name = “akashy" (CHAR)

SQL> DEFINE friendname

DEFINE friendname = “anil" (CHAR)

Listing all variables

Issuing the DEFINE command with no arguments at all tells SQL*Plus to display all defined
variables with their contents;

for example:

SQL > DEFINE

DEFINE YEAR = "1998" (CHAR)

DEFINE name = “akashy" (CHAR)

DEFINE friendname = “anil" (CHAR)

DEFINE manager = “kavi" (CHAR)

DEFINElocation= “chennai" (CHAR)

Undefine command

The UNDEFINE Command

• The UNDEFINE command deletes a variable definition.

• If you have created a variable containing sensitive information, such as a password, you
can use UN-DEFINE to delete it when it is no longer needed.

Syntax:

UNDEF[INE] variable_name [ variable_name...]

where:

UNDEF[INE]= Is the command, and may be abbreviated to UNDEF.

variable_name =Is the name of a user variable to delete.

You can delete several variables with one command by listing them out, separated by spaces.

Deleting a variable
SQL> UNDEFINE year = 1998

SQL> UNDEFINE friendname =anil kumar

Output:

SQL> DEFINE year

SYMBOL YEAR IS UNDEFINED

SQL> DEFINE name

DEFINE name = “akashy" (CHAR)

SQL> DEFINE friendname

SYMBOL FRIENDNAME IS UNDEFINED

CASE STRUCTURE

The SQL CASE Statement

• The CASE statement goes through conditions and returns a value when the first condition
is met (like an IF-THEN-ELSE statement). So, once a condition is true, it will stop
reading and return the result. If no conditions are true, it returns the value in the ELSE
clause.

• If there is no ELSE part and no conditions are true, it returns NULL.

SYNTAX:

CASE
WHEN condition1 THEN result1
WHEN condition2 THEN result2
WHEN conditionN THEN resultN
ELSE result
END;

Explanation: Parameters or Arguments

Expression: The expression that will be compared to each of the values provided. (ie:
value_1, value_2, ... value_n).

value_1, value_2, ... value_n: The values that will be used in the evaluation. Values are
evaluated in the order listed. Once a value matches expression, the CASE statement will execute
the corresponding statements and not evaluate any further.
condition_1, condition_2, ... condition_n: The conditions that will be evaluated. Conditions
are evaluated in the order listed. Once a condition is found to be true, the CASE statement will
return the result and not evaluate the conditions any further. All conditions must be the same
datatype.

result_1, result_2, ... result_n : The value returned once a condition is found to be true. All
values must be the same datatype.

Rules for Simple Case:

Simple Case only allows equality check of Case_Expression with Value_1 to Value_N.

The Case_Expression is compared with Value, in order starting from the first value, i.e.,
Value_1. Below is the execution approach:

• If Case_Expression is equivalent to Value_1, then further WHEN…THEN


statements are skipped, and CASE execution will END immediately.

• If Case_Expression does not match with Value_1, then Case_Expression is


compared with Value_2 for equivalency. This process of comparing
Case_Expression with Value will continue until Case_Expression finds matching
equivalent value from the set of Value_1, Value_2,...

• If nothing matched, then control goes to ELSE statement, and Statement_Else will
get executed.

ELSE is optional.

• If ELSE is not present and Case_Expression matches with none of the values,
then Null will be displayed.

Example Query

SELECT OrderID, Quantity,

CASE WHEN Quantity > 30 THEN 'The quantity is greater than 30'

WHEN Quantity = 30 THEN 'The quantity is 30'

ELSE 'The quantity is under 30'

END AS QuantityText

FROM OrderDetails;
Functions and Grouping:
Built-in functions –Grouping Data.

Multiple Tables: Joins and Set operations:

Join – Set operations.

Built in functions

Function:

A function is a predefined formula which takes one or more arguments as input then process the
arguments and returns an output.

Types of SQL Function:

There are two types of SQL functions, aggregate functions, and scalar(non-aggregate) functions.

Aggregate functions operate on many records and produce a summary, works with GROUP BY

whereas non-aggregate functions(single row function) operate on each record independently.

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. The group functions are used to calculate
aggregate values like total or average, which return just one total or one average value after
processing a group of rows.

1) Single Row Functions:

There are four types of single row functions. They are:

1. Number function

2. Character function

3. Date function

4. Conversion function

1) Numeric Functions:

Numeric functions are used to perform operations on numbers. They accept numeric
values as input and return numeric values as output.

The numeric functions are

1.ABS

2.FLOOR

3. CEIL

4.Exp

5.LN

6.MOD

7. POWER

8.ROUND

9.SIGN

10.SORT

11.TRUNC

1.ABS

Return the absolute value of a number:

Syntax
ABS (n)

Example

SELECT ABS (-15) " Absolute " FROM DUAL;

OUTPUT:

Absolute

--------------

15

2. FLOOR

The SQL FLOOR() function rounded up any positive or negative decimal value down to
the next least integer value

Syntax:

Floor (n)

Example:

1. SELECT FLOOR(17.36) FROM dual;

output:

FLOOR(17.36)

------------

17

2. SELECT FLOOR(-17.36) FROM dual;

output:

FLOOR(-17.36)

------------

- 18
3.CEIL

CEIL() function is used to get the smallest integer which is greater than, or equal to, the
specified numeric expression.

Syntax

CEIL (n)

Example

SELECT CEIL (15.7) “ FROM DUAL;

OUTPUT:

CEIL(15.7)

________

16

4.EXP:

it is used to find the Exponent value

Syntax

Exp (n)

Example

SELECT EXP (4) FROM DUAL ;

OUTPUT:

EXP(4)

_______

54.59815

5.LN -Returns the natural logarithm of n, where n is greater than 0

Syntax

LN(n)

Example
SELECT LN(95) FROM DUAL

LN(95)

__________

4.5538769

6. MOD - Returns the remainder of m divided by n. Returns m if n is 0.

Syntax

MOD (m,u)

Example

SELECT MOD (11,4) " Modulus " FROM DUAL

Modulus

__________

7.POWER

Returns m raised to the nth power . The base m and-the exponent n can be any numbers,
but if m is negative , n must be an integer

Syntax

POWER ( m,n)

Example

SELECT POWER (3,2) " Raised " FROM DUAL

OUTPUT:

Raised

__________

8.ROUND
Returns n rounded to m places right of the decimal point; if m is omitted , n is rounded to
0 places . m can be negative to round off digits left of the decimal point . , m must be an integer.

Syntax

ROUND ( n{ ,m} )

Example

SELECT ROUND (15.193,1) " Round " FROM DUAL

OUTPUT

Round

_______

15.2

9.SIGN

If n < 0. the function returns -1; if n = 0, the function returns 0, if n>0 the function
returns 1.

Syntax

SIGN (n)

Example

SELECT SIGN (-15) " sign " FROM DUAL

output

Sign

______

-1

10. SQRT

Returns square root of n. The value of n. cannot be negative SQRT, returns a " real "
result

Syntax
SORT (n)

Example

SELECT SORT (26) " Square root " FROM DUAL;

OUTPUT

Square root

_________

5.0990195

11.TRUNC

Returns n truncated to m 1 places; if in is omitted , n is truncated to 0 places . m can be


negative to dill-mate (make zero) m digits left of the decimal point

Syntax.

TRUNC (n{ ,m})

Example

1. SELECT TRUNC (15.7954,1) " Truncate " FROM DUAL ;

OUTPUT:

Truncate

_______

15.7

2. SELECT TRUNC (15.7954,2) " Truncate " FROM DUAL ;

OUTPUT:

Truncate

_______

15.79

3. SELECT TRUNC (25.465,0) FROM DUAL ;


OUTPUT:

TRUNC(25.465,0)

---------------

25

2.CHARACTER FUNCTION

Character functions can return both numeric and character values .

THE VARIOUS CHARCATER FUNCTIONS ARE

1. ASCII

2. Length

3. CHR

4. Concat

5. Initcap

6. Ltrim

7. Substr

8. Upper

9. Lower

10. Replace

11. ASCII

Returns the decimal representation in the database character set of the first byte of char . If the
database character set is 7- bit ASCII , the function returns an ASCII Value

Syntax

ASCII(char)

Example

SELECT ASCII(‘Q‘) FROM DUAL ;

Output
ASCII (‘Q')

_________

81

2. LENGTH

Returns the length of characters in char . If Char hasdata type CHAR ,the length includes
all trailing blanks . If char is null , this function returns null.

Syntax

LENGTH (Char).

Example

SELECT LENGTH (' RADIANT’ ) " Length in character” FROM DUAL;

Output

Length in characters

________

3. CHR

Returns the character which is the binary equivalent of n in the database character set

Syntax

CHR(n)

Example

SELECT CHR(75) “character” FROM DUAL;

Output

Character

________

4. CONCAT
Returns char1 concatenated with char 2. This Function is equivalent to the concatenation (||)

Syntax

CONCAT ( char 1, char 2)

Example:

Select concat(‘hello’,’hai’) “result “ from dual;

Output

result

------------------------

hellohai

5. INIT CAP

Returns char, with the first letter of each word in uppercase and all other letters in
lowercase. Words are delimited by white spaces or characters that are not alphanumeric.

Syntax

INITCAP(char)

Example

SELECT INITCAP(‘the soap’) “Capitalized” FROM DUAL;

Output

Capitalized

_________

The Soap

6. LTRIM() Function

Remove leading spaces from a string:

EXAMPLE:

SELECT LTRIM(‘ SQL Tutorial’) “RESULT” FROM DUAL;


OUTPUT:

RESULT

----------

SQL Tutorial

7. REPLACE

Returns char with every occurrence of search_string replaced with replacement_string. If


search replacement_string is omitted or null, all occurrences of search_string are removed .
search string is null, char is returned. TES function provides a superset of the functionality
provided by the TRANSLATE function. TRANSLATE provides single character , one to of):
substitution . REPLACE allows you to substitute one string for another as well as to real
character strings.

Syntax

REPLACE ( char , search _string [ , replacernent_string ] )

Example

SELECT REPLACE (' JACK and JUE',‘J‘,'BL‘) " Changes " FROM DUAL;

output

Changes

_________

BLACK and BLUE

8.SUBSTR

Returns a Portion of char , beginning at character m,n characters long . If mis positive ,
ORACLE counts from the beginning of char to find the first character. If m is negative ORACLE
counts backwards from the end of char. The value of m cannot be 0. If n is omitted, ORACLE
returns all characters till the end of char. The value of n cannot be less than 1.

Syntax

SUBSTR (char,m [,n])

Example

1. SELECT SUBSTR (' ABCDEFG ' , 3,2) “substring " FROM DUAL;
output : substring

_______

CD

2. SELECT SUBSTR (' ABCDEFG ',-3,2 ) " substring " FROM DUAL.

output : substring

__________

EF

9.UPPER

Returnschar, with all letters uppercase . The return value has the same datatype as the
argument char

Syntax

UPPER (char)

Example

SELECT UPPER (' Large') " Uppercase " FROM DUAL;

Output

uppercase

__________

LARGE

10.LOWER

Returns char, with all letters in lowercase. The return value has the same datatype as the
argument char ( CHAR or VARCHR 2 )

Syntax

LOWER (char)

Example

SELECT LOWER (‘MR . SAMUEL HILLHOUSE ') "Lowercase " FROM DUAL ;

Output
Lowercase

____________________

mr . samuel hillhouse

3.Date Functions

1. ADD_MONTHS

Return the date d plus n months, The argument n can be any integer. If d is the last of the
month or if the resulting month has fewer days than the day component of d, thenif result is the
last day of the resulting month. Otherwise, the result has the same day component as d.

Syntax

ADD_MONTHS (d,n)

Example

SELECT ADD_MONTHS (sysdate, 1 ) “Next month " FROM DUAL ;

Output

Next month

__________

20- SEP-20

4.Conversion function

Conversion Function converts a value from one datatype to another.

1. TO_CHAR, date conversion

Converts d of DATE datatype- to value of VARCHAR2 ,datatype in the form specified by the
date format tint. If frit is not specified, d is converted to a VARCHAR2 value in the default date
format

Syntax

TO_CHAR(d[,fmt])

Example

SELECT TO _CHAR(SYSDATE,'Month DD, YYYY') "New date format” FROM dual;

OUTPUT
New date format

_____________

December 04,2020

2. TO_CHAR, number conversion

Converts n,or NUMBER datatype a Value ofVARCHAR2 datatype, using the optional
number format fmt. If no fmt is provided n is converted to a VARCHAR2 value exactly long
enough to hold its significant digits.

Syntax

TO _CHAR(n,[,fmt])

Example

SELECT TO CHAR(17145, ‘999G999‘) “Char” FROM DUAL;

OUTPUT

Char

___________

017,145

2. Grouping data

Definition:

The GROUP BY Statement in SQL is used to arrange identical data into groups with the help of
some functions. i.e if a particular column has same values in different rows then it will arrange
these rows in a group.

Important Points:

GROUP BY clause is used with the SELECT statement.

In the query, GROUP BY clause is placed after the WHERE clause.

In the query, GROUP BY clause is placed before ORDER BY clause if used any.
GROUP BY column_name1" is the clause that performs the grouping based on column_name1.

"[,column_name2,...]" is optional; represents other column names when the grouping is done on
more than one column.

Grouping using a Single Column

In order to help understand the effect of Group By clause, let's execute a simple query that
returns all the gender entries from the members table.

Example Query

SELECT gender FROM members ;

OUTPUT:

Example query:

Select gender from members group by gender;

OUTPUT:
Note only two results have been returned. This is because we only have two gender types Male
and Female. The GROUP BY clause grouped all the "Male" members together and returned only
a single row for it. It did the same with the "Female" members.

2. Grouping using multiple columns

Suppose that we want to get a list of movie category_id and corresponding years in which they
were released.

Example query

SELECT category_id, year_released FROM movies ;

OUTPUT:

The above results has many duplicates

Example query using group by:

Select category_id, year_released from movies group by category_id, year_released;


The GROUP BY clause operates on both the category id and year released to
identify unique rows in our above example.

Having clause

Defintion:

• HAVING is like WHERE but operates on grouped records returned by a GROUP BY.

• HAVING applies to summarized group records, whereas WHERE applies to individual


records.

• Only the groups that meet the HAVING criteria will be returned.

• HAVING requires that a GROUP BY clause is present.

• WHERE and HAVING can be used in the same query.

SYNTAX:

SELECT column-names

FROM table-name

GROUP BY column-names

HAVING condition

• It's not always that we will want to perform groupings on all the data in a given table.
There will be times when we will want to restrict our results to a certain given criteria. In
such cases , we can use the HAVING clause
• Suppose we want to know all the release years for movie category id 8. We would use the
following script to achieve our results.

• Example query using group by and having:

• Select *from movies group by category_id, year_released having category_id =8;

OUTPUT:

SET Operations

SQL Set Operation

The SQL Set operation is used to combine the two or more SQL SELECT statements.

Types of Set Operation

1. Union

2. UnionAll

3. Intersect

4. Minus

1. Union

• UNION is used to combine the results of two or more SELECT statements.


However it will eliminate duplicate rows from its resultset.

• In case of union, number of columns and datatype must be same in both the
tables, on which UNION operation is being applied.

Syntax
SELECT column_name FROM table1

UNION

SELECT column_name FROM table2;

Two example table

Table name : First

Example Query :

Union SQL query will be:

SELECT * FROM First

UNION

SELECT * FROM Second;

Output

The resultset table will look like:


2. Union All

Union All operation is equal to the Union operation. It returns the set without removing
duplication and sorting the data.

Syntax:

SELECT column_name FROM table1

UNION ALL

SELECT column_name FROM table2;

Example Query : Using the above First and Second table.

SELECT * FROM First

UNION ALL

SELECT * FROM Second;

Output:

The resultset table will look like:

3. Intersect

• It is used to combine two SELECT statements. The Intersect operation returns the
common rows from both the SELECT statements.

• In the Intersect operation, the number of datatype and columns must be the same.

• It has no duplicates and it arranges the data in ascending order by default.

Syntax

SELECT column_name FROM table1

INTERSECT
SELECT column_name FROM table2;

Example Query :Using the above First and Second table.

Intersect query will be:

SELECT * FROM First

INTERSECT

SELECT * FROM Second;

Output:

The resultset table will look like:

4. Minus

• It combines the result of two SELECT statements. Minus operator is used to display the
rows which are present in the first query but absent in the second query.

• It has no duplicates and data arranged in ascending order by default.

Syntax:

SELECT column_name FROM table1

MINUS

SELECT column_name FROM table2;

Example Query :Using the above First and Second table.

Minus query will be:

SELECT * FROM First

MINUS
SELECT * FROM Second;

Output:

The resultset table will look like:

Sample query for grouping

1. Create table student(name varchar2(12), age number(2), marks number(4));

2. Insert into student values(‘akash’, 20, 555);

Insert into student values(‘arun’, 20, 555);

Insert into student values(‘balaji’, 19, 560);

Insert into student values(‘balu’, 20, 570);

Name Age Marks

Akash 20 555

Arun 20 555

Balaji 19 560

Balu 20 570

Sample query for grouping in single column

1. Select marks from student group by mark;

Marks
555
560
570

2. Select age from student group by age;

Age

20
19

Sample query for grouping in multiple column

Name Age Marks

Akash 20 555
Arun 20 555
Balaji 19 560
Balu 20 570

1. Select age,marks from student group by age, marks;

age Marks

20 555
19 560

20 570

Sample query for grouping in single column by using having clause

Name Age Marks


Akash 20 555
Arun 20 555
Balaji 19 560
Balu 20 570

Select age from student group by age having age=20;

age

20

Sample query for grouping in multiple column by using having clause

Name Age Marks

Akash 20 555
Arun 20 555
Balaji 19 560
Balu 20 570

Select age,marks from student group by age, marks having age=20;

age Marks

20 555
20 570
JOIN Operations

SQL JOIN

The SQL Joins clause is used to combine records from two or more tables in a database.

A JOIN is a means for combining fields from two tables by using values common to each.

Different types of Joins are:

CARTESIAN JOIN
INNER JOIN

LEFT JOIN

RIGHT JOIN

FULL JOIN

SELF JOIN

1.Cross JOIN or Cartesian Product- returns the Cartesian product of the sets of records from
the two or more joined tables.

This type of JOIN returns the cartesian product of rows from the tables in Join. It will return a
table which consists of records which combines each row from the first table with each row of
the second table.

Syntax

SELECT column-name-list FROM table-name1 CROSS JOIN table-name2;

EXAMPLE:

Example Query

SELECT * FROM class CROSS JOIN class_info;

Output:
this join returns the cross product of all the records present in both the tables

2.INNER JOIN: returns rows when there is a match in both tables.

The INNER JOIN keyword selects all rows from both the tables as long as the condition
satisfies.

This keyword will create the result-set by combining all rows from both the tables where
the condition satisfies i.e value of the common field will be same.

Syntax:

SELECT table1.column1,table1.column2,table2.column1,....

FROM table1

INNER JOIN table2

ON table1.matching_column = table2.matching_column;

table1:First table.

table2: Second table.

matching_column: Column common to both the tables.


EXAMPLE

Now, let us join these two tables using the INNER JOIN as follows

SQL> SELECT ID, NAME, AMOUNT, DATE

FROM CUSTOMERS

INNER JOIN ORDERS

ON CUSTOMERS.ID = ORDERS.CUSTOMER_ID;

output
3.LEFT JOIN: returns all rows from the left table, even if there are no matches in the right
table.

This join returns all the rows of the table on the left side of the join and matching rows for the
table on the right side of join.

The rows for which there is no matching row on right side, the result-set will contain null. LEFT
JOIN is also known as LEFT OUTER JOIN.

Syntax:

SELECT table1.column1,table1.column2,table2.column1,....

FROM table1

LEFT JOIN table2 ON table1.matching_column = table2.matching_column;

table1: First table.

table2: Second table

matching_column: Column common to both the tables.


let us join these two tables using the LEFT JOIN as follows.

SQL> SELECT ID, NAME, AMOUNT, DATE

FROM CUSTOMERS

LEFT JOIN ORDERS

ON CUSTOMERS.ID = ORDERS.CUSTOMER_ID;

Output:

4. RIGHT JOIN: returns all rows from the right table, even if there are no matches in the left
table.

RIGHT JOIN is similar to LEFT JOIN. This join returns all the rows of the table on the right side
of the join and matching rows for the table on the left side of join. The rows for which there is no
matching row on left side, the result-set will contain null. RIGHT JOIN is also known as RIGHT
OUTER JOIN.

Syntax:

SELECT table1.column1,table1.column2,table2.column1,....
FROM table1

RIGHT JOIN table2

ON table1.matching_column = table2.matching_column;

table1: First table.

table2: Second table

matching_column: Column common to both the tables.

Now, let us join these two tables in our SELECT statement as shown below.

SQL> SELECT ID, NAME, AGE, AMOUNT

FROM CUSTOMERS, ORDERS

WHERE CUSTOMERS.ID = ORDERS.CUSTOMER_ID;

Output

5. FULL JOIN: returns rows when there is a match in one of the tables

FULL JOIN creates the result-set by combining result of both LEFT JOIN and RIGHT JOIN.
The result-set will contain all the rows from both the tables. The rows for which there is no
matching, the result-set will contain NULL values.
Syntax:

SELECT table1.column1,table1.column2,table2.column1,....

FROM table1

FULL JOIN table2

ON table1.matching_column = table2.matching_column;

table1: First table.

table2: Second table

matching_column: Column common to both the tables.

Now, let us join these two tables using FULL JOIN as follows.

SQL> SELECT ID, NAME, AMOUNT, DATE

FROM CUSTOMERS

FULL JOIN ORDERS

ON CUSTOMERS.ID = ORDERS.CUSTOMER_ID;

Output:

6.Self join
The SQL SELF JOIN is used to join a table to itself as if the table were two tables; temporarily
renaming at least one table in the SQL statement.

Syntax

SELECT a.column_name, b.column_name... FROM table1 a, table1 b

WHERE a.common_field = b.common_field;

Here, the WHERE clause could be any given expression based on your requirement.

You might also like