0% found this document useful (0 votes)
30 views62 pages

DMS Unit 3

Uploaded by

1603swatisingh
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
30 views62 pages

DMS Unit 3

Uploaded by

1603swatisingh
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 62

DMS unit 3

DM 22319 unit 1

● SQL string functions are primarily utilized for string manipulation.


● The built-in SQL String functions make it easier for us to find and
alter string values.
● For example, cutting blanks off a string value for display.
● You can use the LEN function to find the length of a string.
● It takes a single parameter containing a string expression,
concatenating two strings.

Vidya Lunge 1
DM 22319 unit 1

● You can find the given the word from the sentence; even you can
substring the character up to the given point in the string.
● You can find a word from the given point and of the given length
using the MID function.
● You can also find the nth position of the given the word in a string.

String Functions in SQL


ASCII(): It gives you the ASCII value of a character.
Example:
SELECT ASCII('t') from dual;
Result: 116

CHAR_LENGTH(): It gives you the number of characters in the string.


Example:
SELECT CHAR_LENGTH('world!') from dual;
Result: 6

CHARACTER_LENGTH(): It gives you the number of characters in a


given set of strings.
Example:
SELECT CHARACTER_LENGTH( 'educba.com' );
Result: 10

CONCAT(): It appends two strings to create the new single string, as


shown in the example.
Example:
SELECT 'educba' || ' ' || '.com' FROM viber;
Result: ‘educba.com’

CONCAT_WS(): It appends two strings with a given symbol in between


to concatenate them, as shown in the example.
Example:

SELECT CONCAT_WS('_', 'educba', 'to', 'learn');

Vidya Lunge 2
DM 22319 unit 1

Result: educba_to_learn

FIND_IN_SET(): It finds out the index position of any symbol or


character from the given set of characteristics.
Example:

SELECT FIND_IN_SET('v', 'z, x, v, b, n, m');


Result: 3

FORMAT(): It changes the format of the text from a string to any other
format.
Example:

FORMAT("0.254", "Percent");
Result: ‘25.40%’

INSERT(): It helps you insert text, integer, float, or double into your
database.
Example:

INSERT INTO mydb (name, age) VALUES (sdf, 20);


Result: inserted successfully

INSTR(): It gives you the first occurrence of the index of a character in


the string.
Example:

INSTR('educba to learn', 'e');

Result: 1 (the first occurrence of ‘e’)

LCASE(): It will replace every character in the string in their lowercase


letter.
Example:

LCASE("eduCBA.com To Learn");

Vidya Lunge 3
DM 22319 unit 1

Result: educba.com to learn

INITCAP()
LOWER()
RIGHT()

LEFT(): It is used to get the substring from the left of the string to the
given index position.
Example:

SELECT LEFT('educba.com', 3) from dual;

Result: edu

LENGTH(): gives you the length of the string.


Example:

LENGTH('educba.com');
Result: 10

LOCATE(): It gives you the position of a substring in the given string.


Example:

SELECT LOCATE('cba', 'educba.com', 1);


Result: 4

LOWER(): It converts every character in a string to lowercase from


uppercase.
Example:

SELECT LOWER('EDUCBA.COM');
Result: educba.com

Vidya Lunge 4
DM 22319 unit 1

LPAD(): It adds left padding with the given symbol to make the string of
a given size.
Example:

LPAD('yahoo', 7, '@');

Result:@@yahoo

LTRIM(): It trims the given character from the left of the string.
Example:

LTRIM('345yahoo', '345');

RPAD()

RTRIM()

Result: yahoo

MID(): It gives you the substring from a given position to the number of
characters in the string.
Example:

MID("educba.com", 3, 2);

Result: cba

POSITION(): It gives you the index position of the character in the


string.

Example:

SELECT POSITION('u' IN 'educba.com');

Vidya Lunge 5
DM 22319 unit 1

Result: 3

REPEAT(): It repeats the string to the number of times given.


Example:

SELECT REPEAT('educba', 2);

Result: educbaeducba

REPLACE(): It returns a new string by removing the given string from


the original.
Example:

REPLACE('456yahoo456', '456');

Result: yahoo

REVERSE(): It reverses the characters in a string.


Example:

SELECT REVERSE('educba.com');

Result: moc.abcuda

RIGHT(): It is used to get the substring from the right of the string to the
given index.
Example:

SELECT RIGHT('educba.com', 4);

Result: ‘.com’

RPAD(): It adds the right padding with the given symbol to make the
string of the given size.

Vidya Lunge 6
DM 22319 unit 1

Example:

RPAD('educba', 7, '@');

Result: ‘educba@@’

RTRIM(): It trims the given character from the right of the string.

Example:

RTRIM('educbapou', 'pou');

Result: ‘educba’

SPACE(): It adds the number of spaces specified.

Example:

SELECT SPACE(6);

Result: ‘ ‘

STRCMP(): matches two strings.

○ If both the strings are the same, it gives 0.


○ If the first is smaller than the second, then it gives -1.
○ If the first is bigger than the second, then it gives 1.

Example:

Vidya Lunge 7
DM 22319 unit 1

SELECT STRCMP('zomato.com', 'educba.com');

Result: 0

SUBSTR(): It returns a new substring from a given position to the


number of characters.

Example:

SUBSTR('educba.com', 1, 5);

Result: ‘educba’

SUBSTRING(): It gives you the substring character from the given


string.

Example:

SELECT SUBSTRING('eduCba.com', 4, 1);

Result: ‘C’

SUBSTRING_INDEX(): It gives you the substring until it finds the


given symbol.

Example:

SELECT SUBSTRING_INDEX( 'https://www.educba.com' , '/', 1);

Result: ‘https:’

