0% found this document useful (0 votes)
4 views

Unit 3 (1)

Uploaded by

vrusha017
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views

Unit 3 (1)

Uploaded by

vrusha017
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 22

Unit 3

3.1: In Built Functions: String, Arithmetic

1. String Function:

SQL Server String Functions

Function Description

CONCAT Adds two or more strings together

LENGTH Returns the length of a string

LOWER Converts a string to lower-case

REPLACE Replaces all occurrences of a substring within a string, with a new substring

REVERSE Reverses a string and returns the result

SUBSTRING Extracts some characters from a string

UPPER Converts a string to upper-case

1.CONCAT():The CONCAT() function adds two or more strings together.

 Syntax: CONCAT(string1, string2, ...., string_n)


 Example: SELECT CONCAT('computer', 'department');

2.REPLACE(): The REPLACE() function replaces all occurrences of a substring within a string, with
a new substring.

Syntax: REPLACE(string, old_string, new_string)


Example:select replace( 'JAVATROINT', 'R', 'P' ) as website_name;
3.LENGTH():The LEN() function returns the length of a string.
Syntax: LENGTH(string)
Example: SELECT LENGTH('Database');
4. SUBSTRING(): The SUBSTRING() function extracts some characters from a string.
Syntax: SUBSTRING(string, start, length)
Example: SELECT SUBSTRING(CustomerName, 1, 5) AS subString
FROM student;
Deptname
Computer
Mechanical
Civil
Aiml
electrical
+---------------+
| ExtractString |
+---------------+
| com |
| mec |
| civ |
| aim |
| ele |
+---------------+
5. LOWER(): The LOWER() function converts a string to lower-case.
Syntax: LOWER(text)
Example: SELECT LOWER(dept) AS Lowercase
FROM student;
mysql> SELECT UPPER(name) AS U
-> from student;
+---------------+
| UPPERcaseName |
+---------------+
| HARSHALA |
| SAKSHI |
| CO |
| AIML |
| MECH |
| CIVIL |
+---------------+
6. Reverse(): The REVERSE() function reverses a string and returns the result.
Syntax: REVERSE(string)
Example: SELECT REVERSE(Name)
FROM student;
mysql> SELECT REVERSE(name)
-> from student;
+---------------+
| REVERSE(name) |
+---------------+
| alahsrah |
| ihskas |
| oc |
Arithmetic Function: A mathematical function executes a mathematical operation based on input
values
1.CEIL():This returns the smallest integer value that is either more than X or equal to X.
Syntax: CEIL(expression)

To get the ceiling or nearest rounded up value of 17.36 from the student table , the following SQL
statement can be used :

Example: SELECT(CEIL(17.36))
FROM student;
Output: (CEIL(17.36))-------------18

2.FLOOR(X)
This returns the largest integer value that is either less than X or equal to X.
Syntax:FLOOR(expression)
Example:SELECT FLOOR(17.36)

FROM dual;

Output:FLOOR(17.36)------------17

3.ROUND(X)
This function returns the value of X rounded off to the whole integer that is nearest to it.
Syntax: Select Round(Expression);
Example: select Round(5.7)
Output: 6
Example: select Round(5.2)
Output: 5
4. SQRT(X)
This function returns the square root of X. For example −
Syntax:select sqrt(expression)
Example: Select sqrt(9)
Output: 3
Example: Select sqrt(49)
Output: 7

3.2 Date and Time:

Date Functions:The function returns the date and time values

The following table lists the most important built-in date functions in MySQL:

Function Description

NOW() Returns the current date and time

CURDATE() Returns the current date

CURTIME() Returns the current time

Date and Time:

1.NOW(): NOW() function returns the current date and time.

Syntax: NOW()
Example:SELECT NOW(),CURDATE(),CURTIME()

Output: 2023-09-13 09:45:34

2. CURDATE(): CURDATE() returns the current date.


Syntax: CURDATE()

Example: Select CURDATE()

Output: 2023-09-13

3.CURTIME(): CURTIME() returns the current time

