Professional Documents
Culture Documents
DBMS Unit Iii
DBMS Unit Iii
DML
Examples of DML:
The values are separated commas and the values are entered in the same ORDER as specified by
the structure of the table.
3. Continuous Insertions.
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:
• VALUES (value_1,value_2,...) specifies the values to be added into the new row
Example :
Output:
I row created.
Explanation
• This command inserts the record Where the employee number is 1237, his name is kalai
and so on.
• 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'.
Output
Table created.
1 row created
SQL> INSERT INTO myTable VALUES ('Product Name 3', null, '10-DEC-05');
Output:
1 row created.
Output:
1 row created.
Example 2:
Output:
Table created
Student_id Name
Query for insert:
1 row created
output:
1 row created
output:
1 row created
Desc student;
Output;
student_id number(5)
name varchar2(12)
• 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:
Here, column1, column2, column3,...columnN are the names of the columns in the
table into which you want to insert the data.
Query
Create table customer(id int,name varchar2(12),age number(2),address varchar2(22),
salary number(4,2));
Output:
Table created
The following statements would create six records in the CUSTOMERS table.
You can create a record in the CUSTOMERS table by using the syntax(inserting records to all
fields) as shown below.
Syntax :
Oracle prompts the user to insert values onto all the columns of the table.
output:
1 row created
output:
1 row created
output:
1 row created
In the above method, if u want to insert three rows , three times insert statement will be given
Output:
I row created.
SQL> /
Output:
I row created.
SQL> /
Output:
I row created.
Query for select the table
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:
OUTPUT
Table created
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
Parameters
2) conditions: It specifies the conditions that must met for the records to be deleted.
For ex:
Output:
Student_id Name
101 akash
102 Balaji
103 brindha
output:
I row deleted
Output:
Student_id Name
101 akash
103 brindha
Delete the rows from the table Student where Age is 20.
Output:
The above query will delete two rows(third row and fifth row) and the table Student will now
look like,
Syntax:
Example
Output:
2 rows deleted
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!
SELECT Syntax
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:
Query 1:
Query 2:
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:
Parameters:
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:
Example:
First, let us see how the following SELECT query returns the duplicate salary records.
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.
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.
Two Types:
1.Column alias
2.Table alias
1.Column alias:
Example:
Output:
Example : 2
To fetch Branch using Stream as alias name and Grade as CGPA from table Student_Details.
Output:
2.Table alias:
Generally table aliases are used to fetch the data from more than just single table and connect
them through the field relations.
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.
Example-1
The following statement concatenates two strings 'Happy' and ' coding':
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:
For example,
to concatenate three strings: 'Happy', ' coding', and ' together', you use the concatenation
operator (||) as follows:
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
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.
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.
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 (*) :
4.Modulo division
Modulus ( % ) :
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:
Example:
Query 1
> operator
Query 2
Fetch all the details of employees having salary greater than 6000.
> OPERATOR
= OPERATOR
Operators List:
And OPERATOR
SELECT * FROM EMPLOYEES WHERE EMP_SALARY > 5000 AND EMP_AGE > 23;
Query 2
OR OPERATOR
BETWEEN operator
Basic Syntax:
It is used to fetch filtered data by searching for a particular pattern in where clause.
Basic Syntax:
pattern: exact value extracted from the pattern to get related data in
result set.
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
Syntax: IS 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.
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.
To sort in ascending or descending order we can use the keywords ASC or DESC
respectively.
Syntax:
Explanation:
column_name: name of the column according to which the data is needed to be arranged.
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.
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:
Explanation:
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.
where:
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
Output:
Issuing the DEFINE command with no arguments at all tells SQL*Plus to display all defined
variables with their contents;
for example:
Undefine command
• 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:
where:
You can delete several variables with one command by listing them out, separated by spaces.
Deleting a variable
SQL> UNDEFINE year = 1998
Output:
CASE STRUCTURE
• 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.
SYNTAX:
CASE
WHEN condition1 THEN result1
WHEN condition2 THEN result2
WHEN conditionN THEN resultN
ELSE result
END;
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.
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 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
CASE WHEN Quantity > 30 THEN 'The quantity is greater than 30'
END AS QuantityText
FROM OrderDetails;
Functions and Grouping:
Built-in functions –Grouping Data.
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.
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
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. 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.
1.ABS
2.FLOOR
3. CEIL
4.Exp
5.LN
6.MOD
7. POWER
8.ROUND
9.SIGN
10.SORT
11.TRUNC
1.ABS
Syntax
ABS (n)
Example
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:
output:
FLOOR(17.36)
------------
17
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
OUTPUT:
CEIL(15.7)
________
16
4.EXP:
Syntax
Exp (n)
Example
OUTPUT:
EXP(4)
_______
54.59815
Syntax
LN(n)
Example
SELECT LN(95) FROM DUAL
LN(95)
__________
4.5538769
Syntax
MOD (m,u)
Example
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
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
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
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
OUTPUT
Square root
_________
5.0990195
11.TRUNC
Syntax.
Example
OUTPUT:
Truncate
_______
15.7
OUTPUT:
Truncate
_______
15.79
TRUNC(25.465,0)
---------------
25
2.CHARACTER FUNCTION
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
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
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
Output
Character
________
4. CONCAT
Returns char1 concatenated with char 2. This Function is equivalent to the concatenation (||)
Syntax
Example:
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
Output
Capitalized
_________
The Soap
6. LTRIM() Function
EXAMPLE:
RESULT
----------
SQL Tutorial
7. REPLACE
Syntax
Example
SELECT REPLACE (' JACK and JUE',‘J‘,'BL‘) " Changes " FROM DUAL;
output
Changes
_________
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
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
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
Output
Next month
__________
20- SEP-20
4.Conversion function
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
OUTPUT
New date format
_____________
December 04,2020
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
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:
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.
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
OUTPUT:
Example query:
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.
Suppose that we want to get a list of movie category_id and corresponding years in which they
were released.
Example query
OUTPUT:
Having clause
Defintion:
• HAVING is like WHERE but operates on grouped records returned by a GROUP BY.
• Only the groups that meet the HAVING criteria will be returned.
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.
OUTPUT:
SET Operations
The SQL Set operation is used to combine the two or more SQL SELECT statements.
1. Union
2. UnionAll
3. Intersect
4. Minus
1. Union
• 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
Example Query :
UNION
Output
Union All operation is equal to the Union operation. It returns the set without removing
duplication and sorting the data.
Syntax:
UNION ALL
UNION ALL
Output:
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.
Syntax
INTERSECT
SELECT column_name FROM table2;
INTERSECT
Output:
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.
Syntax:
MINUS
MINUS
SELECT * FROM Second;
Output:
Akash 20 555
Arun 20 555
Balaji 19 560
Balu 20 570
Marks
555
560
570
Age
20
19
Akash 20 555
Arun 20 555
Balaji 19 560
Balu 20 570
age Marks
20 555
19 560
20 570
age
20
Akash 20 555
Arun 20 555
Balaji 19 560
Balu 20 570
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.
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
EXAMPLE:
Example Query
Output:
this join returns the cross product of all the records present in both the 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
ON table1.matching_column = table2.matching_column;
table1:First table.
Now, let us join these two tables using the INNER JOIN as follows
FROM CUSTOMERS
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
FROM CUSTOMERS
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
ON table1.matching_column = table2.matching_column;
Now, let us join these two tables in our SELECT statement as shown below.
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
ON table1.matching_column = table2.matching_column;
Now, let us join these two tables using FULL JOIN as follows.
FROM CUSTOMERS
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
Here, the WHERE clause could be any given expression based on your requirement.