Vidya Lunge 8
DM 22319 unit 1

TRIM(): It trims the given character from the string.

Example:

TRIM(LEADING '333' FROM '333567');

Result: 567

UCASE(): It will replace every character in the string in their uppercase


letter.

Example:

UCASE("EduCbA");

Result: EDUCBA

+++++++++++++++++++++++++++++++++++++++++++++++++++
+++++

SQL arithmetic function


Mathematical functions are very important in SQL to implement different
mathematical concepts in queries.
Some of the the major mathematical functions in SQL are as follows −

ABS(X)
This function returns the absolute value of X. For example −

Select abs(-6) from dual;


This returns 6.

Vidya Lunge 9
DM 22319 unit 1

MOD(X,Y)
The variable X is divided by Y and their remainder is returned. For example −

Select mod(9,5) from dual;


This returns 4.

SIGN(X)
This method returns 1 if X is positive, -1 if it is negative and 0 if the value of X is
0. For example −

Select sign(10) from dual;


This returns 1.

FLOOR(X)
This returns the largest integer value that is either less than X or equal to it. For
example −
Select floor(5.7) from dual;
This returns 5.

CEIL(X)
This returns the smallest integer value that is either more than X or equal to it. For
example −
Select ceil(5.7);
This returns 6.

ROUND(X)
This function returns the value of X rounded off to the whole integer that is nearest
to it. For example −
Select round(5.7);
This returns 6.
Select round(5.3);

Vidya Lunge 10
DM 22319 unit 1

POWER(X,Y)
This function returns the value of x raised to the power of Y For example −
Select power(2,5);
This returns 32.

SQRT(X)
This function returns the square root of X. For example −
Select sqrt(9);
This returns 3.

ASIN(X)
This function accepts a Sin value as the input and returns the angle in radians. For
example −
Select asin(0);
This returns 0.

ACOS(X)
This function accepts a Cos value as the input and returns the angle in radians. For
example −
Select acos(1);
This returns 0.

ATAN(X)
This function accepts a Tan value as the input and returns the angle in radians. For
example −
Select atan(0);
This returns 0.

SIN(X)
This function accepts an angle in radians as its parameter and returns its Sine
value. For example −

Vidya Lunge 11
DM 22319 unit 1

Select sin(0);
This returns 0.

COS(X)
This function accepts an angle in radians as its parameter and returns its Cosine
value. For example −
Select cos(0);
This returns 1.

TAN(X)
This function accepts an angle in radians as its parameter and returns its Tan value.
For example −
Select tan(0);
This returns 0

SQL arithmetic functions are:

Function Description
s

ABS() This SQL ABS() returns the absolute value of a number


passed as an argument.

CEIL() This SQL CEIL() will rounded up any positive or


negative decimal value within the function upwards.

Vidya Lunge 12
DM 22319 unit 1

FLOOR() The SQL FLOOR() rounded up any positive or


negative decimal value down to the next least integer
value.

EXP() The SQL EXP() returns e raised to the n-th power(n is


the numeric expression), where e is the base of natural
algorithm and the value of e is approximately
2.71828183.

LN() The SQL LN() function returns the natural logarithm of


n, where n is greater than 0 and its base is a number
equal to approximately 2.71828183.

MOD() This SQL MOD() function returns the remainder from a


division.

POWER( This SQL POWER() function returns the value of a


) number raised to another, where both of the numbers
are passed as arguments.

SQRT() The SQL SQRT() returns the square root of given value
in the argument.

Refer this for example of all functions:


:https://www.w3resource.com/sql/arithmetic-functions/sql-arithmetic-fu
nction.php

Vidya Lunge 13
DM 22319 unit 1

Date and time functions in DBMS:


The different date and time functions are as follows −
ADDDATE(DATE,DAYS)
The numbers of days in integer form (DAYS) is added to the
specified date.
This is the value returned by the function. For example −
sql> SELECT ADDDATE('2018-08-01', 31) from dual ;
+---------------------------------------------------------+
| DATE_ADD('2018-08-01', INTERVAL 31 DAY) |
+---------------------------------------------------------+
| 2018-09-01 |
+---------------------------------------------------------+
1 row in set (0.00 sec)
This function adds 31 days to the given date i.e. ‘2018-08-01’ and
returns the resultant date i.e. ‘2018-09-01’.
ADDTIME(exp1,exp2)
This function adds the two expressions exp1 and exp2 and displays
the result. In this case, exp1 can be a datetime or time expression
and exp2 is a time expression. For example:
sql> SELECT ADDTIME('2018-08-01 23:59:59.999999','1 1:1:1.000002') from
dual;
+---------------------------------------------------------+
|ADDTIME('2018-08-01 23:59:59.999999','1 1:1:1.000002') |
+---------------------------------------------------------+
| 2018-08-02 01:01:01.000001 |
+---------------------------------------------------------+
1 row in set (0.00 sec)

Vidya Lunge 14
DM 22319 unit 1

The time '1 1:1:1.000002' is added to the datetime function


'2018-08-01 23:59:59.999999' to give the resultant value ‘2018-08-02
01:01:01.000001’
CURDATE()
This returns the current date of the system in the YYYY-MM-DD
format. For example −
sql> SELECT CURDATE() from dual;
+---------------------------------------------------------+
| CURDATE() |
+---------------------------------------------------------+
| 2018-08-01 |
+---------------------------------------------------------+
1 row in set (0.00 sec)
This function returns the current date i.e. ‘2018-08-01’
CURTIME()
This returns the current time of the system from the current time
zone in the format HH:MM:SS. For example −
sql> SELECT CURTIME() from dual;;
+---------------------------------------------------------+
| CURTIME() |
+---------------------------------------------------------+
| 10:56:35 |
+---------------------------------------------------------+
1 row in set (0.00 sec)
This function returns the current time i.e ‘10:56:35’
DAYNAME(date)
For the given date, this function returns the corresponding day of
the week. For example −