Syntax: CURTIME()

Example: Select CURTIME()

Output:09:45:34

Time Function:The TIME() function extracts the time part from a given time/datetime.

Note: This function returns "00:00:00"

Syntax: TIME(expression)
Example:SELECT TIME("2017-08-15 19:30:10");

3. Aggregate Functions:
An aggregate function in SQL returns one value after calculating multiple values of a column. We often
use aggregate functions with the GROUP BY and HAVING clauses of the SELECT statement.

There are 5 types of SQL aggregate functions:

 Count()

 Sum()

 Avg()

 Min()

 Max()

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.
o COUNT function uses the COUNT(*) that returns the count of all the rows in a specified table.
COUNT(*) considers duplicate and Null.

Syntax: SELECT COUNT(column_name) FROM table_name;

Emp_Id Emp_Name Emp_Salary Emp_City

2001 Saurabh 25000 NULL

2002 Ram 29000 Delhi


2003 Sumit 30000 NULL

2004 Ankit 45000 Goa

2005 Bheem 40000 NULL

Suppose, you want to count the total values of the Emp_City column

Example: SELECT COUNT (Emp_City)FROM Employee_details ;


TotalCity

2. SUM Function: Sum function is used to calculate the sum of all selected columns. It works on
numeric fields only.
Syntax: SELECT SUM (column_name) FROM table_name;

ID EMPLOYEE_NAME SALARY

1 Saurabh 25000

2 Ram 29000

3 Sumit 30000

4 Ankit 45000

If you want to know how the combined total salary of all employee

Example: SELECT SUM (salary)FROM employees ;

Totalsalary

1,29,000

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: SELECT AVG(column_name) FROM table_name;
Product_ID Product_Name Product_Quantity

104 P1 10.250

202 P4 15.500

103 P2 18.250

111 P7 25.250

210 P6 15.500

212 P8 19.750

112 P10 10.250

Example:SELECT AVG(Product_Quantity) FROM Product_Detail.

Average_ofproductquantity

16.39

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: SELECT MAX (column_name) FROM table_name;

ID EMPLOYEE_NAME SALARY

1 Saurabh 25000

2 Ram 29000

3 Sumit 30000

4 Ankit 45000

Example: SELECT MAX(salary)from employee;

SALARY

450000
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: SELECT MIN (column_name) FROM table_name;

ID EMPLOYEE_NAME SALARY

1 Saurabh 25000

2 Ram 29000

3 Sumit 30000

4 Ankit 45000

Example: SELECT MIN(salary)from employee;

SALARY

25000

3.3 Queries using Group By:


1. Group By: The Group By statement is used for organizing similar data into groups.

The GROUP BY statement is often used with aggregate functions


(COUNT(), MAX(), MIN(), SUM(), AVG()) to group the result-set by one or more columns.

GROUP BY Syntax:
SELECT column_name(s)
FROM table_name
GROUPBY column_name(s);

1.mysql> select * from student;


+--------+----------+--------+
| rollno | name | deptid |
+--------+----------+--------+
| 3 | harshala | NULL |
| 5 | sakshi | NULL |
| 85 | co | 12 |
| 23 | aiml | 45 |
| 98 | mech | 56 |
| 37 | civil | 63 |
+--------+----------+--------+
6 rows in set (0.00 sec)

2.mysql> select rollno from student


-> group by name;
+--------+
| rollno |
+--------+
| 23 |
| 37 |
| 85 |
| 3|
| 98 |
| 5|
+--------+
6 rows in set (0.09 sec)

3.mysql> select name from student


-> group by rollno;
+----------+
| name |
+----------+
| harshala |
| sakshi |
| aiml |
| civil |
| co |
| mech |
+----------+
6 rows in set (0.00 sec)

mysql

Joins: SQL Join statement is used to combine rows from two or more tables based on a common field
between them.

Different types of Joins are as follows:


 INNER JOIN
 FULL JOIN/OUTER JOIN

 Inner Join:The INNER JOIN keyword selects all rows from both the tables as long as the
