SQL Dissertation
SQL Dissertation
LANGUAGE
1
A Project Report
On
A COMPARATIVE STUDY ON
STRUCTURED QUERY LANGUAGE
(SQL)
PREPARED BY
USNISH BARMAN ROY
BENGAL INSTITUTE OF BUSINESS STUDIES
MBA
( 2021-2023 )
UNDER THE GUIDANCE OF
PROF. SHAMBO SEN
3
ACKNOWLEDGMENTS
The work presented in this dissertation has been a life-changing experience and
it would not have been possible without the support and guidance that I have
received from many people.
I, therefore, take this opportunity to extend my sincere gratitude and
appreciation to all those who have made this thesis possible.
Firstly, I would like to acknowledge my indebtedness and render my warmest
thanks to my supervisors, Prof Shambo Sen, and Mr. Rushikesh Dane. I am
grateful to Prof Shambo Sen for suggesting my topic as well as for introducing
me to the exciting fields of applications. He has taught me, both consciously and
unconsciously, the elements of how good research should be done. He has
spent countless hours editing my work in addition to constantly reminding me of
how we needed to ‘flush’ accepted manuscripts; words which I will fondly
remember. I will forever value all the time, advice, inspiration, encouragement,
and ideas that he has contributed to my thesis. The joy and enthusiasm that he
has for research is truly remarkable and this has been a motivational factor
throughout my MBA journey.
I would also like to extend my thankfulness to Prof. Sheikh Ali for their words of
encouragement during the writing of this thesis.
Lastly and most importantly, I would like to thank my family and friends for all
their love, endless support and encouragement. I am thankful to my parents,
who have constantly supported me in all my academic pursuits.
4
DECLARATION
I, Usnish Barman Roy , a student of MBA in Business Analytics and Data Science,
Batch PGPBA-DS 2021-23 of Bengal Institute of Business studies hereby declare
that the Business Dissertation Report titled “The comparative study of
Structured Query Language (SQL) is a result my own work and all of work of
authors, researchers, other publications, etc. have been duly credited in this
report towards the end. I shall be solely responsible for plagiarism or other
irregularities, if found any.
I assert that the statements made and conclusions drawn are the outcome of
my own understanding during the research conducted through secondary
sources for this Business Dissertation report. I further declare that to the best of
my knowledge and belief that this report does not contain any work which has
been previously submitted for the award of any other
degree/diploma/certificate in this university or in India or abroad.
5
CERTIFICATE
Thanking you.
Yours truly,
6
INDEX.
7
INTRODUCTION AND BACKGROUND
Structured Query Language (SQL) is the official query language for most relational
databases, containing commands used to access and manipulate data. Since released by
Codd [1970], SQL has been used by most database vendors for their products. Although SQL
is highly declarative, many end-users encounter several challenges in writing correct
queries. Such challenges have limited its use as the preferred database language of choice.
This part of the thesis introduces what SQL is, describes several terms used, and reviews
literature similar to this work.
For the past three decades, Structured Query Language (SQL) has been the preferred
database language for relational database management systems (RDBMSs). Since being
adopted as an ANSI1 and ISO2 standard, SQL has been widely used by most database
vendors for their commercial products, such as IBM3 DB2, Microsoft SQL Server and Access,
SAP HANA, Splunk DB, Teradata DB, etc. Similarly, many open-source RDBMSs have been
introduced that support SQL, such as Oracle’s MySQL, PostgreSQL, Mozilla’s Firebird,
MariaDB, Ingres, etc. SQL has found many applications in academia and industry. In higher
learning institutions, SQL is taught as part of the introductory database course in the
undergraduate curriculum. Learning SQL is a pivotal skill that a Computer Science (CS)
student ought to master as it is pertinent for an entry role in many diverse industries. It is
worth noting that SQL underpins a range of applications and programming languages to
allow users to manipulate and retrieve information. These applications range from e-
commerce, Internet of Things (IoT), commercial as well as open-source software. The
following examples show some applications of SQL:
1. Several Extract Transform Load (ETL) tools such as SQL Server Integration Services
(SSIS), Skyvia and Informatica use SQL to communicate with databases.
2. Programming languages such as Python and PHP usually embed SQL in their query
strings when connecting to a database.
3. Top Business intelligence (BI) tools such as the Microsoft Power BI and Tableau use
SQL to create reports and charts while working with data.
4. Most mobile application development frameworks: hybrid (Ionic, PhoneGap,
Xamarin, etc) and native (Android Studio and Swift) support SQL in their engines;
since many of these frameworks support SQLite.
5. Big data analytic tools that support the restfull API such as Elasticsearch and Sphinx
execute SQL queries to produce results.
8
1. DDL, DQL, DML, DCL and TCL Commands
Structured Query Language(SQL) as we all know is the database language by the
use of which we can perform certain operations on the existing database and
also, we can use this language to create a database. SQL uses certain commands
like Create, Drop, Insert, etc. to carry out the required tasks.
These SQL commands are mainly categorized into five categories as:
9
List of DDL commands:
CREATE: This command is used to create the database or its objects (like
table, index, function, views, store procedure, and triggers).
DROP: This command is used to delete objects from the database.
ALTER: This is used to alter the structure of the database.
TRUNCATE: This is used to remove all records from a table, including all
spaces allocated for the records are removed.
COMMENT: This is used to add comments to the data dictionary.
RENAME: This is used to rename an object existing in the database.
DQL (Data Query Language):
DQL statements are used for performing queries on the data within schema
objects. The purpose of the DQL Command is to get some schema relation
based on the query passed to it. We can define DQL as follows it is a component
of SQL statement that allows getting data from the database and imposing order
upon it. It includes the SELECT statement. This command allows getting the data
out of the database to perform operations with it. When a SELECT is fired
against a table or tables the result is compiled into a further temporary table,
which is displayed or perhaps received by the program i.e. a front-end.
List of DQL Commands:
SELECT: It is used to retrieve data from the database.
DML(Data Manipulation Language):
The SQL commands that deal with the manipulation of data present in the
database belong to DML or Data Manipulation Language and this includes most
of the SQL statements. It is the component of the SQL statement that controls
access to data and to the database. Basically, DCL statements are grouped with
DML statements.
List of DML commands:
INSERT : It is used to insert data into a table.
UPDATE: It is used to update existing data within a table.
DELETE : It is used to delete records from a database table.
LOCK: Table control concurrency.
CALL: Call a PL/SQL or JAVA subprogram.
EXPLAIN PLAN: It describes the access path to data.
10
DCL (Data Control Language):
DCL includes commands such as GRANT and REVOKE which mainly deal with the
rights, permissions, and other controls of the database system.
List of DCL commands:
GRANT: This command gives users access privileges to the database.
REVOKE: This command withdraws the user’s access privileges given by
using the GRANT command.
TCL (Transaction Control Language):
Transactions group a set of tasks into a single execution unit. Each transaction
begins with a specific task and ends when all the tasks in the group successfully
complete. If any of the tasks fail, the transaction fails. Therefore, a transaction
has only two results: success or failure. You can explore more about transactions
here. Hence, the following TCL commands are used to control the execution of a
transaction:
11
2. SQL PRIMARY KEY Constraint
The PRIMARY KEY constraint uniquely identifies each record in a table.
Primary keys must contain UNIQUE values, and cannot contain NULL values.
A table can have only ONE primary key; and in the table, this primary key can
consist of single or multiple columns (fields).
12
SQL PRIMARY KEY on ALTER TABLE
To create a PRIMARY KEY constraint on the "ID" column when the table is already
created, use the following SQL:
13
3. SQL FOREIGN KEY Constraint
The FOREIGN KEY constraint is used to prevent actions that would destroy links
between tables.
A FOREIGN KEY is a field (or collection of fields) in one table, that refers to the
PRIMARY KEY in another table.
The table with the foreign key is called the child table, and the table with the
primary key is called the referenced or parent table.
Look at the following two tables:
Persons Table
Orders Table
Notice that the "PersonID" column in the "Orders" table points to the
"PersonID" column in the "Persons" table.
The "PersonID" column in the "Persons" table is the PRIMARY KEY in the
"Persons" table.
The "PersonID" column in the "Orders" table is a FOREIGN KEY in the "Orders"
table.
The FOREIGN KEY constraint prevents invalid data from being inserted into the
foreign key column, because it has to be one of the values contained in the
parent table.
14
SQL FOREIGN KEY on CREATE TABLE
The following SQL creates a FOREIGN KEY on the "PersonID" column when the
"Orders" table is created:
CREATE TABLE Orders (OrderID int NOT NULL,
OrderNumber int NOT NULL, PersonID int,
PRIMARY KEY (OrderID),
FOREIGN KEY (PersonID) REFERENCES Persons(PersonID)
);
SQL FOREIGN KEY on ALTER TABLE
To create a FOREIGN KEY constraint on the "PersonID" column when the
"Orders" table is already created, use the following SQL:
ALTER TABLE Orders
ADD FOREIGN KEY (PersonID) REFERENCES Persons(PersonID);
To allow naming of a FOREIGN KEY constraint, and for defining a FOREIGN KEY
constraint on multiple columns, use the following SQL syntax:
ALTER TABLE Orders ADD CONSTRAINT FK_PersonOrder
FOREIGN KEY (PersonID) REFERENCES Persons(PersonID);
DROP a FOREIGN KEY Constraint
To drop a FOREIGN KEY constraint, use the following SQL:
ALTER TABLE Orders DROP FOREIGN KEY FK_PersonOrder;
15
4. SQL Syntax
Database Tables
A database most often contains one or more tables. Each table is identified by a
name (e.g. "Customers" or "Orders"). Tables contain records (rows) with data.
Below is a selection from the "Customers" table:
The table above contains five records (one for each customer) and seven
columns (CustomerID, CustomerName, ContactName, Address, City, PostalCode,
and Country).
SQL Statements
Most of the actions you need to perform on a database are done with SQL
statements. The following SQL statement selects all the records in the
"Customers" table:
SELECT * FROM Customers;
16
5. The SQL SELECT Statement
The SELECT statement is used to select data from a database. The data returned
is stored in a result table, called the result-set.
SELECT Syntax
SELECT column1, column2, ...FROM table_name;
Here, column1, column2, ... are the field names of the table you want to select
data from. If you want to select all the fields available in the table, use the
following syntax:
SELECT * FROM table_name;
17
6. SQL SELECT DISTINCT Statement
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.
SELECT Country
FROM Customers;
18
SELECT Example Without DISTINCT
The following SQL statement selects all (including the duplicates) values from
the "Country" column in the "Customers" table:
SELECT Country
FROM Customers;
19
7. SQL WHERE Clause
The WHERE clause is used to filter records.
It is used to extract only those records that fulfil a specified condition.
SELECT column1, column2, ...
FROM table_name
WHERE condition;
20
SELECT * FROM Customers
WHERE Country='Mexico';
Text Fields vs. Numeric Fields
SQL requires single quotes around text values. However, numeric fields should
not be enclosed in quotes:
SELECT * FROM Customers
WHERE CustomerID=1;
21
NOT Syntax
SELECT column1, column2, ...
FROM table_name
WHERE NOT condition;
AND Example
The following SQL statement selects all fields from "Customers" where country
is "Germany" AND city is "Berlin":
SELECT * FROM Customers
WHERE Country='Germany' AND City='Berlin';
OR Example
The following SQL statement selects all fields from "Customers" where country
is "Germany" OR "Spain":
SELECT * FROM Customers
22
WHERE Country='Germany' OR Country='Spain';
NOT Example
The following SQL statement selects all fields from "Customers" where country
is NOT "Germany":
SELECT * FROM Customers
WHERE NOT Country='Germany';
Combining AND, OR and NOT
You can also combine the AND, OR and NOT operators.
The following SQL statement selects all fields from "Customers" where country
is "Germany" AND city must be "Berlin" OR "München"
23
9. SQL ORDER BY
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.
ORDER BY Syntax
SELECT column1, column2, ...
FROM table_name
ORDER BY column1, column2, ... ASC|DESC;
24
ORDER BY Example
The following SQL statement selects all customers from the "Customers" table,
sorted by the "Country" column:
SELECT * FROM Customers
ORDER BY Country;
25
10. The SQL INSERT INTO Statement
The INSERT INTO statement is used to insert new records in a table.
INSERT INTO Syntax
It is possible to write the INSERT INTO statement in two ways:
1. Specify both the column names and the values to be inserted:
2. 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. However, make sure the
order of the values is in the same order as the columns in the table. Here,
the INSERT INTO syntax would be as follows:
26
INSERT INTO Example
The following SQL statement inserts a new record in the "Customers" table:
INSERT INTO Customers (CustomerName, ContactName, Address, City,
PostalCode, Country)
VALUES ('Cardinal', 'Tom B. Erichsen', 'Skagen 21', 'Stavanger', '4006',
'Norway');
The selection from the "Customers" table will now look like this:
The selection from the "Customers" table will now look like this:
27
11. SQL NULL Values
A field with a NULL value is a field with no value. If a field in a table is optional, it
is possible to insert a new record or update a record without adding a value to
this field. Then, the field will be saved with a NULL value. It is not possible to
test for NULL values with comparison operators, such as =, <, or <>. We will have
to use the IS NULL and IS NOT NULL operators instead.
IS NULL Syntax
SELECT column_name FROM table_name
WHERE column_name IS NULL;
28
The IS NULL Operator
The IS NULL operator is used to test for empty values (NULL values).The
following SQL lists all customers with a NULL value in the "Address" field:
29
12. SQL UPDATE Statement
The UPDATE statement is used to modify the existing records in a table.
SQL UPDATE Syntax
UPDATE table_name
SET column1 = value1, column2 = value2, ...
30
WHERE condition;
Below is a selection from the "Customers" table in the Northwind sample
database:
The following SQL statement updates the first customer (CustomerID = 1) with a
new contact person and a new city.
UPDATE Customers
SET ContactName = 'Alfred Schmidt', City= 'Frankfurt'
WHERE CustomerID = 1;
The selection from the "Customers" table will now look like this:
Update Warning
Be careful when updating records. If you omit the WHERE clause, ALL records
will be updated!
UPDATE Customers
SET ContactName='Juan';
The "Customers" table will now look like this:
32
Below is a selection from the "Customers" table in the Northwind sample
database:
The following SQL statement deletes the customer "Alfreds Futterkiste" from
the "Customers" table:
DELETE FROM Customers
WHERE CustomerName='Alfreds Futterkiste';
The "Customers" table will now look like this:
MIN() Example
The following SQL statement finds the price of the cheapest product:
SELECT MIN(Price)
AS SmallestPrice
FROM Products;
MAX() Example
The following SQL statement finds the price of the most expensive product:
SELECT MAX(Price)
AS LargestPrice
FROM Products;
COUNT() Example
The following SQL statement finds the number of products:
SELECT COUNT(ProductID)
FROM Products;
Note: NULL values are not counted.
AVG() Example
36
The following SQL statement finds the average price of all products:
SELECT AVG(Price)
FROM Products;
Below is a selection from the "OrderDetails" table in the Northwind sample
database:
SUM() Example
The following SQL statement finds the sum of the "Quantity" fields in the
"OrderDetails" table:
SELECT SUM(Quantity)
FROM OrderDetails;
37
The percent sign (%) represents zero, one, or multiple characters.
The underscore sign (_) represents one, single character.
The percent sign and the underscore can also be used in combinations!
LIKE Syntax
SELECT column1, column2, ...
FROM table_name
WHERE columnN LIKE pattern;
* You can also combine any number of conditions using AND or OR operators.
Here are some examples showing different LIKE operators with '%' and '_'
wildcards:
The table below shows the complete "Customers" table from the Northwind
sample database:
38
SQL LIKE Examples
The following SQL statement selects all customers with a CustomerName
starting with "a":
SELECT * FROM Customers
WHERE CustomerName LIKE 'a%';
The following SQL statement selects all customers with a CustomerName ending
with "a":
SELECT * FROM Customers
WHERE CustomerName LIKE '%a';
The following SQL statement selects all customers with a CustomerName that
have "or" in any position:
SELECT * FROM Customers
WHERE CustomerName LIKE '%or%';
The following SQL statement selects all customers with a CustomerName that
have "r" in the second position:
SELECT * FROM Customers
WHERE CustomerName LIKE '_r%';
The following SQL statement selects all customers with a CustomerName that
starts with "a" and are at least 3 characters in length:
39
SELECT * FROM Customers
WHERE CustomerName LIKE 'a__%';
The following SQL statement selects all customers with a ContactName that
starts with "a" and ends with "o":
Example
SELECT * FROM Customers
WHERE ContactName LIKE 'a%o';
The following SQL statement selects all customers with a CustomerName that
does NOT start with "a":
Example
SELECT * FROM Customers
WHERE CustomerName NOT LIKE 'a%';
40
18. SQL IN Operator
The IN operator allows you to specify multiple values in a WHERE clause.
The IN operator is a shorthand for multiple OR conditions.
SELECT column_name(s)
FROM table_name
WHERE column_name IN (value1, value2, ...);
or:
SELECT column_name(s)
FROM table_name
WHERE column_name IN (SELECT STATEMENT);
IN Operator Examples
The following SQL statement selects all customers that are located in
"Germany", "France" or "UK":
41
The following SQL statement selects all customers that are NOT located in
"Germany", "France" or "UK":
The following SQL statement selects all customers that are from the same
countries as the suppliers:
42
19. SQL Aliases
SQL aliases are used to give a table, or a column in a table, a temporary name.
Aliases are often used to make column names more readable.
An alias only exists for the duration of that query.
An alias is created with the AS keyword.
SELECT column_name(s)
FROM table_name AS alias_name;
43
20. SQL JOIN
A JOIN clause is used to combine rows from two or more tables, based on a
related column between them.
Different Types of SQL JOINs
Here are the different types of the JOINs in SQL:
(INNER) JOIN: Returns records that have matching values in both tables
LEFT (OUTER) JOIN: Returns all records from the left table, and the
matched records from the right table
RIGHT (OUTER) JOIN: Returns all records from the right table, and the
matched records from the left table
FULL (OUTER) JOIN: Returns all records when there is a match in either left
or right table.
44
SQL INNER JOIN Keyword
The INNER JOIN keyword selects records that have matching values in both
tables.
SELECT column_name(s)
FROM table1
INNER JOIN table2
ON table1.column_name = table2.column_name;
SQL INNER JOIN Example
The following SQL statement selects all orders with customer information:
SELECT Orders.OrderID, Customers.CustomerName
FROM Orders
INNER JOIN Customers ON Orders.CustomerID = Customers.CustomerID;
The INNER JOIN keyword selects all rows from both tables as long as there is a
match between the columns. If there are records in the "Orders" table that do
not have matches in "Customers", these orders will not be shown!
JOIN Three Tables
The following SQL statement selects all orders with customer and shipper
information:
SELECT Orders.OrderID, Customers.CustomerName,
Shippers.ShipperName
FROM ((Orders
INNER JOIN Customers ON Orders.CustomerID = Customers.CustomerID)
INNER JOIN Shippers ON Orders.ShipperID = Shippers.ShipperID);
45
SQL LEFT JOIN Keyword
The LEFT JOIN keyword returns all records from the left table (table1), and the
matching records from the right table (table2). The result is 0 records from the
right side, if there is no match.
SELECT column_name(s)
FROM table1
LEFT JOIN table2
ON table1.column_name = table2.column_name;
* In some databases LEFT JOIN is called LEFT OUTER JOIN.
SQL LEFT JOIN Example
The following SQL statement will select all customers, and any orders they might
have:
SELECT Customers.CustomerName, Orders.OrderID
FROM Customers
LEFT JOIN Orders ON Customers.CustomerID = Orders.CustomerID
ORDER BY Customers.CustomerName;
* The LEFT JOIN keyword returns all records from the left table (Customers),
even if there are no matches in the right table (Orders).
46
SQL RIGHT JOIN Keyword
The RIGHT JOIN keyword returns all records from the right table (table2), and
the matching records from the left table (table1). The result is 0 records from
the left side, if there is no match.
SELECT column_name(s)
FROM table1
RIGHT JOIN table2
ON table1.column_name = table2.column_name;
* In some databases RIGHT JOIN is called RIGHT OUTER JOIN.
SQL RIGHT JOIN Example
The following SQL statement will return all employees, and any orders they
might have placed:
SELECT Orders.OrderID, Employees.LastName, Employees.FirstName
FROM Orders
RIGHT JOIN Employees ON Orders.EmployeeID = Employees.EmployeeID
ORDER BY Orders.OrderID;
* The RIGHT JOIN keyword returns all records from the right table (Employees),
even if there are no matches in the left table (Orders).
47
SQL FULL OUTER JOIN Keyword
The FULL OUTER JOIN keyword returns all records when there is a match in left
(table1) or right (table2) table records.
* FULL OUTER JOIN and FULL JOIN are the same.
SELECT column_name(s)
FROM table1
FULL OUTER JOIN table2
ON table1.column_name = table2.column_name
WHERE condition;
* FULL OUTER JOIN can potentially return very large result-sets!
Below is a selection from the "Customers" table:
48
SQL FULL OUTER JOIN Example
The following SQL statement selects all customers, and all orders:
SELECT Customers.CustomerName, Orders.OrderID
FROM Customers
FULL OUTER JOIN Orders ON Customers.CustomerID=Orders.CustomerID
ORDER BY Customers.CustomerName;
* The FULL OUTER JOIN keyword returns all matching records from both tables
whether the other table matches or not. So, if there are rows in "Customers"
that do not have matches in "Orders", or if there are rows in "Orders" that do
not have matches in "Customers", those rows will be listed as well.
49
SQL Self Join
A self join is a regular join, but the table is joined with itself.
SELECT column_name(s)
FROM table1 T1, table1 T2
WHERE condition;
T1 and T2 are different table aliases for the same table.
Below is a selection from the "Customers" table:
50
SQL Self Join Example
The following SQL statement matches customers that are from the same city:
SELECT A.CustomerName AS CustomerName1, B.CustomerName AS
CustomerName2, A.City
FROM Customers A, Customers B
WHERE A.CustomerID <> B.CustomerID
AND A.City = B.City
ORDER BY A.City;
53
SELECT City, Country FROM Customers
WHERE Country='Germany'
UNION ALL
SELECT City, Country FROM Suppliers
WHERE Country='Germany'
ORDER BY City;
Another UNION Example
The following SQL statement lists all customers and suppliers:
SELECT 'Customer' AS Type, ContactName, City, Country
FROM Customers
UNION
SELECT 'Supplier', ContactName, City, Country
FROM Suppliers;
54
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.
SELECT column_name(s)
FROM table_name
WHERE condition
GROUP BY column_name(s)
ORDER BY column_name(s);
Below is a selection from the "Customers" table in the Northwind sample
database:
The following SQL statement lists the number of customers in each country,
sorted high to low:
SELECT COUNT(CustomerID), Country
FROM Customers
GROUP BY Country
ORDER BY COUNT(CustomerID) DESC;
55
Below is a selection from the "Orders" table in the Northwind sample database:
56
SELECT column_name(s)
FROM table_name
WHERE condition
GROUP BY column_name(s)
HAVING condition
ORDER BY column_name(s);
Below is a selection from the "Customers" table in the Northwind sample
database:
57
HAVING COUNT(CustomerID) > 5;
The following SQL statement lists the number of customers in each country,
sorted high to low (Only include countries with more than 5 customers):
SELECT COUNT(CustomerID), Country
FROM Customers
GROUP BY Country
HAVING COUNT(CustomerID) > 5
ORDER BY COUNT(CustomerID) DESC;
58
For doing operations on data SQL has many built-in functions, they are
categorized in two categories and further sub-categorized in different seven
functions under each category. The categories are:
1. Aggregate functions:
These functions are used to do operations from the values of the column and a
single value is returned.
AVG() - It returns the average value after calculating from values in a
numeric column.
Syntax: SELECT AVG(column_name) FROM table_name;
COUNT() - It is used to count the number of rows returned in a SELECT
statement. It can’t be used in MS ACCESS.
Syntax: SELECT COUNT(column_name) FROM table_name;
FIRST() - The FIRST() function returns the first value of the selected
column.
Syntax: SELECT FIRST(column_name) FROM table_name;
LAST() - The LAST() function returns the last value of the selected column.
It can be used only in MS ACCESS.
Syntax:SELECT LAST(column_name) FROM table_name;
MAX() - The MAX() function returns the maximum value of the selected
column.
Syntax:SELECT MAX(column_name) FROM table_name;
MIN() - The MIN() function returns the minimum value of the selected
column.
Syntax:SELECT MIN(column_name) FROM table_name;
SUM() - The SUM() function returns the sum of all the values of the
selected column.
Syntax:SELECT SUM(column_name) FROM table_name;
59
2.Scalar functions:
These functions are based on user input, these too returns single value.
UCASE() - It converts the value of a field to uppercase.
Syntax: SELECT UCASE(column_name) FROM table_name;
LCASE() - It converts the value of a field to lowercase.
Syntax:SELECT LCASE(column_name) FROM table_name;
MID() - The MID() function extracts texts from the text field.
Syntax:SELECT MID(column_name,start,length) AS some_name FROM
table_name; specifying length is optional here, and start signifies start position (
starting from 1 )
LEN() - The LEN() function returns the length of the value in a text field.
Syntax:SELECT LENGTH(column_name) FROM table_name;
ROUND() - The ROUND() function is used to round a numeric field to the
number of decimals specified.NOTE: Many database systems have adopted
the IEEE 754 standard for arithmetic operations, which says that when any
numeric .5 is rounded it results to the nearest even integer i.e, 5.5 and 6.5
both gets rounded off to 6.
Syntax: SELECT ROUND(column_name,decimals) FROM table_name;
decimals- number of decimals to be fetched.
NOW() - The NOW() function returns the current system date and time.
Syntax:SELECT NOW() FROM table_name;
FORMAT() - The NOW() function returns the current system date and time.
Syntax:SELECT NOW() FROM table_name;
60
25. SQL Stored Procedures for SQL Server
A stored procedure is a prepared SQL code that you can save, so the code can be
reused over and over again.
So if you have an SQL query that you write over and over again, save it as a
stored procedure, and then just call it to execute it.
You can also pass parameters to a stored procedure, so that the stored
procedure can act based on the parameter value(s) that is passed.
Stored Procedure Syntax
CREATE PROCEDURE procedure_name
AS
sql_statement
GO;
Execute a Stored Procedure
EXEC procedure_name;
Below is a selection from the "Customers" table in the Northwind sample
database:
61
CREATE PROCEDURE SelectAllCustomers
AS
SELECT * FROM Customers
GO;
Execute the stored procedure above as follows:
EXEC SelectAllCustomers;
Stored Procedure With One Parameter
The following SQL statement creates a stored procedure that selects Customers
from a particular City from the "Customers" table:
62
Execute the stored procedure above as follows:
63
26. SQL SELECT INTO Statement
The SELECT INTO statement copies data from one table into a new table.
Copy all columns into a new table:
SELECT *
INTO newtable [IN externaldb]
FROM oldtable
WHERE condition;
Copy only some columns into a new table:
SELECT column1, column2, column3, ...
INTO newtable [IN externaldb]
FROM oldtable
WHERE condition;
The new table will be created with the column-names and types as defined in
the old table. You can create new column names using the AS clause.
The following SQL statement creates a backup copy of Customers:
SELECT * INTO CustomersBackup2017
FROM Customers;
The following SQL statement uses the IN clause to copy the table into a new
table in another database:
SELECT * INTO CustomersBackup2017 IN 'Backup.mdb'
FROM Customers;
The following SQL statement copies only a few columns into a new table:
SELECT CustomerName, ContactName INTO CustomersBackup2017
FROM Customers;
The following SQL statement copies only the German customers into a new
table:
SELECT * INTO CustomersGermany
FROM Customers
WHERE Country = 'Germany';
64
The following SQL statement copies data from more than one table into a new
table:
SELECT Customers.CustomerName, Orders.OrderID
INTO CustomersOrderBackup2017
FROM Customers
LEFT JOIN Orders ON Customers.CustomerID = Orders.CustomerID;
Note: SELECT INTO can also be used to create a new, empty table using the
schema of another. Just add a WHERE clause that causes the query to return no
data:
SELECT * INTO newtable
FROM oldtable
WHERE 1 = 0;
65
27. SQL INSERT INTO SELECT Statement
The INSERT INTO SELECT statement copies data from one table and inserts it
into another table.
The INSERT INTO SELECT statement requires that the data types in source and
target tables match.
Note: The existing records in the target table are unaffected.
Copy all columns from one table to another table:
Copy only some columns from one table into another table:
66
SQL INSERT INTO SELECT Examples
The following SQL statement copies "Suppliers" into "Customers" (the columns
that are not filled with data, will contain NULL):
INSERT INTO Customers (CustomerName, City, Country)
SELECT SupplierName, City, Country FROM Suppliers;
The following SQL statement copies "Suppliers" into "Customers" (fill all
columns):
INSERT INTO Customers (CustomerName, ContactName, Address, City,
PostalCode, Country)
SELECT SupplierName, ContactName, Address, City, PostalCode, Country
FROM Suppliers;
The following SQL statement copies only the German suppliers into
"Customers":
INSERT INTO Customers (CustomerName, City, Country)
SELECT SupplierName, City, Country FROM Suppliers
WHERE Country='Germany';
67
28. SQL CASE Expression
The CASE expression goes through conditions and returns a value when the first
condition is met (like an if-then-else statement). So, once a condition is true, it
will stop reading and return the result. If no conditions are true, it returns the
value in the ELSE clause.
If there is no ELSE part and no conditions are true, it returns NULL.
CASE
WHEN condition1 THEN result1
WHEN condition2 THEN result2
WHEN conditionN THEN resultN
ELSE result
END;
69
29. SQL NULL Functions
SQL IFNULL(), ISNULL(), COALESCE(), and NVL() Functions
Look at the following "Products" table:
70
Suppose that the "UnitsOnOrder" column is optional, and may contain NULL
values.
Look at the following SELECT statement:
SELECT ProductName, UnitPrice * (UnitsInStock + UnitsOnOrder)
FROM Products;
In the example above, if any of the "UnitsOnOrder" values are NULL, the result
will be NULL.
The MySQL IFNULL() function lets you return an alternative value if an
expression is NULL:
71
72
THANK YOU
73