Vidya Lunge 15
DM 22319 unit 1

sql> SELECT DAYNAME('2018-08-01') from dual;;


+---------------------------------------------------------+
| DAYNAME('2018-08-01') |
+---------------------------------------------------------+
| Wednesday |
+---------------------------------------------------------+
1 row in set (0.00 sec)
For the date '2018-08-01’, this function returns the day of the week
i.e. Wednesday.
DAYOFMONTH(date)
For the given date, it returns the day of the month the date is on.
The value of day of the month ranges from 1 to 31. For example −
sql> SELECT DAYOFMONTH('2018-02-15') from dual;;
+---------------------------------------------------------+
| DAYOFMONTH('2018-02-15') |
+---------------------------------------------------------+
| 15 |
+---------------------------------------------------------+
1 row in set (0.00 sec)
This returns the day of the month '2018-02-15' falls on i.e 15.
DAYOFWEEK(date)
For the given date, it returns the day of the week the date is on. The
value of day of the week ranges from 1 to 7 (Sunday is 1 and
Saturday is 7). For example −
sql> SELECT DAYOFWEEK('2018-02-15');
+---------------------------------------------------------+
|DAYOFWEEK('2018-02-15') |
+---------------------------------------------------------+
|5|
+---------------------------------------------------------+

Vidya Lunge 16
DM 22319 unit 1

1 row in set (0.00 sec)


This returns the day of the week '2018-02-15' falls on i.e 5.
DAYOFYEAR(date)
For the given date, it returns the day of the year the date is on.
The value of day of the year ranges from 1 to 366. For example −
sql> SELECT DAYOFYEAR('2018-02-15') from dual;
+---------------------------------------------------------+
| DAYOFYEAR('2018-02-15') |
+---------------------------------------------------------+
| 46 |
+---------------------------------------------------------+
1 row in set (0.00 sec)
This returns the day of the year '2018-02-15' falls on i.e 46.
MONTH(date)
It returns the month value for the corresponding date. The range of
the month is from 1 to 12. For example −
sql> SELECT MONTH('2018-08-01') from dual;;
+---------------------------------------------------------+
| MONTH('2018-08-01') |
+---------------------------------------------------------+
|8|
+---------------------------------------------------------+
1 row in set (0.00 sec)
This returns the month number for '2018-08-01' which is 8.
TIME(expr)
This function displays the time part of a time or date time
expression in the form of a string. For example −
sql> SELECT TIME('2018-08-01 11:33:25');

Vidya Lunge 17
DM 22319 unit 1

+---------------------------------------------------------+
| TIME('2018-08-01 11:33:25') |
+---------------------------------------------------------+
| 11:33:25 |
+---------------------------------------------------------+
1 row in set (0.00 sec)
This displays the time part of '2018-08-01 11:33:25' in the form of a
string.

Dual table
What is DUAL table in SQL/oracle?
● DUAL is a table automatically created by Oracle Database along with
the data dictionary.
● DUAL is in the schema of the user SYS but is accessible by the name
DUAL to all users.
● It has one column, DUMMY , defined to be VARCHAR2(1) , and contains
one row with a value X .
● It is suitable for use in selecting a pseudo column such as SYSDATE or
USER.

SQL Aggregate Functions


● SQL aggregation function is used to perform the calculations on
multiple rows of a single column of a table. It returns a single value.

● It is also used to summarize the data.

Types of SQL Aggregation Function

Vidya Lunge 18
DM 22319 unit 1

1. COUNT FUNCTION

● COUNT function is used to Count the number of rows in a database table.

● It can work on both numeric and non-numeric data types.

● COUNT function uses the COUNT(*) that returns the count of all the rows
in a specified table.

● COUNT(*) considers duplicate and Null.

Syntax

1. COUNT(*) or COUNT( [ALL|DISTINCT] expression )


2. COUNT(*) or COUNT(ALL )
3. COUNT( DISTINCT )

Sample table:

PRODUCT_MAST

Vidya Lunge 19
DM 22319 unit 1

PRODUCT COMPANY QTY RATE COST

Item1 Com1 2 10 20

Item2 Com2 3 25 75

Item3 Com1 2 30 60

Item4 Com3 5 10 50

Item5 Com2 2 20 40

Item6 Com1 3 25 75

Item7 Com1 5 30 150

Item8 Com1 3 10 30

Item9 Com2 2 25 50

Item10 Com3 4 30 120

Example: COUNT()

Vidya Lunge 20
DM 22319 unit 1

1. SELECT COUNT(*)
2. FROM PRODUCT_MAST;

Output:

10

Example: COUNT with WHERE

1. SELECT COUNT(*)
2. FROM PRODUCT_MAST;
3. WHERE RATE>=20;

Output:

Example: COUNT() with DISTINCT

1. SELECT COUNT(DISTINCT COMPANY)


2. FROM PRODUCT_MAST;

Output:

Example: COUNT() with GROUP BY

1. SELECT COMPANY, COUNT(*)


2. FROM PRODUCT_MAST
3. GROUP BY COMPANY;

Vidya Lunge 21
DM 22319 unit 1

Output:

Com1 5
Com2 3
Com3 2

Example: COUNT() with HAVING

1. SELECT COMPANY, COUNT(*)


2. FROM PRODUCT_MAST
3. GROUP BY COMPANY
4. HAVING COUNT(*)>2;

Output:

Com1 5
Com2 3

