Using Basic Structured Query Language
Using Basic Structured Query Language
MODULE DESCRIPTION:
This module defines the competency required to use a basic structured query language (SQL) to define,
create and manipulate database structures and associated data in a relational database LEARNING
OUTCOMES At the end of the module the trainee will be able to:
DBMS fundamental
A database management system (DBMS) is a software tool that enables users to manage a database
easily. It allows users to access and interact with the underlying data in the database. These actions can
range from simply querying data to defining database schemas that fundamentally affect the database
structure.
Furthermore, DBMS allow users to interact with a database securely and concurrently without interfering
with each user and while maintaining data integrity.
Defining- A database involves specifying the data types, structures, and constraints for the data to
be stored in the database.
Constructing- The database is the process of storing the data itself on some storage, medium that
is controlled by the DBMS.
Manipulating- A database includes such as querying the database to retrieve specific data,
updating the database to reflect changes in the mini-world, and generating reports from the data.
Applications of DBMS
Banking- All transactions
Airlines- Reservations, schedules
Universities- Registrations, grades
Sales- Customers, products, purchase
Manufacturing- Production, inventory, orders, supply chain
Purpose of Database System
In early days database applications were built on top of the file systems.
# Drawbacks of using file systems to store data,
Data redundancy and inconsistency — multiple file-formats, duplication of information in
different files.
Difficulty in accessing data — need to re-write programs to carry out new tasks.
Data isolation
Integrity problems — hard to add or change constraints.
Atomicity of updates — failures may leave the database in an inconsistent state with partial
updates carried out.
Concurrent access from multiple users.
Security problems.
Benefits of the database approach
Potential for enforcing standards — defined for names and formats of data elements, display
formats, report structure, terminology, etc.
Reduced application development time — development time using a DBMS is estimated to be
one-sixth to one-fourth of that for a traditional file system.
Flexibility — easy to change the structure of a database as requirements change.
Availability of up to date information.
Components of a database management system
All DBMS comes with various integrated components and tools necessary to carry out almost all database
management tasks. Some DBMS software even provides the ability to extend beyond the core
functionality by integrating with third-party tools and services, directly or via plugins.
In this section, we will look at the common components that are universal across all DBMS software,
including:
Storage engine
Data Manipulation Language (DML). Commands that directly deal with the data in the
database. All CRUD operations come under DML.
DML(Data Manipulation Language): Once the tables are created and the database is generated
using DDL commands, manipulation inside those tables and databases is done using DML
commands. The advantage of using DML commands is, that if in case any wrong changes or
values are made, they can be changed and rolled back easily.
DML commands:
INSERT: It is used to insert data into a table.
INSERT INTO Student (Stu_id, Stu_Name, Stu_Marks, Stu_Age) VALUES (104, A
nmol, 89, 19);
UPDATE: It is used to update existing data within a table.
UPDATE Product SET Product_Price = 80 WHERE Product_Id = 'P102' ;
UPDATE Student SET Stu_Marks = 80, Stu_Age = 21 WHERE Stu_Id = 103 AND S
tu_Id = 202;
DELETE: It is used to delete records from a database table.
DELETE FROM Product WHERE Product_Id = 'P202' ;
DELETE FROM Student WHERE Stu_Marks > 70 ;
o LOCK: Table control concurrency.
o CALL: Call a PL/SQL or JAVA subprogram.
o EXPLAIN PLAN: It describes the access path to data.
DQL(Data Query Language): Data query language consists of only one command upon which
data selection in SQL relies. The SELECT command in combination with other SQL clauses is
used to retrieve and fetch data from databases/tables based on certain conditions applied by the
user. The SELECT command is used in Data Query Language Command
EXAMPLE
Select * FROM dost;
Select: It is used to retrive data into a table.
SELECT * FROM table_name;
SELECT Emp_Id, Emp_Salary FROM Employee;
SELECT * FROM Student WHERE Stu_Marks = 80;
DCL(Data Control Language): DCL commands as the name suggests manage the matters and
issues related to the data controller in any database. DCL includes commands such
as GRANT and REVOKE which mainly deal with the rights, permissions, and other controls of
the database system.
DCL commands:
o GRANT: This command gives users access privileges to the database.
EXAMPLE
o GRANT SELECT, UPDATE ON TABLE Student TO groupx;
o GRANT INSERT ON films TO PUBLIC;
o REVOKE Insert ON films FROM PUBLIC;
Transaction Control Language (TCL). Command which deals with internal database
transactions.
Query processor
This is the intermediary between the user queries and the database. The query processor
interprets the queries of users and makes them actionable commands that can be understood by
the database to perform the appropriate functionality.
Optimization engine
The optimization Engine allows the DBMS to provide insights into the performance of the
database in terms of optimizing the database itself and queries. When coupled with database
monitoring tools, it can provide a powerful toolset to gain the best performance out of the
database.
Metadata catalog
This is the centralized catalog of all the objects within the database. When an object is created,
the DBMS keeps a record of that object with some metadata about it using the metadata catalog.
Then, this record can be used to:
Verify user requests to the appropriate database objects
Provide an overview of the complete database structure
Log manager
This component will keep all the logs of the DBMS. These logs will consist of user logins and
activity, database functions, backups and restore functions, etc. The log manager ensures all
these logs are properly recorded and easily accessible.
Reporting & monitoring tools
Advantages of a DBMS
DBMS was introduced to solve the fundamental issues associated with storing, managing,
accessing, securing, and auditing data in traditional file systems. Software users and
organizations can gain the following benefits by using DBMS:
Data integration
DBMS allows users to gain a centralized view of databases spread across multiple locations and
manage them using a single interface rather than operating them as separate entities.
The WHERE clause is used to constrain which rows to retrieve. We do this by specifying a
boolean predicate that compares the values of table columns to literal values or to other columns.
The ORDER BY clause gives us a way to order the display of the rows in the result of the
statement.
The example of the next section provides more information on how to retrieve information using
this SELECT statement.
SQL statement to retrieve all customers and the result set While the result of a query is known as
a result set, the result is not in fact always a set. The result could be a multi set, that is, a
collection of rows that can have duplicate rows.
Clearly we need to a refinement step as the query retrieves all customers while we are only
interested in customers who live in zip code 90840. We need to specify in the statement that the
only rows to retrieve from the database are those that meet this criteria. Such qualifying criteria
is specified in the WHERE clause using boolean expressions. Our first statement is thus refined
as shown in the figure below.
Note that SQL syntax requires the use of single quotes around literal strings like '90840'. While
not illustrated in this example and unlike SQL keywords, literal strings and strings stored in the
database are case sensitive; thus, 'Long Beach' is a different string than 'long beach'.
We need just a couple of more refinements. While we now are retrieving only the customers we
desire, we are also retrieving every column from the table yet, not all are needed. We need a way
In addition to that, ORDER BY clause can also sort the data in a database table in a preferred
order. This case may not sort the records of a table in any standard order (like alphabetical or
lexicographical), but, they could be sorted based on any external condition. For instance, in an
ORDERS table containing the list of orders made by various customers of an organization, the
details of orders placed can be sorted based on the dates those orders are made. This need not be
alphabetically sorted,instead it is based on first come first serve.
There are various types of clauses available in SQL, and some of them are listed below:
Clause Description
HAVING HAVING clause can be used in a GROUP BY clause. It is used to specify a search
condition for a group in the database tables.
WHERE The WHERE clause in SQL is used to retrieve the specific data from the database
that specifies the conditions exactly that are given in the UPDATE, DELETE, etc.
statements.
ORDER The ORDER BY clause in SQL is used for sorting the records of the database
BY tables.
GROUP To group the result set of the rows that have the same values in the result set from
BY the database tables, the GROUP BY clause is used.
TOP This clause is used when the database has many records. It is used to specify the
total number of records to be fetched or returned.
WITH WITH clause acts as a temporary view as it is available only during the execution
of SELECT, UPDATE, INSERT, DELETE, etc. statements. It is used to simplify
complex and long queries.
LIKE The SQL LIKE clause compares a value to similar values using wildcard operators,
i.e. per cent sign ( % ) and the underscore operator ( _ ).
FROM The FROM clause in SQL is used to select the database tables, which are
manipulated using the SELECT, DELETE, and UPDATE statements.
LIMIT The LIMIT clause is used when you are dealing with large databases. It is used to
specify the maximum number of rows to be retrieved from the table.
AND The AND clause is used when multiple conditions are specified in a query and
returns a dataset when all the conditions given in the AND clause meet the
requirements.
OR The OR clause is used when multiple conditions are specified in a query and returns
a dataset when one of those conditions gets satisfied.
WHERE
The WHERE clause in SQL is used to fetch the data or certain records that match the specified
condition in the SELECT statement. SQL's WHERE clause is also used with
the DELETE, UPDATE, etc. statements.
GROUP BY
Another usage of the clause in SQL is to group the rows that have the same values in the result
set, and this can be achieved by using the GROUP BY clause in SQL.
TOP
If you want to determine the total number of record rows in the result then you can use
the TOP clause in SQL.
AND
The AND clause is used with the UPDATE and DELETE statements and returns the resultant
dataset only when all the conditions given with the AND clause are satisfied.
OR
The OR clause is also used with the UPDATE and DELETE statements and returns the resultant
dataset when one or more than one condition is satisfied.
LIMIT
When the amount of data in the database is very large, the LIMIT clause is used to restrict the
number of rows from the database records.
Example: The following query uses the GROUP BY clause to fetch the total fees in the students'
individual classes. This can be easily done by grouping of the rows from the Students table.
SELECT SUM(stu_fees), stu_class FROM Students GROUP BY stu_class;
Output:
stu_fees stu_class
9000 10
4500 11
7500 9
As shown in the output above, the GROUP BY clause is used to group the rows of the students
based on the student class column. The total fees in an individual class are summed up, and the
grouped rows are displayed in the table.
Example: Let's take another example which includes the ORDER BY clause in SQL. The below
query is used to order the students based on the fees of the individual students.
SELECT * FROM Students ORDER BY stu_fees;
Output:
stu_id stu_name stu_fees stu_subject stu_age stu_class
2 Mayra Pandit 2000 Social Science 16 10
4 Manvi Tyagi 2000 Social Science 16 9
6 Tisha Shah 2500 Science 15 9
1 Divyesha Patil 3000 Maths 16 10
5 Joy Yadav 3000 Maths 16 9
7 Surbhi Soni 4000 Chemistry 17 10
3 Kunal Purohit 4500 Chemistry 17 11
In the above example, the ORDER BY clause is applied to the column stu_fees to sort the final
result based on the fees of the students.
Example:
Consider another example which explains the HAVING clause in SQL. The following query
returns the details of all the students having an age less than 17 after grouping the records based
on stu_id.
SELECT * FROM Students GROUP BY stu_id HAVING stu_age < 17;
Output:
stu_id stu_name stu_fees stu_subject stu_age stu_class
1 Divyesha Patil 3000 Maths 16 10
2 Mayra Pandit 2000 Social Science 15 9
4 Manvi Tyagi 2000 Social Science 16 9
5 Joy Yadav 3000 Maths 16 10
6 Tisha Shah 2500 Science 15 9
1.11 Using SQL syntax to supress duplicate values from query result
How to Remove Duplicates in SQL Using the DISTINCT Keyword
One of the easiest ways to remove duplicate data in SQL is by using the DISTINCT keyword.
You can use the DISTINCT keyword in a SELECT statement to retrieve only unique values
from a particular column.
Here's an example of how to use the DISTINCT keyword to remove duplicates from a table:
SELECT DISTINCT customer_name FROM customers;
Here's an example of how to use the GROUP BY clause to remove duplicates from a table:
SELECT customer_id FROM orders GROUP BY customer_id;
Here's an example of how to use the INNER JOIN statement to remove duplicates from a table:
SELECT a.column_name
FROM table_name a
INNER JOIN table_name b ON a.column_name = b.column_name
WHERE a.primary_key > b.primary_key;
SELECT a.department_id
FROM employees a
INNER JOIN employees b ON a.department_id = b.department_id
WHERE a.employee_id > b.employee_id;
IS NULL Condition
The IS NULL condition is used to return rows that contain the NULL values in a column and its
syntax is like below:
The following query will retrieve the rows from the Person table which are MiddleName column
values are equal to NULL.
Order of Precedence
The following rules determine the order of precedence for arithmetic operators in an MDX
expression:
When there is more than one arithmetic operator in an expression, MDX performs
multiplication and division first, followed by subtraction and addition.
When all arithmetic operators in an expression have the same level of precedence, the
order of execution is left to right.
Expressions within parentheses take precedence over all other operations.
SELECT 100 + 200 ;
SELECT 45 - 74 ;
SELECT 25 * 4 ;
SELECT 36 / 6 ;
SELECT 17 % 4 ;
2.2. Using string functions and operators to obtain required query output
SQL string functions are used primarily for string manipulation. The following table details the
important string functions –
Example
The following SELECT query displays the SQL ASCII value of the first character of the given
string.
SELECT ASCII ("SQL stands for Structured Query Language") AS ASCII_S;
The following SELECT query displays the ASCII value of the string we have given.
select ASCII ("Kaushik");
The CHAR() function does not support multiple integer arguments, if we try to pass multiple
values it generates an error saying "The char function requires 1 argument(s)"
We can also use this function with along with the table columns, by passing them as parameters,
along with strings, and characters.
Example
The following SELECT query displays the CHAR value of 100 −
SELECT CHAR(100) AS char_function;
The SQL CHARINDEX() function searches for a substring within a string starting at the
specified location and returns the position of the substring found. If the substring was not found
this function returns 0. It accepts three parameters, substring, string(The string to be searched),
start(It is an optional parameter) The position where the search will start.
Parameters
Here, CHARINDEX() Function accepts three parameters −
substring − The substring to search for, It has the limit of 8000 characters.
string − The string to be searched.
start − It is an optional parameter. The position where the search will start (if you do not
want to start at the beginning of string). The first position in string is 1.
Return value
This function returns the position of a substring within the given string, If the substring is not
found in the string, the function returns 0.
Example
Example
The following SELECT query adds two characters and creates a new string −
SELECT CONCAT_WS('_','Tutorialspoint', 'Company') AS CONCAT_WSfunction;
The SQL CONCAT() function accepts a one or more string values as parameters,
concatenates/join all the given strings and returns the result.
When we display the result, the Concat service converts the Null values to an empty string. The
operator is used to concatenate character strings and column strings. In the CONCAT function,
we can use a literal. A literal is a number, character, or date that is contained in a SELECT
statement.
The SQL CONCAT() function accepts a one or more string values as parameters,
concatenates/join all the given strings and returns the result.
When we display the result, the Concat service converts the Null values to an empty string. The
operator is used to concatenate character strings and column strings. In the CONCAT function,
We can use a literal. A literal is a number, character, or date that is contained in a SELECT
statement.
The SQL server DIFFERENCE() function is used to compare two SOUNDEX values of the
strings. It accepts two parameters, exp1 and exp2 and returns an integer value that indicates a
match for two SOUNDEX values, from 0 to 4.
The Soundex value is a four-character code that is based on how the string sounds when spoken
in English. Here, the 0 value indicates little or no similarity between SOUNDEX values, whereas
the value 4 indicates strong similarity or matching SOUNDEX values.
Parameters
Example
Following is an example using DIFFERENCE() function with similar SOUNDEX values −
SELECT SOUNDEX('Had') AS soundex_Had, SOUNDEX('Hadi') AS soundex_Hadi,
DIFFERENCE('Had', 'Hadi') AS similarity;
MOD(X,Y)
The variable X is divided by Y and their remainder is returned. For example −
Select mod(9,5);
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);
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);
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.
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
−
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.
GETDATE() function
Verification
When we execute the above SQL query, we get the current date with time as follow −
+-------------------------+
| current datetime |
+-------------------------+
| 2023-02-06 14:10:49.860 |
+-------------------------+
CURRENT_TIMESTAMP
The current_timestamp is used to obtain the current timestamp and it returns the same date and
time as the GETDATE() function. Its datatypes are also date and time. As shown in the
following SQL query, the CURRENT_TIMESTAMP typically returns the current time along
with the current date −
SELECT CURRENT_TIMESTAMP AS 'CURRENTTIMESTAMP';
SYSDATETIME() Function
The SYSDATETIME() function is also used to obtain the current time of the system on which
the SQL server instance is running. It has larger fractional-second precision compared to the
GETDATE() function. Following is the SQL query for the SYSDATETIME() function.
SELECT SYSDATETIME() AS 'Current Time and Date';
CONVERT() Function
We are extracting the time using the GETDATE() OR CURRENT_TIMESTAMP inside convert
function to separate the time component from the current date (from the SYSDATE), as we can
see in the SQL query that follow −
SELECT CONVERT(VARCHAR(8), GETDATE(), 108) AS 'HH:MM:SS';
Verification
When we run the above SQL query, we only get the time in "HH:MM:SS" because we are using
108. 108 is a time-only format that displays the time in the "HH:MM:SS" format.
DBA generally used these functions for summarizing their data. When aggregate functions are
invoked with a particular set of input values multiple times, they always return the same value.
This table shows some other aggregate functions used in SQL Server:
Aggregate Function Descriptions
CHECKSUM_AGG It calculates the checksum of the values in a defined set.
COUNT_BIG() It counts the number of elements, including NULL values in a defined set.
This function is the same as the COUNT() function, but it returns a BIG INT
data type, whereas COUNT returns an INT data type.
STDEV() It calculates the statistical standard deviation of each value in the defined
expression on the basis of a sample data population.
STDEVP() It calculates the standard deviation for each value in the given expression on
the basis of an entire data population.
VAR() It calculates the statistical variance of each element in the defined expression
on the basis of a sample data population.
VARP() It calculates the statistical variance of each element in the defined expression
on the basis of an entire data population.
GROUPING() It signifies whether or not a GROUP BY lists specified column expression is
aggregated. If the result set shows 1, it means the result set is aggregated and,
if not, returns 0.
GROUPING_ID() It is used to computes the level of grouping.
Why we use aggregate functions?
COUNT() Function
This function returns the total number of rows, including NULL values in the given expression.
It can also count all records based on a specified condition and returns zero if it does not find
any matching records. It can work with both numeric and non-numeric data types.
Example
The below example uses the COUNT() function and returns the total number of employees data
stored in the employee table:
SUM() Function
This function calculates the total summation of NON-NULL values in the given set. It returns
NULL if the result set does not have any records. The SUM function can only work with
the numeric data type.
Example
The below example uses the SUM function and calculates the total summed up salary of all
employees stored in the employee table:
SELECT SUM(salary) AS total_salary FROM employee;
Output:
After execution, we can see the total salary of all employees in the table:
AVG() Function
This function calculates the average of NON-NULL values specified in the column. The AVG
function can only work with the numeric data type.
Example
The below example uses the AVG function and calculates the average salary of employees stored
in the employee table:
SELECT AVG(salary) AS "Average Salary" FROM employee;
Output:
Example
The below example uses the MIN function and returns the lowest salary of an employee stored in
the employee table:
SELECT MIN(salary) AS "Lowest Salary" FROM employee;
Output:
Here we can see that the minimum salary of an employee available in the table:
MAX() Function
This function gives the maximum (highest) value of the specified column. It also works with
numeric data types only.
Example
The below example uses the MAX function and returns the highest salary of employees stored in
the employee table:
SELECT MAX(salary) AS "Highest Salary" FROM employee;
Output:
Suppose we want to calculate the total number of employee and their addresses from two
different tables. We can do this by using the below statement:
Example 1: Let's take the following Employee table, which helps you to analyze the HAVING
clause with SUM aggregate function:
Emp_Id Emp_Name Emp_Salary Emp_City
201 Abhay 2000 Goa
If you want to add the salary of employees for each city, you have to write the following query:
SELECT SUM(Emp_Salary), Emp_City FROM Employee GROUP BY Emp_City;
Now, suppose that you want to show those cities whose total salary of employees is more than
5000. For this case, you have to type the following query with the HAVING clause in SQL:
SELECT SUM(Emp_Salary), Emp_City FROM Employee GROUP BY Emp_City HAVING S
UM(Emp_Salary)>5000;
The output of the above SQL query shows the following table in the output:
SUM(Emp_Salary) Emp_City
9000 Delhi
8000 Jaipur
Example 2: Let's take the following Student_details table, which helps you to analyze the
HAVING clause with the COUNT aggregate function:
Roll_No Name Marks Age
1 Rithik 91 20
2 Kapil 60 19
3 Arun 82 17
4 Ram 92 18
5 Anuj 50 20
6 Suman 88 18
7 Sheetal 57 19
8 Anuj 64 20
Suppose, you want to count the number of students from the above table according to their age.
For this, you have to write the following query:
SELECT COUNT(Roll_No), Age FROM Student_details GROUP BY Age ;
Now, suppose that you want to show the age of those students whose roll number is more than
and equals 2. For this case, you have to type the following query with the HAVING clause in
SQL:
SELECT COUNT(Roll_No), Age FROM Student_details GROUP BY Age HAVING COUNT(
Roll_No) >= 2 ;
The output of the above SQL query shows the following table in the output:
Count(Roll_No) Age
3 20
2 19
2 18
Example 3: Let's take the following Employee table, which helps you to analyze the HAVING
clause with MIN and MAX aggregate function:
Emp_ID Name Emp_Salary Emp_Dept
1001 Anuj 9000 Finance
1002 Saket 4000 HR
1003 Raman 3000 Coding
1004 Renu 6000 Coding
1005 Seenu 5000 HR
1006 Mohan 10000 Marketing
1007 Anaya 4000 Coding
1008 Parul 8000 Finance
Now, suppose that you want to show only those departments whose minimum salary of
employees is greater than 4000. For this case, you have to type the following query with the
Example 4: Let's take the following Employee_Dept table, which helps you to analyze the
HAVING clause with AVG aggregate function:
Emp_ID Name Emp_Salary Emp_Dept
1001 Anuj 8000 Finance
1002 Saket 4000 HR
1003 Raman 3000 Coding
1004 Renu 6000 Coding
1005 Seenu 5000 HR
1006 Mohan 10000 Marketing
1007 Anaya 4000 Coding
1008 Parul 6000 Finance
If you want to find the average salary of employees in each department, you have to write the
following query:
SELECT AVG(Emp_Salary), Emp_Dept FROM Employee_Dept GROUP BY Emp_Dept;
The above query will show the following output:
AVG(Emp_Salary) Emp_Dept
7000 Finance
4500 HR
The above SQL query will show the following table in the output:
AVG(Emp_Salary) Emp_Dept
7000 Finance
6500 Coding
10000 Marketing
Now, you have to create the new table using the following CREATE TABLE syntax:
CREATE TABLE table_name
(
column_Name_1 data type (size of the column_1),
column_Name_2 data type (size of the column_2),
The following query creates the Doctor_Info table in the Hospital Database:
The following query inserts the record of those doctors who work in Hospital:
Output:
Output:
The following query shows the minimum marks of a student in each subject from the above
School_Stu_Details table:
The following query simply shows the record of students in the tabular form:
SELECT * FROM School_Stu_Details;
Stu_ID Stu_Name Stu_Subject Stu_Age Stu_Marks
101 Anuj English 20 88
102 Raman Maths 24 98
104 Shyam Hindi 19 92
107 Vikash Computer 20 78
111 Monu English 21 65
114 Jones Hindi 18 93
121 Parul Maths 20 97
123 Divya English 21 89
128 Hemant Computer 23 90
130 Nidhi Hindi 20 88
132 Priya English 22 99
138 Mohit Maths 21 92
The following query shows the maximum marks of a student in each subject from the above
School_Stu_Details table:
The subquery (inner query) executes once before the main query (outer query) executes.
The main query (outer query) use the subquery result.
marks
Now we want to write a query to identify all students who get better marks than that of the
student who's StudentID is 'V002', but we do not know the marks of 'V002'.
- To solve the problem, we require two queries. One query returns the marks (stored in
Total_marks field) of 'V002' and a second query identifies the students who get better marks than
the result of the first query.
First query:
SELECT * FROM `marks`WHERE studentid = 'V002';
Copy
Query result:
Second query:
You can combine the above two queries by placing one query inside the other. The subquery
(also called the 'inner query') is the query inside the parentheses. See the following code and
query result :
SQL Code:
SELECT a.studentid, a.name, b.total_marks
FROM student a, marks b
WHERE a.studentid = b.studentid AND b.total_marks >
(SELECT total_marks
FROM marks
WHERE studentid = 'V002');
Copy
Query result:
Here are the syntax and an example of subqueries using UPDATE statement.
UPDATE neworder SET ord_date='15-JAN-10' WHERE ord_amount-
advance_amount<(SELECT MIN(ord_amount) FROM orders);
4.2 Constructing sub-queries that return single row and multiple row
The above query returns the average 'ord_amount' 2500, is used in the WHERE clause of the
outer query shown earlier.
SELECT MAX(AVG(min_salary))
FROM jobs
WHERE job_id
IN(
'ST_CLERK','ST_CLERK','IT_PROG',
'SA_REP','SA_MAN','AD_ASST', '
AC_ACCOUNT')
GROUP BY job_id;
The subquery returns the maximum of averages of min_salary for each unique job_id return ( i.e.
'ST_CLERK','ST_CLERK','IT_PROG', 'SA_REP','SA_MAN','AD_ASST', 'AC_ACCOUNT' )
by the previous subquery.
Now the outer query that receives output from the subquery and which also receives the output
from the nested subquery stated above.
The outer query returns the job_id, average salary of employees that are less than maximum of
average of min_salary returned by the previous query
CORRELATED DELETE :
DELETE FROM table1 alias1
WHERE column1 operator
(SELECT expression
FROM table2 alias2
WHERE alias1.column = alias2.column);
Use a correlated subquery to delete rows in one table based on the rows from another
table.