condition is satisfied.
 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 the same.
 Syntax: SELECT column_name(s)
FROM table1
INNER JOIN table2
ON table1.column_name = table2.column_name;

Department

Dept_Id Dept_Name

1001 Finance
1002 Marketing

1003 Sales

1004 Coding

1005 Administration

Employee_Detail

Emp_Id Emp_Name Dept_Id Emp_Salary

1 Akshay 1001 23000

2 Ram 1002 24000

3 Balram 1004 25000

4 Yatin NULL NULL

5 Manoj 1004 23000

6 Priyanka 1003 24000

8 Yogesh NULL NULL

9 Naveen NULL NULL

10 Tarun 1004 23000

Example:SELECT Employee_Details.Emp_Id, Employee_Details.Emp_Name,


Department.Dept_Name,Employee_Details.Emp_Salary,
FROM Department INNER JOIN Employee_Details
ON Department.Dept_ID = Employee_Details.Emp_Id;

 It only fetches the details of those employees from both the tables whose Dept_Id in the
Employee table matches with the Dept_Id of the Department table.
 Output:

Emp_Id Emp_Name Dept_Name Emp_Salary

1 Akshay Finance 23000

2 Ram Marketing 24000


3 Balram Coding 25000

5 Manoj Coding 23000

6 Priyanka Sales 24000

10 Tarun Coding 23000

JOIN UNION

JOIN combines data from many tables


SQL combines the result set of two or more
based on a matched condition between
SELECT statements.
them

It combines data into new columns. It combines data into new rows

The number of columns selected from The number of columns selected from each table
each table may not be the same. should be the same.

Datatypes of corresponding columns


The data types of corresponding columns selected
selected from each table can be
from each table should be the same.
different.

It may not return distinct columns. It returns distinct rows.

FULL OUTER JOIN:

The FULL OUTER JOIN command returns all rows when there is a match in either left table or right
table.

Syntax:SELECT column_name(s)
FROM table1FULL OUTER JOIN table2
ON table1.column_name = table2.column_name

Example: Student Table


Books Table

Example:
SELECT students.name, books.title
FROM students FULLOUTERJOIN books
ON students.student_id=books.student_id;
 we are selecting the names from the students table and the book titles from the books table.
Records are matched using the student_id column in both tables.
 With the full outer join, we are able to see all of the students, including those who have not
chosen a book yet. We can also see all of the books, including those that have not yet been
chosen.
 Output:
What is the Difference between INNER JOIN vs OUTER JOIN in SQL?
 The biggest difference between an INNER JOIN and an OUTER JOIN is that the inner join will
keep only the information from both tables that's related to each other (in the resulting table). An
Outer Join, on the other hand, will also keep information that is not related to the other table in the
resulting table.