2. SUM Function
Sum function is used to calculate the sum of all selected columns. It works on
numeric fields only.

Syntax

1. SUM() or SUM( [ALL|DISTINCT] expression )

Example: SUM()

1. SELECT SUM(COST)
2. FROM PRODUCT_MAST;

Vidya Lunge 22
DM 22319 unit 1

Output:

670

Example: SUM() with WHERE

1. SELECT SUM(COST)
2. FROM PRODUCT_MAST
3. WHERE QTY>3;

Output:

320

Example: SUM() with GROUP BY

1. SELECT SUM(COST)
2. FROM PRODUCT_MAST
3. WHERE QTY>3
4. GROUP BY COMPANY;

Output:

Com1 150
Com2 170

Example: SUM() with HAVING

1. SELECT COMPANY, SUM(COST)


2. FROM PRODUCT_MAST
3. GROUP BY COMPANY

Vidya Lunge 23
DM 22319 unit 1

4. HAVING SUM(COST)>=170;

Output:

Com1 335
Com3 170

3. AVG function
The AVG function is used to calculate the average value of the numeric type.
AVG function returns the average of all non-Null values.

Syntax

1. AVG()
2. or
3. AVG( [ALL|DISTINCT] expression )

Example:

1. SELECT AVG(COST)
2. FROM PRODUCT_MAST;

Output:

67.00

4. MAX Function
MAX function is used to find the maximum value of a certain column. This
function determines the largest value of all selected values of a column.

Syntax

Vidya Lunge 24
DM 22319 unit 1

1. MAX()
2. or
3. MAX( [ALL|DISTINCT] expression )

Example:

1. SELECT MAX(RATE)
2. FROM PRODUCT_MAST;

30

5. MIN Function
MIN function is used to find the minimum value of a certain column. This
function determines the smallest value of all selected values of a column.

Syntax

1. MIN()
2. or
3. MIN( [ALL|DISTINCT] expression )

Example:

1. SELECT MIN(RATE)
2. FROM PRODUCT_MAST;

Output:

10

Vidya Lunge 25
DM 22319 unit 1

SQL Clauses
The following are the various SQL clauses:

1. GROUP BY

● SQL GROUP BY statement is used to arrange identical data into groups.

● The GROUP BY statement is used with the SQL SELECT statement.

● The GROUP BY statement follows the WHERE clause in a SELECT


statement and precedes the ORDER BY clause.

● The GROUP BY statement is used with aggregation function.

Syntax

1. SELECT column
2. FROM table_name
3. WHERE conditions
4. GROUP BY column
5. ORDER BY column

Vidya Lunge 26
DM 22319 unit 1

Sample table:

PRODUCT_MAST

PRODUCT COMPANY QTY RATE COST

Item1 Com1 2 10 20

Item2 Com2 3 25 75

Item3 Com1 2 30 60

Item4 Com3 5 10 50

Item5 Com2 2 20 40

Item6 Cpm1 3 25 75

Item7 Com1 5 30 150

Item8 Com1 3 10 30

Item9 Com2 2 25 50

Item10 Com3 4 30 120

Example:

Vidya Lunge 27
DM 22319 unit 1

1. SELECT COMPANY, COUNT(*)


2. FROM PRODUCT_MAST
3. GROUP BY COMPANY;

Output:

Com1 5
Com2 3
Com3 2

2. HAVING

● HAVING clause is used to specify a search condition for a group or an


aggregate.

● Having is used in a GROUP BY clause.

● If you are not using GROUP BY clause then you can use HAVING
function like a WHERE clause.

Syntax:

1. SELECT column1, column2


2. FROM table_name
3. WHERE conditions
4. GROUP BY column1, column2
5. HAVING conditions
6. ORDER BY column1, column2;

Vidya Lunge 28
DM 22319 unit 1

Example:

1. SELECT COMPANY, COUNT(*)


2. FROM PRODUCT_MAST
3. GROUP BY COMPANY
4. HAVING COUNT(*)>2;

Output:

Com1 5
Com2 3

3. ORDER BY

● The ORDER BY clause sorts the result-set in ascending or descending order.

● It sorts the records in ascending order by default. DESC keyword is used to


sort the records in descending order.

Syntax:

1. SELECT column1, column2


2. FROM table_name
3. WHERE condition
4. ORDER BY column1, column2... ASC|DESC;

Where

ASC: It is used to sort the result set in ascending order by expression.

DESC: It sorts the result set in descending order by expression.

Vidya Lunge 29
DM 22319 unit 1

Example: Sorting Results in Ascending Order


Table:

CUSTOMER

CUSTOMER_ID NAME ADDRESS

12 Kathrin US

23 David Bangkok

34 Alina Dubai

45 John UK

56 Harry US

Enter the following SQL statement:

1. SELECT *
2. FROM CUSTOMER
3. ORDER BY NAME;

Output:

CUSTOMER_ID NAME ADDRESS

Vidya Lunge 30
DM 22319 unit 1

34 Alina Dubai

23 David Bangkok

56 Harry US

45 John UK

12 Kathrin US

Example: Sorting Results in Descending Order


Using the above CUSTOMER table

1. SELECT *
2. FROM CUSTOMER
3. ORDER BY NAME DESC;

Output:

CUSTOMER_ID NAME ADDRESS

12 Kathrin US

45 John UK

Vidya Lunge 31
DM 22319 unit 1

56 Harry US

23 David Bangkok

34 Alina Dubai

++++++++++++++++++++
SQL JOIN
● As the name shows, JOIN means to combine something.
● In case of SQL, JOIN means "to combine two or more tables".
● In SQL, JOIN clause is used to combine the records from two or
more tables in a database.

Types of SQL JOIN


