0% found this document useful (0 votes)
2 views15 pages

UNIT 5-sql

The document provides an overview of SQL joins, specifically natural joins and Cartesian joins, detailing their syntax and functionality. It also covers SQL operators like ANY and ALL, subqueries, and various date and time functions in DBMS. Additionally, it discusses string functions in SQL, including ASCII, BIN, CHAR, and CONCAT, among others.

Uploaded by

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

UNIT 5-sql

The document provides an overview of SQL joins, specifically natural joins and Cartesian joins, detailing their syntax and functionality. It also covers SQL operators like ANY and ALL, subqueries, and various date and time functions in DBMS. Additionally, it discusses string functions in SQL, including ASCII, BIN, CHAR, and CONCAT, among others.

Uploaded by

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

UNIT 5

Natural Join

 Used to join tables on the basis of a common column.


 A natural join is a type of equijoin, which means it works by matching
equal values in common columns.

 Natural Join
 This join is used to combine rows of tables based on columns having the
same name and data type in both the tables.
 The common columns only appear once in the result of this join.
 Natural join can be used to combine two or more tables,
 Additional joins like LEFT, RIGHT, etc. can be combined with natural
join but usually not with inner join.

 syntax :
 SELECT Column_1,Column_2,…..Column_n

FROM table_1

NATURAL JOIN table_2;

 If you want to perform a natural join on the entire table you can use the
following syntax:
 SELECT * FROM table_1

NATURAL JOIN table_2;

 For example,

SELECT * FROM Employee

NATURAL JOIN Department;

The key features of a natural join are:

 It is an INNER JOIN by default that returns only matching rows between the
tables.
 Tables are joined based on all columns with the same name and data types. The
SQL engine automatically detects these common columns.

 Output contains unique columns; common join columns appear only once.

 ON or USING clauses cannot be used to specify join columns, as join uses all
common column names implicitly.

 Can be combined with left, right, and full outer joins for more flexibility.

Cartesian Join

Returns the cartesian product of tables’ rows

Cartesian Join or Cross Join


 Cartesian Join also known as the Cross Join,
 It returns the cartesian product of the tables being joined, which is the
combination of every row of one table with every row of another table.
 For example,
 if table A contains 20 rows and table B consists of 30 rows, the Cross
Join of these tables will result in a table will containing 20*30 (600)
rows.
 The syntax of this join is as follows:
 SELECT table_1.Column_1, table_1.Column_2,
table_2 .Column_1, table_2. Column_2…

FROM table_1, table_2;

Syntax:

SELECT * FROM table_1, table_2;

ON clause:

 ON clause is used in conjunction with JOIN statements


 It is used to specify the conditions that determine how two
or more tables are related or joined.

1. Combine data: Join two or more tables to retrieve data


from multiple sources and present it as a unified result set.

2. Establish relationships: Define the conditions that


determine how rows in one table relate to rows in another,
such as connecting employees to their departments or orders
to customers.

3. Filter data: Apply specific filtering criteria to the join, limiting


the rows that are included in the result set.

The syntax for using the ON clause :

SELECT column_list
FROM table1
JOIN table2
ON table1.column_name = table2.column_name;

The SQL ANY and ALL Operators


The ANY and ALL operators allow you to perform a comparison.
The SQL ANY Operator

The ANY operator:

 returns a boolean value as a result


 returns TRUE if ANY of the subquery values meet the condition

ANY means that the condition will be true if the operation is true for any of the values
in the range.

Example:
SELECT ProductName
FROM Products
WHERE ProductID = ANY
(SELECT ProductID
FROM OrderDetails
WHERE Quantity = 10);

The SQL ALL Operator

The ALL operator:

 returns a boolean value as a result


 returns TRUE if ALL of the subquery values meet the condition
 is used with SELECT, WHERE and HAVING statements

ALL means that the condition will be true only if the operation is true for all values in
the range.

Example
SELECT ALL ProductName
FROM Products
WHERE TRUE;