Group By Clause:GROUP BY statement groups rows that have the same values into summary ...
The GROUP BY statement is often used with aggregate functions ( COUNT() , MAX() , ...

 GROUP BY clause is used with the SELECT statement.


 In the query, the GROUP BY clause is placed after the WHERE clause.
Syntax: Select Column_name(s)

From Table_name

Group by Column_name(s);

Ex Query:select name, sum(salary)


from emp
group by name;

Example:Emp

E_Id E_name Salary


1 Ram 10000
2 Sham 30000
3 Ram 40000
4 Geeta 20000
Output: Emp
E_Name Sum(Salary)
Geeta 2000
Ram 5000
Sham 3000

Ex Query: select E_name, min(salary)


from emp
group by name;

Output:
E_Name Sum(Salary)
Geeta 2000
Ram 1000
Sham 3000

Order By Clause: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.

Syntax:SELECT column1, column2, ...


FROM table_name
ORDER BY column1, column2, ... ASC|DESC;

Example :SELECT * FROM Emp


ORDER BY Salary;

Example :SELECT * FROM Customers


ORDER BY Country ASC, CustomerName DESC;

Ex Query: Select * from emp

Order by Salary;

Example:

E_Id E_name Salary


1 Ram 10000
2 Sham 30000
3 Ram 40000
4 Geeta 20000

Output:

E_Id E_name Salary


1 Ram 10000
4 Geeta 20000
2 Sham 30000
3 Ram 40000

Having Clause: This clause is used in SQL because we cannot use the WHERE clause with the SQL
aggregate functions. Both WHERE and HAVING clauses are used for filtering the records in SQL
queries.

The HAVING clause places the condition in the groups defined by the GROUP BY clause in the
SELECT statement.

Syntax: Select column_name aggregate_function(column_name)

From table_name

Group By column_name

Having condition;

Ex Query:Select name,sum(salary)

from emp

group by E_name

having sum(salary)>20000;

Example: Emp

E_Id E_name Salary


1 Ram 10000
2 Sham 30000
3 Ram 40000
4 Geeta 20000

Output:Emp

E_Name Sum(Salary)

Ram 50000

sham 30000

 Create View: In SQL, a view is a virtual table based on the result-set of an SQL statement.
 A view contains rows and columns, just like a real table. The fields in a view are fields from
one or more real tables in the database.
 You can add SQL statements and functions to a view and present the data as if the data were
coming from one single table.
 A view is created with the CREATE VIEW statement.

Syntax: CREATE VIEW view_name AS


SELECT column1, column2, ...
FROM table_name
WHERE condition;

Ex Query: Create view Emp1 As


Select E_id, salary
From emp;
Result:Query OK

Ex Query: select * from Emp1;

Output: Emp1

E_Id Salary
1 10000
2 30000
3 40000
4 20000

Update View: Update View refers to a view (logic) to update a particular instance of a table from the
database with some extra details. It is used to update entries in the database

Syntax: Update View_Name

Set col1=value,col2=value2…..

Where condition;

Ex Query: Update emp1

Set salary=60000

Where id = 2;

Result: Query OK

Ex Query: Select *from emp1;

Output: emp1

E_Id E_name Salary


1 Ram 10000
2 Sham 60000
3 Ram 40000
4 Geeta 20000

Drop View:The SQL DROP VIEW statement is used to delete an existing view, along with its
definition and other information. Once the view is dropped, all the permissions for it will also be
removed.

And note that if a record is deleted from a view, it is also deleted from its corresponding base table.

Syntax:DROPVIEW view_name;

Ex Query: Drop view emp1;

Delete View: Instead of removing an entire view we can also delete selected rows of a view using the
DELETE statement.

Syntax:DELETEFROM view_name WHERE condition;

Ex Query: Delete from emp1 where id=4

E_Id E_name Salary


1 Ram 10000
2 Sham 60000
3 Ram 40000
4 Geeta 20000

Output: Emp1

E_Id E_name Salary


1 Ram 10000
2 Sham 60000
3 Ram 40000

Sequences:

 A sequence is a user-defined schema-bound object that generates a series 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 provide 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 it exceeds max_value.

Syntax:CREATE SEQUENCE Sequence_Name


START WITH Initial_Value
INCREMENT BY Increment_Value
MINVALUE Minimum_Value
MAXVALUE Maximum_Value
CYCLE|NOCYCLE;

 Sequence_Name − This specifies the name of the sequence.


 Initial_Value − This specifies the starting value from where the sequence should start.
 Increment_Value − This specifies the value by which the sequence will increment by itself.
This can be valued positively or negatively.
 Minimum_Value − This specifies the minimum value of the sequence.
 Maximum_Value − This specifies the maximum value of the sequence.
 Cycle − When the sequence reaches its Maximum_Value, it starts again from the beginning.
 Nocycle − An exception will be thrown if the sequence exceeds the Maximum_Value.
Example: Example: +------+-----------+------+
| ID | NAME | AGE |
+------+-----------+------+
| NULL | Dhruv | 20 |
| NULL | Arjun | 23 |
| NULL | Dev | 25 |
| NULL | Riya | 19 |
| NULL | Aarohi | 24 |
| NULL | Lisa | 20 |
| NULL | Roy | 24 |
+------+-----------+------+

Ex Query:SQL>CREATE SEQUENCE My_Sequence ASINT

STARTWITH1
INCREMENT BY1
MINVALUE 1
MAXVALUE 5
CYCLE;
In the above query, the sequence is named “My_Sequence” and it starts with the value 1 and
increments by 1 each time a value is generated. The sequence has a maximum value of 5 and cycles
back to the
Output: SQL> SELECT * FROM STUDENTS;

+------+-----------+------+
| ID | NAME | AGE |
+------+-----------+------+
| 1 | Dhruv | 20 |
| 2 | Arjun | 23 |
| 3 | Dev | 25 |
| 4 | Riya | 19 |
| 5 | Aarohi | 24 |
| 1 | Lisa | 20 |
| 2 | Roy | 24 |
+------+-----------+------+

Left Join:This join returns all the rows of the table on the left side of the join and matches rows for
the table on the right side of the join. For the rows for which there is no matching row on the 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;
Example: Student

Course

Ex Query:SELECT Student.NAME,Course.COURSE_ID
FROM StudentLEFT JOIN Course
ON Course.ROLL_NO = Student.ROLL_NO;
Output:
Right Join: 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 the join. For the rows for
which there is no matching row on the 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;
//Consider same tables as student and course//
Ex Query: SELECT Student.NAME,Course.COURSE_ID
FROM Student RIGHT JOIN Course
ON Course.ROLL_NO = Student.ROLL_NO;
Output:

Index: The Index in SQL is a special table used to speed up the searching of the data in the database
tables. It also retrieves a vast amount of data from the tables frequently. The INDEX requires its own
space in the hard disk.
The index concept in SQL is same as the index concept in the novel or a book.

Create Index: The CREATE INDEX statement is used to create indexes in tables.

Indexes are used to retrieve data from the database more quickly than otherwise. The users cannot see
the indexes, they are just used to speed up searches/queries.

Syntax

Creates an index on a table. Duplicate values are allowed:

CREATE INDEX index_name


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

Different Types of Indexes in SQL Server

There are various types of indexes that can be created using the CREATE INDEX statement. They are:

 Unique Index
 Single-Column Index
 Composite Index
 Implicit Index
Unique Indexes

Unique indexes are used not only for performance, but also for data integrity. A unique index does not
allow any duplicate values to be inserted into the table. It is automatically created by PRIMARY and
UNIQUE constraints when they are applied on a database table, in order to prevent the user from
inserting duplicate values into the indexed table column(s). The basic syntax is as follows.

CREATE UNIQUE INDEX index_name


on table_name (column_name);
Single-Column Indexes

A single-column index is created only on one table column. The syntax is as follows.

CREATE INDEX index_name


ON table_name (column_name);
Composite Indexes

A composite index is an index that can be created on two or more columns of a table. Its basic syntax is
as follows.

CREATE INDEX index_name


on table_name (column1, column2);

DROP INDEX
An index can be dropped using SQL DROP command. Dropping an index can effect the query
performance in a database. Thus, an index needs to be dropped only when it is absolutely necessary.

The basic syntax is as follows −

DROP INDEX index_name;

Synonym: An alias or alternative names can be given to any of the database objects like a table, view,
stored procedure, user-defined function, and sequence with the help of SQL Server Synonym.

Whenever we create a SQL Server Synonym in a database, the synonym is referenced to a particular
database object and that database object is called base object. The location of the base object to which
the synonym is referenced can be either in the same database or in some other database in the same
server or even on some other instance running on another server.

Syntax: CREATE SYNONYM <synonym> FOR <name>


Example: CREATE SYNONYM pr FOR payroll;

Input Description
<synonym>The name of the synonym.
<name> The name of the table or view for which the synonym is to be created.

Drop Synonym: Use the DROP SYNONYM statement to remove a synonym from the database or to
change the definition of a synonym by dropping and re-creating it.

Syntax: Drop Synonym synonym_name;

Example: Drop synonym pr;

You might also like