1. INNER JOIN
2. LEFT JOIN
3. RIGHT JOIN
4. FULL JOIN

Vidya Lunge 32
DM 22319 unit 1

5.

Sample Table
EMPLOYEE

EMP_ID EMP_NAME CITY SALARY AGE

1 Angelina Chicago 200000 30

2 Robert Austin 300000 26

3 Christian Denver 100000 42

4 Kristen Washington 500000 29

5 Russell Los angels 200000 36

6 Marry Canada 600000 48

Vidya Lunge 33
DM 22319 unit 1

PROJECT
PROJECT_NO EMP_ID DEPARTMENT

101 1 Testing

102 2 Development

103 3 Designing

104 4 Development

1. INNER JOIN
In SQL, INNER JOIN selects records that have matching values in both tables
as long as the condition is satisfied.

It returns the combination of all rows from both the tables where the
condition satisfies.

Syntax

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


2. FROM table1
3. INNER JOIN table2
4. ON table1.matching_column = table2.matching_column;

Query

1. SELECT EMPLOYEE.EMP_NAME, PROJECT.DEPARTMENT


2. FROM EMPLOYEE
3. INNER JOIN PROJECT
4. ON PROJECT.EMP_ID = EMPLOYEE.EMP_ID;

Output

EMP_NAME DEPARTMENT

Vidya Lunge 34
DM 22319 unit 1

Angelina Testing

Robert Development

Christian Designing

Kristen Development

2. LEFT JOIN
The SQL left join returns all the values from left table and the matching
values from the right table. If there is no matching join value, it will return
NULL.

Syntax

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


2. FROM table1
3. LEFT JOIN table2
4. ON table1.matching_column = table2.matching_column;

Query

1. SELECT EMPLOYEE.EMP_NAME, PROJECT.DEPARTMENT


2. FROM EMPLOYEE
3. LEFT JOIN PROJECT
4. ON PROJECT.EMP_ID = EMPLOYEE.EMP_ID;

Output

EMP_NAME DEPARTMENT

Vidya Lunge 35
DM 22319 unit 1

Angelina Testing

Robert Development

Christian Designing

Kristen Development

Russell NULL

Marry NULL

3. RIGHT JOIN
In SQL, RIGHT JOIN returns all the values from the values from the rows of
right table and the matched values from the left table. If there is no matching
in both tables, it will return NULL.

Syntax

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


2. FROM table1
3. RIGHT JOIN table2
4. ON table1.matching_column = table2.matching_column;

Query

1. SELECT EMPLOYEE.EMP_NAME, PROJECT.DEPARTMENT


2. FROM EMPLOYEE
3. RIGHT JOIN PROJECT
4. ON PROJECT.EMP_ID = EMPLOYEE.EMP_ID;

Vidya Lunge 36
DM 22319 unit 1

Output

EMP_NAME DEPARTMENT

Angelina Testing

Robert Development

Christian Designing

Kristen Development

4. FULL JOIN
● In SQL, FULL JOIN is the result of a combination of both left and right
outer join.
● Join tables have all the records from both tables.
● It puts NULL on the place of matches not found.

Syntax

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


2. FROM table1
3. FULL JOIN table2
4. ON table1.matching_column = table2.matching_column;

Query

1. SELECT EMPLOYEE.EMP_NAME, PROJECT.DEPARTMENT


2. FROM EMPLOYEE
3. FULL JOIN PROJECT
4. ON PROJECT.EMP_ID = EMPLOYEE.EMP_ID;

Vidya Lunge 37
DM 22319 unit 1

Output

EMP_NAME DEPARTMENT

Angelina Testing

Robert Development

Christian Designing

Kristen Development

Russell NULL

Marry NULL

SQL Sub Query


A Subquery is a query within another SQL query and embedded within
the WHERE clause.

(outer/main/parent)Select * from phalana

Where phalana condition(subquery,child/innerquery)

Important Rule:

● A subquery can be placed in a number of SQL clauses like


WHERE clause, FROM clause, HAVING clause.

Vidya Lunge 38
DM 22319 unit 1

● You can use Subquery with SELECT, UPDATE, INSERT,


DELETE statements along with the operators like =, <, >, >=, <=,
IN, BETWEEN, etc.

● A subquery is a query within another query.

● The outer query is known as the main query, and the inner query is
known as a subquery.

● Subqueries are on the right side of the comparison operator.

● A subquery is enclosed in parentheses.

● In the Subquery, ORDER BY command cannot be used.

● But GROUP BY command can be used to perform the same


function as ORDER BY command.

1. Subqueries with the Select Statement


SQL subqueries are most frequently used with the Select statement.

Syntax

1. SELECT column_name
2. FROM table_name
3. WHERE column_name expression operator ( SELECT column_name
from table_name WHERE ... );

Example

Vidya Lunge 39
DM 22319 unit 1

Consider the EMPLOYEE table have the following records:

ID NAME AGE ADDRESS SALARY

1 John 20 US 2000.00

2 Stephan 26 Dubai 1500.00

3 David 27 Bangkok 2000.00

4 Alina 29 UK 6500.00

5 Kathrin 34 Bangalore 8500.00

6 Harry 42 China 4500.00

7 Jackson 25 Mizoram 10000.00

The subquery with a SELECT statement will be:

1. SELECT *
2. FROM EMPLOYEE
3. WHERE ID IN (SELECT ID FROM EMPLOYEE
4. WHERE SALARY > 4500);

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

5. SELECT *
6. FROM EMPLOYEE
7. WHERE ID IN (4,5,7);

Vidya Lunge 40
DM 22319 unit 1

This would produce the following result:

ID NAME AGE ADDRESS SALARY