SELECT ProductName
FROM Products
WHERE ProductID = ALL
(SELECT ProductID
FROM OrderDetails
WHERE Quantity = 10);

Subquery
A subquery is a SQL query nested inside a larger query.

 subquery can be located in :

o - A SELECT clause

o - A FROM clause

o - A WHERE clause

o - A HAVING clause

 The subquery can be nested inside a SELECT, INSERT, UPDATE, or


DELETE statement or inside another subquery.

 A subquery is usually added within the WHERE Clause of another SQL


SELECT statement.

 A subquery is also called an inner query or inner select, while the statement
containing a subquery is also called an outer query or outer select.

 In the SELECT Clause : Used to return a single value or a set of values.


SELECT first_name, (SELECT department_name FROM departments WHERE
departments.department_id = employees.department_id) AS department_name

FROM employees;

 In the FROM Clause : Treated as a derived table or inline view.


SELECT *

FROM (SELECT first_name, salary FROM employees WHERE salary > 5000) AS
"high_salaried"
 In the WHERE Clause : Used to filter the results.
SELECT first_name

FROM employees

WHERE department_id IN (SELECT department_id FROM departments WHERE


location_id>1500);

 In the HAVING Clause : Used to filter groups.


SELECT department_id, AVG(salary)

FROM employees

GROUP BY department_id

HAVING AVG(salary) > (SELECT AVG(salary) FROM employees);

Type of Subqueries

 Scalar Subquery: Returns a single value.


 Column Subquery: Returns a single column of values
 Multiple column subqueries : Returns one or more columns.
 Single row subquery : Returns a single row of values.
 Multiple row subquery : Returns one or more rows.
 Table Subquery: Returns a result set that can be treated as a table
 Correlated subqueries : Reference one or more columns in the outer SQL
statement. The subquery is known as a correlated subquery because the
subquery is related to the outer SQL statement.
 Nested subqueries : Subqueries are placed within another subquery.
Correlated vs. Non-Correlated Subqueries
Non-Correlated Subquery:
  Independent and can be executed alone.
 SELECT first_name
 FROM employees
 WHERE salary > (SELECT AVG(salary) FROM employees);

Correlated Subquery:
  Depends on the outer query and is executed for each row processed by the
outer query.
 SELECT first_name
 FROM employees e1
 WHERE salary > (SELECT AVG(salary) FROM employees e2 WHERE
e1.department_id = e2.department_id);

Date and Time Functions in DBMS


 The date and time functions in DBMS are quite useful to manipulate and store
values related to date and time.
 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);
+---------------------------------------------------------+
| DATE_ADD('2018-08-01', INTERVAL 31 DAY) |
+---------------------------------------------------------+
| 2018-09-01 |
+---------------------------------------------------------+
1 row in set (0.00 sec)

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');
+---------------------------------------------------------+
|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)

CURDATE():

This returns the current date of the system in the YYYY-MM-DD format.
For example −
sql> SELECT CURDATE();
+---------------------------------------------------------+
| CURDATE() |
+---------------------------------------------------------+
| 2018-08-01 |
+---------------------------------------------------------+
1 row in set (0.00 sec)

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();
+---------------------------------------------------------+
| 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 −
sql> SELECT DAYNAME('2018-08-01');
+---------------------------------------------------------+
| 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');
+---------------------------------------------------------+
| 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|
+---------------------------------------------------------+
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');
+---------------------------------------------------------+
| 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');
+---------------------------------------------------------+
| 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');
+---------------------------------------------------------+
| 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.

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();
+---------------------------------------------------------+
| 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 −
sql> SELECT DAYNAME('2018-08-01');
+---------------------------------------------------------+
| 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');
+---------------------------------------------------------+
| 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|
+---------------------------------------------------------+
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');
+---------------------------------------------------------+
| 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');
+---------------------------------------------------------+
| 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');
+---------------------------------------------------------+
| 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.
SQL - String Functions
 String functions are functions in SQL that take string values as inputs.
 The output may or may not be a string.
 SQL offers many in-built string functions