4 Alina 29 UK 6500.00

5 Kathrin 34 Bangalore 8500.00

7 Jackson 25 Mizoram 10000.00

2. Subqueries with the INSERT Statement

● SQL subquery can also be used with the Insert statement.

● In the insert statement, data returned from the subquery is used to


insert into another table.

● In the subquery, the selected data can be modified with any of the
character, date functions.

Syntax:

1. INSERT INTO table_name (column1, column2, column3....)


2. SELECT *
3. FROM table_name
4. WHERE VALUE OPERATOR

Example

Consider a table EMPLOYEE_BKP with similar as EMPLOYEE.

Vidya Lunge 41
DM 22319 unit 1

Now use the following syntax to copy the complete EMPLOYEE table into the
EMPLOYEE_BKP table.

1. INSERT INTO EMPLOYEE_BKP


2. SELECT * FROM EMPLOYEE
3. WHERE ID IN (SELECT ID FROM EMPLOYEE);
4.

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

5. INSERT INTO EMPLOYEE_BKP


6. SELECT * FROM EMPLOYEE
7. WHERE ID IN (1,2,3,4,5,6,7);

3. Subqueries with the UPDATE Statement


The subquery of SQL can be used in conjunction with the Update statement.
When a subquery is used with the Update statement, then either single or
multiple columns in a table can be updated.

Syntax

1. UPDATE table
2. SET column_name = new_value
3. WHERE VALUE OPERATOR
4. (SELECT COLUMN_NAME
5. FROM TABLE_NAME
6. WHERE condition);

Example

Vidya Lunge 42
DM 22319 unit 1

Let's assume we have an EMPLOYEE_BKP table available which is backup


of EMPLOYEE table. The given example updates the SALARY by .25 times
in the EMPLOYEE table for all employee whose AGE is greater than or equal
to 29.

1. UPDATE EMPLOYEE
2. SET SALARY = SALARY * 0.25
3. WHERE AGE IN (SELECT AGE FROM EMPLOYE_BKP
4. WHERE AGE >= 29);

This would impact three rows, and finally, the EMPLOYEE table would have
the following records.

ID NAME AGE ADDRESS SALARY

1 John 20 US 2000.00

2 Stephan 26 Dubai 1500.00

3 David 27 Bangkok 2000.00

4 Alina 29 UK 1625.00

5 Kathrin 34 Bangalore 2125.00

6 Harry 42 China 1125.00

7 Jackson 25 Mizoram 10000.00

4. Subqueries with the DELETE Statement

Vidya Lunge 43
DM 22319 unit 1

The subquery of SQL can be used in conjunction with the Delete statement
just like any other statements mentioned above.

Syntax

1. DELETE FROM TABLE_NAME


2. WHERE VALUE OPERATOR
3. (SELECT COLUMN_NAME
4. FROM TABLE_NAME
5. WHERE condition);

Example

Let's assume we have an EMPLOYEE_BKP table available which is backup


of EMPLOYEE table. The given example deletes the records from the
EMPLOYEE table for all EMPLOYEE whose AGE is greater than or equal
to 29.

1. DELETE FROM EMPLOYEE


2. WHERE AGE IN (SELECT AGE FROM EMPLOYEE_BKP
3. WHERE AGE >= 29 );

---------

4. DELETE FROM EMPLOYEE


5. WHERE AGE IN (29,34,42 );

This would impact three rows, and finally, the EMPLOYEE table would have
the following records.

ID NAME AGE ADDRESS SALARY

1 John 20 US 2000.00

Vidya Lunge 44
DM 22319 unit 1

2 Stephan 26 Dubai 1500.00

3 David 27 Bangkok 2000.00

7 Jackson 25 Mizoram 10000.00

DBMS | Database Objects :(TVSIS)/create


A database object is any defined object in a database that is used to

1. store data.
2. reference data.

● Anything which we make from create command is known as Database


Object.
● It can be used to hold and manipulate the
data.DML=(select,update,insert,delete)

Some of the examples of database objects are : view, sequence, indexes, etc.

● Table – Basic unit of storage; composed rows and columns


● View – Logically represents subsets of data from one or more tables.
● A(4,6,8,12)
● B(4,12)
● C(1,2,3)
● Sequence – Generates primary key values
● Index – Improves the performance of some queries
● Synonym – Alternative name for an object

Vidya Lunge 45
DM 22319 unit 1

Different database Objects :(TVSIS)

Table – This database object is used to create a table in database.


Syntax :
CREATE TABLE [schema.]table
(column datatype [DEFAULT expr][, ...]);
Example :
CREATE TABLE dept
(deptno NUMBER(2),
dname VARCHAR2(14),
loc VARCHAR2(13)
);
Output :

DESCRIBE dept;

View –
● This database object is used to create a view in database.
● A view is a logical table based on a table or another view.
● A view contains no data of its own but is like a window through
which data from tables can be viewed or changed.
● The tables on which a view is based are called base tables.

Vidya Lunge 46
DM 22319 unit 1

● The view is stored as a SELECT statement in the data dictionary.


Syntax :

CREATE [OR REPLACE] [FORCE|NOFORCE] VIEW view


[(alias[, alias]...)]
AS subquery
[WITH CHECK OPTION [CONSTRAINT constraint]]
[WITH READ ONLY [CONSTRAINT constraint]];
Example :
CREATE VIEW salvu50
AS
SELECT employee_id ID_NUMBER, last_name NAME, salary*12
ANN_SALARY
FROM employees
WHERE department_id = 50;
Output :
SELECT *FROM salvu50;

Views in SQL
● Views in SQL are considered as a virtual table.

● A view also contains rows and columns.

● To create the view, we can select the fields from one or more tables present
in the database.

Vidya Lunge 47
DM 22319 unit 1

● A view can either have specific rows based on certain condition or all the
rows of a table.

Sample table:
Student_Detail

STU_ID NAME ADDRESS

1 Stephan Delhi

2 Kathrin Noida

3 David Ghaziabad

4 Alina Gurugram

Student_Marks

STU_ID NAME MARKS AGE

1 Stephan 97 19

2 Kathrin 86 21

3 David 74 18

4 Alina 90 20

5 John 96 18

Vidya Lunge 48
DM 22319 unit 1

1. Creating view
A view can be created using the CREATE VIEW statement.

We can create a view from a single table or multiple tables.

Syntax:

1. CREATE VIEW view_name


2. AS
3. SELECT column1, column2.....
4. FROM table_name
5. WHERE condition;

2. Creating View from a single table


In this example, we create a View named Details

View from the table Student_Detail.

Query:

1. CREATE VIEW DetailsView


2. AS
3. SELECT NAME, ADDRESS FROM Student_Details
4. WHERE STU_ID < 4;

Just like table query, we can query the view to view the data.

1. SELECT * FROM DetailsView;

Output:

Vidya Lunge 49
DM 22319 unit 1

NAME ADDRESS

Stephan Delhi

Kathrin Noida

David Ghaziabad

3. Creating View from multiple tables


View from multiple tables can be created by simply include multiple tables in
the SELECT statement.

In the given example, a view is created named MarksView from two tables
Student_Detail and Student_Marks.

Query:

1. CREATE VIEW MarksView


2. AS
3. SELECT Student_Detail.NAME, Student_Detail.ADDRESS,
Student_Marks.MARKS
4. FROM Student_Detail, Student_Mark
5. WHERE Student_Detail.NAME = Student_Marks.NAME;

To display data of View MarksView:

1. SELECT * FROM MarksView;

NAME ADDRESS MARKS

Vidya Lunge 50
DM 22319 unit 1

Stephan Delhi 97

Kathrin Noida 86

David Ghaziabad 74

Alina Gurugram 90

4. Deleting View
A view can be deleted using the Drop View statement.

Syntax

1. DROP VIEW view_name;

Example:

If we want to delete the View MarksView, we can do this as:

1. DROP VIEW MarksView;

++++++++++++++++++++++++++++++++++++++++++
Sequence –
● This database object is used to create a sequence in database.
● A sequence is a user created database object that can be shared by multiple
users to generate unique integers.
● A typical usage for sequences is to create a primary key value, which
must be unique for each row.
● Sequence is a set of integers 1, 2, 3, … that are generated and supported
by some database systems to produce unique values on demand.

Vidya Lunge 51
DM 22319 unit 1

● A sequence is a user defined schema bound object that generates a


sequence of numeric values.
● Sequences are frequently used in many databases because many
applications require each row in a table to contain a unique value and
sequences provides an easy way to generate them.
● The sequence of numeric values is generated in an ascending or
descending order at defined intervals and can be configured to restart
when exceeds max_value.
● CACHE:Specify how many values of the sequence the database preallocates
and keeps in memory for faster access. Oracle recommends using the
CACHE setting to enhance performance if you are using sequences in a Real
Application Clusters environment. The "cache" clause caches the specified
number of sequence values into the buffers in the SGA. This speeds access,
but all cached numbers are lost when the database is shut down. The default
value is 20; maximum value is maxvalue-minvalue.
● NOCACHE:Specify NOCACHE to indicate that values of the sequence are
not preallocated. If you omit both CACHE and NOCACHE, the database
caches 20 sequence numbers by default.

● The sequence is generated and incremented (or decremented) by an internal


Oracle routine.
Syntax :
CREATE SEQUENCE sequencename
[INCREMENT BY n]
[START WITH n]
[{MAXVALUE n | NOMAXVALUE}]

Vidya Lunge 52
DM 22319 unit 1

[{MINVALUE n | NOMINVALUE}]
[{CYCLE | NOCYCLE}]
[{CACHE n | NOCACHE}];

3,6,9,12,15,18,21,24,27,30------increment 1, max,

30,27,24,21,18,15,12,9,6,3-----increment -1, min,

sequence_name: Name of the sequence.

initial_value: starting value from where the sequence starts.


Initial_value should be greater than or equal
to minimum value and less than equal to maximum value.

increment_value: Value by which sequence will increment itself.


Increment_value can be positive or negative.

minimum_value: Minimum value of the sequence.


maximum_value: Maximum value of the sequence.

cycle: When sequence reaches its set_limit


it starts from beginning.

nocycle: An exception will be thrown


if sequence exceeds its max_value.
Example :
CREATE SEQUENCE dept_deptid_seq
INCREMENT BY 10
START WITH 120
MAXVALUE 9999
NOCACHE

Vidya Lunge 53
DM 22319 unit 1

NOCYCLE;
Check if sequence is created by :
SELECT sequence_name, min_value, max_value,
increment_by, last_number
FROM user_sequences;

Following is the sequence query creating sequence in ascending order.

Example 1:
CREATE SEQUENCE sequence_1
start with 1
increment by 1
minvalue 0
maxvalue 100
cycle;

Above query will create a sequence named sequence_1


● .Sequence will start from 1 and will be incremented by 1 having maximum

value 100.
● Sequence will repeat itself from start value after exceeding 100.

Example 2:
Following is the sequence query creating sequence in descending order.
CREATE SEQUENCE sequence_2
start with 100
increment by -1
minvalue 1
maxvalue 100
cycle;

Above query will create a sequence named sequence_2.

Vidya Lunge 54
DM 22319 unit 1

● Sequence will start from 100 and should be less than or equal to maximum