ASCII(str)

 Syntax- ASCII ( character_expression )


For Example:- SELECT ASCII (‘ABSC’) will return the value ‘65’, which is the
ASCII code for the letter ‘A’.

BIN(N)

 Syntax- BIN (N)


 This function returns the binary value of the decimal in the argument.
 For Example- SELECT BIT_LENGTH (‘TEXT’) will return the value 32.

CHAR(N,... [USING charset_name])

 Syntax- CHAR(N,... [USING charset_name])


 This function interprets the string and returns the length of the string in
characters.

For Example- SELECT CHAR_Length(“Eleven”) will return the value of 6.

CHARACTER_LENGTH(str)

 Syntax- CHARACTER_LENGTH(str)
This function is the same as CHAR_LENGTH(str)

CONCAT(str1,str2,...)

 Syntax- CONCAT(str1,str2,...)
This function takes multiple strings as inputs and then concatenates the strings to
get a single string value.

For Example:-

SELECT CONCAT(‘one ‘, ‘line ‘, ‘below’). This will return the string with the
text ‘one line below’.

CONCAT_WS(separator,str1,str2,...)

 Syntax- CONCAT_WS(separator,str1,str2,...)
 A separator is passed as the first argument, and the separator is added between all
the strings to be concatenated.
 For example:- CONCAT_WS(',' , 'John’ , ‘Smith'). This will return the string with
the text ‘John,Smith).

INSTR(str,substr)

 Syntax- INSTR(str,substr)
 It gives the position of the string substr in the string str.
 INSTR(‘abcdefgh’,2,3,’red’)
The returned value is ‘aredefgh’.

INSERT(str,pos,len,newstr)

 Syntax- INSERT(str,pos,len,newstr)
 It converts the str argument into a new string by adding the string newstr with
the len length and from pos position.
SQL query:-

INSERT(‘abcdefgh’,2,3,’red’)

The returned value is ‘aredefgh’.

HEX(N_or_S)

 Syntax- HEX(N_or_S)
 It converts the integer argument into a hexadecimal representation.
For the below SQL query:-

HEX(255)

The returned value is ‘FF’.

FORMAT(X,D)

 Syntax- FORMAT(X,D)
 It formats the number X to a decimal number rounded off to D decimal
places. The output returned is in the form of a string.
For the below SQL query:-
FORMAT(12345.55553234,4)

The returned value is ‘12345.5555’.

FIND_IN_SET(str,strlist)

 Syntax- FIND_IN_SET(str,strlist)
 It returns the index of the position str in the list of a single string.
 For the below SQL query:-
FIND_IN_SET(‘a’,’b,a,c,d’)

The returned value is ‘2’.

FIELD(str,str1,str2,str3,...)

 Syntax- FIELD(str,str1,str2,str3,...)
 It returns the index of the position str in the arguments. The arguments are
counted starting from 1.
For the below SQL query:-

Field(‘ab’,’abcd’,’ab’,’bfd’,’fdd’)

The returned value is ‘2’.

EXPORT_SET(bits,on,off[,separator[,number_of_bits]])

 Syntax- EXPORT_SET(bits,on,off[,separator[,number_of_bits]])
 This function uses the argument ‘bits’ to return the on bits and off bits.
For the below SQL query:-

 Export_Set(9,’ON’,’OFF’, ‘,’,4)
 The string returned is ON,OFF,OFF,ON

ELT(N,str1,str2,str3,...)

 Syntax- ELT(N,str1,str2,str3,...)
 If the integer is 1, the first string is given as the output.
 For Example:- SELECT ELT(2,’abc’,’def’,’ghi’,’jkl’). The output will be the
second string, i.e. ‘def’.
CONV(N,from_base,to_base)

 Syntax- CONV(N,from_base,to_base)

From_base is the initial base, and To_base is the final base.

For example:- SELECT CONV('a',16,2). This will return the string with the text
‘1010’.

You might also like