value and will be incremented by -1 having minimum value 1.


Example to use sequence : create a table named students with columns as id and
name.
CREATE TABLE students
(
ID number(10),
NAME char(20)
);

Now insert values into table


INSERT into students VALUES(sequence_1.nextval,'Ramesh');
INSERT into students VALUES(sequence_1.nextval,'Suresh');

where sequence_1.nextval will insert id’s in id column in a sequence as defined in


sequence_1.
Output:
______________________
| ID | NAME |
------------------------
| 1 | Ramesh |
| 2 | Suresh |
----------------------
Examples

Modifying a Sequence: Examples

This statement sets a new maximum value for the customers_seq sequence,
which was created in "Creating a Sequence: Example":

ALTER SEQUENCE customers_seq


MAXVALUE 1500;

Vidya Lunge 55
DM 22319 unit 1

This statement turns on CYCLE and CACHE for the customers_seq sequence:

ALTER SEQUENCE customers_seq


CYCLE
CACHE 5;

Dropping a Sequence: Example

The following statement drops the sequence customers_seq owned by the


user oe, which was created in "Creating a Sequence: Example". To issue this
statement, you must either be connected as user oe or have the DROP ANY
SEQUENCE system privilege:

DROP SEQUENCE oe.customers_seq;

Index –
● This database object is used to create a indexes in database.
● An Oracle server index is a schema object that can speed up the retrieval of
rows by using a pointer.Indexes can be created explicitly or automatically.
● If you do not have an index on the column, then a full table scan occurs.
An index provides direct and fast access to rows in a table.
● Its purpose is to reduce the necessity of disk I/O by using an indexed path to
locate data quickly.
● The index is used and maintained automatically by the Oracle server.
● Once an index is created, no direct activity is required by the user
● Indexes are logically and physically independent of the table they index.
● This means that they can be created or dropped at any time and have no
effect on the base tables or other indexes.
● Indexes are special lookup tables.

● It is used to retrieve data from the database very fast.

Vidya Lunge 56
DM 22319 unit 1

● An Index is used to speed up select queries and where clauses. But it shows
down the data input with insert and update statements. Indexes can be
created or dropped without affecting the data.

● An index in a database is just like an index in the back of a book.

● For example: When you reference all pages in a book that discusses a certain
topic, you first have to refer to the index, which alphabetically lists all the
topics and then referred to one or more specific page numbers.

● Syntax of simple index :


CREATE INDEX index
ON table (column[, column]...);
Example :
CREATE INDEX emp_last_name_idx
ON employees(last_name);

● Syntax of composite index


Example

1. CREATE INDEX idx_name


2. ON Persons (LastName, FirstName);

2. Unique Index statement


It is used to create a unique index on a table. It does not allow duplicate value.

Syntax

1. CREATE UNIQUE INDEX index_name


2. ON table_name (column1, column2, ...);

Vidya Lunge 57
DM 22319 unit 1

Example

1. CREATE UNIQUE INDEX websites_idx


2. ON websites (site_name);

Implicit indexes :
● These are indexes that are automatically created by the database server
when an object is created.
● Indexes are automatically created for primary key constraints and unique
constraints.

3. Drop Index Statement


It is used to delete an index in a table.

Syntax

1. DROP INDEX index_name;

Example

1. DROP INDEX websites_idx;

++++++++++++++++++++++++++++++++++++++++++

Synonym :
● A SYNONYM provides another name for database object, referred to as original
object, that may exist on a local or another server.
● A synonym belongs to schema, name of synonym should be unique.

Vidya Lunge 58
DM 22319 unit 1

● The query below results in an entry for each synonym in database.


● This query provides details about synonym metadata such as the name of synonym
and name of the base object.
select * from sys.synonyms ;

● Synonyms are database dependent and cannot be accessed by other databases.


Syntax:

CREATE [OR REPLACE] [PUBLIC] SYNONYM schema.synonym_name

FOR schema.object;

Ex: create synonym for stock table

CREATE SYNONYM stocks

FOR inventories;

the stocks is synonym of the inventories table in the query like the following:

SELECT * FROM stocks;

DROP SYNONYM stocks;

Vidya Lunge 59
DM 22319 unit 1

Extra:

CREATE SYNONYM: Examples

To define the synonym offices for the table locations in the schema hr, issue the
following statement:

CREATE SYNONYM offices


FOR hr.locations;

To create a PUBLIC synonym for the employees table in the schema hr on the remote
database, you could issue the following statement:

CREATE PUBLIC SYNONYM emp_table


FOR hr.employees@remote.us.oracle.com;

A synonym may have the same name as the underlying object, provided the
underlying object is contained in another schema.

If the user hr's schema does not contain an object named customers, and if hr has select
permission on oe.customers, then hr can access the customers table in oe's schema by
using the public synonym customers:

Vidya Lunge 60
DM 22319 unit 1

● It simplify access to objects by creating a synonym(another name for


an object).
● With synonyms, you can Ease referring to a table owned by another
user and shorten lengthy object names.
● To refer to a table owned by another user, you need to prefix the table
name with the name of the user who created it followed by a period.

● Creating a synonym eliminates the need to qualify the object name

with the schema and provides you with an alternative name for a table,
view, sequence,procedure, or other objects. This method can be
especially useful with lengthy object names, such as views.
In the syntax:
PUBLIC : creates a synonym accessible to all users
synonym : is the name of the synonym to be created
object : identifies the object for which the synonym is created
Syntax :


CREATE [PUBLIC] SYNONYM synonym FOR object;
Example :
CREATE SYNONYM d_sum FOR dept_sum_vu;
__________________________________________________________

Vidya Lunge 61

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy