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

Module 4 DBMS

SQL, or Structured Query Language, is a standard language used for managing data in relational database management systems (RDBMS) such as MySQL and Oracle. It includes various commands categorized into Data Definition Language (DDL), Data Manipulation Language (DML), Data Control Language (DCL), Transaction Control Language (TCL), and Data Query Language (DQL) for creating, modifying, and querying databases. SQL also allows for defining constraints on data to ensure data integrity and uniqueness.

Uploaded by

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

Module 4 DBMS

SQL, or Structured Query Language, is a standard language used for managing data in relational database management systems (RDBMS) such as MySQL and Oracle. It includes various commands categorized into Data Definition Language (DDL), Data Manipulation Language (DML), Data Control Language (DCL), Transaction Control Language (TCL), and Data Query Language (DQL) for creating, modifying, and querying databases. SQL also allows for defining constraints on data to ensure data integrity and uniqueness.

Uploaded by

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

Module 4 -SQL

o SQL stands for Structured Query Language. It is used for storing and managing data in relational database
management system (RDMS).
o It is a standard language for Relational Database System. It enables a user to create, read, update and delete
relational databases and tables.
o All the RDBMS like MySQL, Informix, Oracle, MS Access and SQL Server use SQL as their standard
database language.
o SQL allows users to query the database in a number of ways, using English-like statements.

Rules:SQL follows the following rules:


o Structure query language is not case sensitive. Generally, keywords of SQL are written in uppercase.
o Statements of SQL are dependent on text lines. We can use a single SQL statement on one or multiple text
line.
o Using the SQL statements, you can perform most of the actions in a database.
o SQL depends on tuple relational calculus and relational algebra.

Characteristics of SQL
o SQL is easy to learn.,SQL is used to access data from relational database management systems.
o SQL can execute queries against the database.SQL is used to describe the data.
o SQL is used to define the data in the database and manipulate it when needed.
o SQL is used to create and drop the database and table.SQL is used to create a view, stored procedure,
function in a database.
o SQL allows users to set permissions on tables, procedures, and views.

SQL Command:SQL defines following ways to manipulate data stored in an RDBMS


Types of SQL :Here are five types of widely used SQL queries.
• Data Definition Language (DDL)
• Data Manipulation Language (DML)
• Data Control Language(DCL)
• Transaction Control Language(TCL)
• Data Query Language (DQL)

DDL: Data Definition Language


This includes changes to the structure of the table like creation of table, altering table, deleting a table etc.
All DDL commands are auto-committed. That means it saves all the changes permanently in the database.

Command Description

create to create new table or database

alter for alteration

truncate delete data from table

drop to drop a table

rename to rename a table

DML: Data Manipulation Language

DML commands are used for manipulating the data stored in the table and not the table itself.DML commands are
not auto-committed. It means changes are not permanent to database, they can be rolled back.

Command Description

insert to insert a new row

update to update existing row

delete to delete a row

merge merging two rows or two tables

TCL: Transaction Control Language

These commands are to keep a check on other commands and their affect on the database. These commands can
annul changes made by other commands by rolling the data back to its original state. It can also make any
temporary change permanent.
Command Description

commit to permanently save

rollback to undo change

savepoint to save temporarily

DCL: Data Control Language

Data control language are the commands to grant and take back authority from any database user.

Command Description

grant grant permission of right

revoke take back permission.

DQL: Data Query Language

Data query language is used to fetch data from tables based on conditions that we can easily apply.

Command Description

select retrieve records from one or more table

DDL
Data Definition Language helps you to define the database structure or schema. Let’s learn about DDL commands
with syntax.
CREATE CREATE statements is used to define the database structure schema:
Syntax:CREATE TABLE TABLE_NAME (COLUMN_NAME DATATYPES[,....]);
For example:Create database university;Create table students;Create view for_students;
DROP : Drops commands remove tables and databases from RDBMS.
Syntax :DROP TABLE ;
For example:Drop object_typeobject_name;Drop database university;Drop table student;
ALTER : Alters command allows you to alter the structure of the database.
Syntax:To add a new column in the table
ALTER TABLE table_name ADD column_name COLUMN-definition;
To modify an existing column in the table:ALTER TABLE MODIFY(COLUMN DEFINITION....);
For example:Alter table guru99 add subject varchar;
TRUNCATE:This command used to delete all the rows from the table and free the space containing the table.
Syntax:TRUNCATE TABLE table_name;
Example:TRUNCATE table students;

DML
Data Manipulation Language (DML) allows you to modify the database instance by inserting, modifying, and
deleting its data. It is responsible for performing all types of data modification in a database.
There are three basic constructs which allow database program and user to enter data and information are:
Here are some important DML commands in SQL:
• INSERT
• UPDATE
• DELETE
INSERT:This is a statement is a SQL query. This command is used to insert data into the row of a table.
Syntax:INSERT INTO TABLE_NAME(col1, col2, col3,.... col N)VALUES (value1, value2, ….valueN);
Or INSERT INTO TABLE_NAME VALUES (value1, value2, value3, .... valueN);
For example:INSERT INTO students (RollNo, FIrstName, LastName) VALUES ('60', 'Tom', Erichsen');
UPDATE:This command is used to update or modify the value of a column in the table.
Syntax:UPDATEtable_name SET [column_name1= value1,...column_nameN = valueN] [WHERE
CONDITION]
For example:UPDATE students SET FirstName = 'Jhon', LastName= 'Wick' WHERE StudID = 3;
DELETE:This command is used to remove one or more rows from a table.
Syntax:DELETE FROM table_name [WHERE condition];
For example:DELETE FROM students WHERE FirstName = 'Jhon';

DCL
DCL (Data Control Language) includes commands like GRANT and REVOKE, which are useful to give “rights &
permissions.” Other permission controls parameters of the database system.
DCL commands:Commands that come under DCL:
• Grant
• Revoke
Grant: This command is use to give user access privileges to a database.
Syntax:GRANT SELECT, UPDATE ON MY_TABLE TO SOME_USER, ANOTHER_USER;
For example:GRANT SELECT ON Users TO'Tom'@'localhost;
Revoke: It is useful to back permissions from the user.
Syntax:REVOKEprivilege_nameONobject_nameFROM {user_name |PUBLIC |role_name}
For example:REVOKE SELECT, UPDATE ON student FROM BCA, MCA;
TCL
Transaction control language or TCL commands deal with the transaction within the database.
Commit:This command is used to save all the transactions to the database.
Syntax: Commit;
For example:DELETE FROM Students WHERERollNo =25;
COMMIT;
Rollback :Rollback command allows you to undo transactions that have not already been saved to the database.
Syntax:ROLLBACK;
Example:DELETE FROM Students WHERE RollNo =25;
SAVEPOINT: This command helps you to sets a save point within a transaction.
Syntax:SAVEPOINT SAVEPOINT_NAME;

DQL
Data Query Language (DQL) is used to fetch the data from the database. It uses only one command:
SELECT:This command helps you to select the attribute based on the condition described by the WHERE clause.
Syntax:SELECT expressions FROM TABLES WHERE conditions;
For example:SELECTFirstName FROM Student WHERE RollNo> 15;

SQL Table
Table is a collection of data, organized in terms of rows and columns. In DBMS term, table is known as relation
and row as tuple.Table is the simple form of data storage. A table is also considered as a convenient representation
of relations.

Employee

EMP_NAME ADDRESS SALARY

Ankit Lucknow 15000

Raman Allahabad 18000

Mike New York 20000

SQL TABLE Variable


The SQL Table variable is used to create, modify, rename, copy and delete tables. It is a variable where we
temporary store records and results. This is same like temp table but in the case of temp table we need to explicitly
drop it.Table variables are used to store a set of records. So declaration syntax generally looks like CREATE
TABLE syntax.
create table "tablename" ("column1" "data type", "column2" "data type", ... "columnN" "data type");
SQL CREATE TABLESQL CREATE TABLE statement is used to create table in a database.If you want to
create a table, you should name the table and define its column and each column's data type.
create table "tablename" ("column1" "data type", "column2" "data type", ... "columnN" "data type");
The data type of the columns may vary from one database to another.
Let us take an example to create a STUDENTS table with ID as primary key and NOT NULL are the constraint
showing that these fields cannot be NULL while creating records in the table.
SQL> CREATE TABLE STUDENTS(ID INT NOT NULL, NAME VARCHAR (20) NOT NULL,
AGE INT NOT NULL,ADDRESS CHAR (25), PRIMARY KEY (ID) );
SQL> DESC STUDENTS;

FIELD TYPE NULL KEY DEFAULT EXTRA

ID Int(11) NO PRI

NAME Varchar(20) NO

AGE Int(11) NO

ADDRESS Varchar(25) YES NULL

SQL DROP TABLE:A SQL DROP TABLE statement is used to delete a table definition and all data from a
table.This is very important to know that once a table is deleted all the information available in the table is lost
forever, so we have to be very careful when using this command.Syntax :DROP TABLE "table_name";

SQL DELETE TABLE :The DELETE statement is used to delete rows from a table. If you want to remove a
specific row from a table you should use WHERE condition.
DELETE FROM table_name [WHERE condition]; But if you do not specify the WHERE condition it will
remove all the rows from the table.
DELETE FROM table_name;
Difference between DELETE and TRUNCATE statements :There is a slight difference b/w delete and truncate
statement. The DELETE statement only deletes the rows from the table based on the condition defined by
WHERE clause or delete all the rows from the table when condition is not specified.The TRUNCATE statement:
it is used to delete all the rows from the table and free the containing space.
TRUNCATE TABLE employee;
SQL RENAME TABLE :In some situations, database administrators and users want to change the name of the
table in the SQL database because they want to give a more relevant name to the table. Any database user can
easily change the name by using the RENAME TABLE and ALTER TABLE statement in Structured Query
Language.The RENAME TABLE and ALTER TABLE syntax help in changing the name of the table.
RENAME old_table _name To new_table_name ;
RENAME Employee To Coding_Employees ;
ALTER TABLE Student RENAME TO MCA_Student_Details ;
Defining constraints
Constraints are the rules that we can apply on the type of data in a table. That is, we can specify the limit on the
type of data that can be stored in a particular column in a table using constraints.
• NOT NULL: This constraint tells that we cannot store a null value in a column. That is, if a column is
specified as NOT NULL then we will not be able to store null in this particular column any more.
• UNIQUE: This constraint when specified with a column, tells that all the values in the column must be
unique. That is, the values in any row of a column must not be repeated.
• PRIMARY KEY: A primary key is a field which can uniquely identify each row in a table. And this
constraint is used to specify a field in a table as primary key.
• FOREIGN KEY: A Foreign key is a field which can uniquely identify each row in a another table. And
this constraint is used to specify a field as Foreign key.
• CHECK: This constraint helps to validate the values of a column to meet a particular condition. That is, it
helps to ensure that the value stored in a column meets a specific condition.
• DEFAULT: This constraint specifies a default value for the column when no value is specified by the user.
CREATE TABLE sample_table
(
column1 data_type(size) constraint_name,
column2 data_type(size) constraint_name,
column3 data_type(size) constraint_name,
....
);
sample_table: Name of the table to be created.
data_type: Type of data that can be stored in the field.
constraint_name: Name of the constraint. for example- NOT NULL, UNIQUE, PRIMARY KEY etc.
1. NOT NULL –
If we specify a field in a table to be NOT NULL. Then the field will never accept null value. That is, you will be
not allowed to insert a new row in the table without specifying any value to this field.
For example, the below query creates a table Student with the fields ID and NAME as NOT NULL. That is, we
are bound to specify values for these two fields every time we wish to insert a new row.

CREATE TABLE Student


(
ID int(6) NOT NULL,
NAME varchar(10) NOT NULL,
ADDRESS varchar(20)
);
2. UNIQUE –
This constraint helps to uniquely identify each row in the table. i.e. for a particular column, all the rows should
have unique values. We can have more than one UNIQUE columns in a table.
For example, the below query creates a table Student where the field ID is specified as UNIQUE. i.e, no two
students can have the same ID. Unique constraint in detail.
CREATE TABLE Student
(
ID int(6) NOT NULL UNIQUE,
NAME varchar(10),
ADDRESS varchar(20)
);

3. PRIMARY KEY –

Primary Key is a field which uniquely identifies each row in the table. If a field in a table as primary key, then
the field will not be able to contain NULL values as well as all the rows should have unique values for this field.
So, in other words we can say that this is combination of NOT NULL and UNIQUE constraints.
A table can have only one field as primary key. Below query will create a table named Student and specifies the
field ID as primary key.

CREATE TABLE Student


(
ID int(6) NOT NULL UNIQUE,
NAME varchar(10),
ADDRESS varchar(20),
PRIMARY KEY(ID)
);
4. FOREIGN KEY –

Foreign Key is a field in a table which uniquely identifies each row of a another table. That is, this field points
to primary key of another table. This usually creates a kind of link between the tables.
Consider the two tables as shown below:

Orders Customers
O_IDORDER_NOC_ID
1 2253 3 C_IDNAME ADDRESS
2 3325 3 1 RAMESH DELHI
3 4521 2 2 SURESH NOIDA
4 8532 1 3 DHARMESHGURGAON

As we can see clearly that the field C_ID in Orders table is the primary key in Customers table, i.e. it uniquely
identifies each row in the Customers table. Therefore, it is a Foreign Key in Orders table.
Syntax:

CREATE TABLE Orders


(
O_ID int NOT NULL,
ORDER_NO int NOT NULL,
C_ID int,
PRIMARY KEY (O_ID),
FOREIGN KEY (C_ID) REFERENCES Customers(C_ID)
)
(i) CHECK –
Using the CHECK constraint we can specify a condition for a field, which should be satisfied at the time of
entering values for this field. For example, the below query creates a table Student and specifies the condition
for the field AGE as (AGE >= 18 ). That is, the user will not be allowed to enter any record in the table with
AGE < 18.

CREATE TABLE Student


(
ID int(6) NOT NULL,
NAME varchar(10) NOT NULL,
AGE int NOT NULL CHECK (AGE >= 18)
);
(ii) DEFAULT –
This constraint is used to provide a default value for the fields. That is, if at the time of entering new records in
the table if the user does not specify any value for these fields then the default value will be assigned to them.
For example, the below query will create a table named Student and specify the default value for the field AGE
as 18.

CREATE TABLE Student


(
ID int(6) NOT NULL,
NAME varchar(10) NOT NULL,
AGE int DEFAULT 18
);

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;


SELECT CustomerName, City FROM Customers;

The 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 DISTINCT Syntax :SELECT DISTINCT column1, column2, ...FROM table_name;

SELECT DISTINCT Country FROM Customers;

The SQL WHERE Clause

The WHERE clause is used to filter records.It is used to extract only those records that fulfill a specified
condition.

WHERE Syntax :SELECT column1, column2, ...FROM table_nameWHERE condition;


SQL Logical Operators

Operator Description

ALL TRUE if all of the subquery values meet the condition

AND TRUE if all the conditions separated by AND is TRUE

ANY TRUE if any of the subquery values meet the condition

BETWEEN TRUE if the operand is within the range of comparisons

EXISTS TRUE if the subquery returns one or more records

IN TRUE if the operand is equal to one of a list of expressions

LIKE TRUE if the operand matches a pattern

NOT Displays a record if the condition(s) is NOT TRUE

OR TRUE if any of the conditions separated by OR is TRUE

SOME TRUE if any of the subquery values meet the condition

Logical operators are used to specify conditions in the structured query language (SQL) statement.
They are also used to serve as conjunctions for multiple conditions in a statement.
ALL − It is used to compare a value with every value in a list or returned by a query. Must be preceded
by =, !=, >, < ,<=, or >= evaluates.
For example,select * from emp where salary>= ALL(1500,4000);
AND − Returns TRUE if both component conditions are TRUE. Returns FALSE if either is FALSE;
otherwise returns UNKNOWN.
example,select * from emp where job=’manager’ AND deptno=20;
OR − Return TRUE if either component condition is TRUE. Return FALSE if both are FALSE.
Otherwise, return UNKNOWN.
For example,select * from emp where job=’manager’ OR deptno=20;
IN − It is equivalent to any test. Equivalent to = ANY, The In operator is used to compare a value to a list
of literal values that have been specified.
For example,select * from emp where ename IN (‘bhanu’,’ward’);
NOT − Returns TRUE if the condition is FALSE. Returns FALSE, if it is TRUE. If it is UNKNOWN, it
remains UNKNOWN.
For example,select * from emp where NOT (job is NULL)
select * from emp where NOT(salary between 2000 AND 5000);
BETWEEN − It is used to define range limits.
For example,If we want to find all employees whose age is in between 40 and 50 the query is as follows

Select * from employee E where E.age between 40 AND 50;


LIKE − It is used to compare values to a list of literal values that are specified. “%” character is used to
match any substring and “_” character is used to match any character. It expresses a pattern by using
the ‘like’ comparison operator.
For example,To display all names whose second letter is ‘b’, use the below mentioned command −
select * from emp where ename LIKE ‘_b%’;
To display a person details whose first letter is ‘A’ and third letter is ‘d’, use the command given below −
Select * from emp where ename LIKE ‘A_d_’;

SQL Functions
SQL functions are similar to SQL operators in that both manipulate data items and both return a result. SQL
functions differ from SQL operators in the format in which they appear with their arguments. The SQL function
format enables functions to operate with zero, one, or more arguments.function(argument1, argument2, ...)

Aggregate functions:
These functions are used to do operations from the values of the column and a single value is returned.
1. AVG()
2. COUNT()
3. FIRST()
4. LAST()
5. MAX()
6. MIN()
7. SUM()
Students-Table

AVG(): It returns average value after calculating from values in a numeric column.
Syntax:SELECT AVG(column_name) FROM table_name;
Queries:Computing average marks of students.
SELECT AVG(MARKS) AS AvgMarks FROM Students;
Output: AvgMarks
80
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;
Queries:Computing total number of students.
SELECT COUNT(*) AS NumStudents FROM Stuents;
Output: NumStudents
5
FIRST(): The FIRST() function returns the first value of the selected column.
Syntax:SELECT FIRST(column_name) FROM table_name;
Queries:Fetching marks of first student from the Students table.
SELECT FIRST(MARKS) AS MarksFirst FROM Students;
Output: MarksFirst
90
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;
Queries:Fetching marks of last student from the Students table.
SELECT LAST(MARKS) AS MarksLast FROM Students;
Output: MarksLast
82
MAX(): The MAX() function returns the maximum value of the selected column.
Syntax:ELECT MAX(column_name) FROM table_name;
Queries:Fetching maximum marks among students from the Students table.
SELECT MAX(MARKS) AS MaxMarks FROM Students;
Output: MaxMarks
95
MIN(): The MIN() function returns the minimum value of the selected column.
Syntax:SELECT MIN(column_name) FROM table_name;
Queries:Fetching minimum marks among students from the Students table.
SELECT MIN(MARKS) AS MinMarks FROM Students;
Output: MinMarks
50
SUM(): The SUM() function returns the sum of all the values of the selected column.
Syntax:SELECT SUM(column_name) FROM table_name;
Queries:Fetching summation of total marks among students from the Students table.
SELECT SUM(MARKS) AS TotalMarks FROM Students;
Output: TotalMarks
400

Various String, Numeric, and Date & Time functions


String Functions :
The string functions of MySQL can manipulate the text string in many ways. Some commonly used string
functions are being discussed below :
.
S.No Function Description Examples

Returns the character 1. SELECT CHAR(70, 65, 67, 69) ;


1. CHAR() for each integer passes 2. SELECT CHAR(65, 67.3, 69.3) ;

Returns concatenated SELECT CONCAT(name, aggregate) AS “Name Marks”


2. CONCAT() string FROM student WHERE age = 14 OR age = 16;

SELECT LOWER(‘GEEKSFORGEEKS’) AS
LOWER() Returns the argument “LowerName1”,LOWER(‘Geeks For Geeks’) AS
3. /LCASE() in lowercase “LowerName2” ;

SUBSTRING(), Returns the substring 1. SELECT SUBSTR(‘ABSDEFG’, 3, 4) “Subs” ;


4. UBSTR() as specified 2. SELECT SUBSTR(‘ABCDEFG’, -5, 4) “Subs” ;

SELECT UPPER(‘Large’) “Uppercase” ;


5. UPPER()/UCASE() Converts to uppercase or SELECT UCASE(‘Large’) “Uppercase”;
Removes leading and trailing
6. TRIM() spaces SELECT TRIM(‘Bar One’) ;

Returns the length of a string SELECT LENGTH(‘CANDIDE’) “Length in


7. LENGTH() in bytes characters” ;

Numeric Functions :

The number functions are those functions that accept numeric values and after performing the required
operations, return numeric values. Some useful numeric functions are being discussed below :

S.No.Function Description Example

Returns the remainder of one expression by


1. MOD() diving y another expression. SELECT MOD(11, 4) “Modulus” ;

Returns the value of one expression raised to


2. POWER()/POW() the power of another expression SELECT POWER(3, 2) “Raised” ;

Returns numeric expression rounded to an


integer. Can be used to round an expression to SELECT ROUND(15.193, 1)
3. ROUND() a number of decimal points. “Round” ;

4. SIGN() This function returns sign of a given number. SELECT SIGN(-15) “Sign” ;

Returns the non-negative square root of SELECT SQRT(26) “Square root”


5. SQRT() numeric expression. ;

Returns numeric exp1 truncate to exp2


decimal places. If exp2 is 0, then the result TRUNCATE(15.79, 1) “Truncate”
6. TRUNCATE() will have no decimal point ;
Date and Time Functions : Date functions operate on values of the DATE datatype.
S.No.Function Description Example

CURDATE()/
CURRENT_DATE()/
1 CURRENT_DATE Returns the current date. SELECT CURDATE() ;

Extracts the date part of a


date or date-time
2 DATE() expression. SELECT DATE(‘2020-12-31 01:02:03’) ;

Returns the month from


3 MONTH() the date passed. SELECT MONTH(‘2020-12-31’) ;

4 YEAR() Returns the year SELECT YEAR(‘2020-12-31’) ;

Returns the time at which


5 NOW() the function executes. SELECT NOW() ;

SELECT NOW(), SLEEP(2), NOW() ;


Returns the current date or SELECT SYSDATE(), SLEEP(2), SYSDATE()
6 SYSDATE() and time. ;

SQL Set Operation

The SQL Set operation is used to combine the two or more SQL SELECT statements.
Types of Set Operation
1. Union
2. UnionAll
3. Intersect
4. Minus

UNION Operation :

UNION is used to combine the results of two or more SELECT statements. However it will eliminate duplicate
rows from its resultset. In case of union, number of columns and datatype must be same in both the tables, on
which UNION operation is being applied.

The First table, The Second table, Result : ID NAME


ID Name ID Name 1 abhi
1 abhi 2 adam 2 adam
2 adam 3 Chester 3 Chester

SELECT * FROM First UNIONSELECT * FROM Second;


UNION ALL :This operation is similar to Union. But it also shows the duplicate rows.
SELECT * FROM First UNION ALLSELECT * FROM Second;

ID NAME
1 abhi
2 adam
2 adam
3 Chester

INTERSECT :Intersect operation is used to combine two SELECT statements, but it only retuns the records
which are common from both SELECT statements. In case of Intersect the number of columns and datatype
must be same.
SELECT * FROM First INTERSECTSELECT * FROM Second;

ID NAME
2 adam

MINUS :The Minus operation combines results of two SELECT statements and return only those in the final
result, which belongs to the first set of the result.

Subquery
A Subquery or Inner query or a Nested query is a query within another SQL query and embedded within the
WHERE clause.A subquery is used to return data that will be used in the main query as a condition to further
restrict the data to be retrieved.Subqueries can be used with the SELECT, INSERT, UPDATE, and DELETE
statements along with the operators like =, <, >, >=, <=, IN, BETWEEN, etc.

• A subquery is usually added within the WHERE Clause of another SQL SELECT statement.
• You can use the comparison operators, such as >, <, or =. The comparison operator can also be a multiple-
row operator, such as IN, ANY, or ALL.
• 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.
• The inner query executes first before its parent query so that the results of an inner query can be passed to
the outer query.
You can use a subquery in a SELECT, INSERT, DELETE, or UPDATE statement to perform the following tasks:

• Compare an expression to the result of the query.


• Determine if an expression is included in the results of the query.
• Check whether the query selects any rows.
• The subquery (inner query) executes once before the main query (outer query) executes.
• The main query (outer query) use the subquery result.
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');

SQL Correlated Subqueries


Correlated subqueries are used for row-by-row processing. Each subquery is executed once for every row of the
outer query.

A correlated subquery is evaluated once for each row processed by the parent statement. The parent statement
can be a SELECT, UPDATE, or DELETE statement.

SELECT column1, column2, ....FROM table1 outer WHERE column1 operator (SELECT column1, column2
FROM table2 WHERE expr1 = outer.expr2);

A correlated subquery is one way of reading every row in a table and comparing values in each row against
related data. It is used whenever a subquery must return a different result or set of results for each candidate row
considered by the main query. In other words, you can use a correlated subquery to answer a multipart question
whose answer depends on the value in each row processed by the parent statement.
Nested Subqueries Versus Correlated Subqueries :
With a normal nested subquery, the inner SELECT query runs first and executes once, returning values to be
used by the main query. A correlated subquery, however, executes once for each candidate row considered by
the outer query. In other words, the inner query is driven by the outer query.
SQL group by

In SQL, The Group By statement is used for organizing similar data into groups. The data is further organized
with the help of equivalent function. It means, if different rows in a precise column have the same values, it will
arrange those rows in a group.

o The SELECT statement is used with the GROUP BY clause in the SQL query.
o WHERE clause is placed before the GROUP BY clause in SQL.
o ORDER BY clause is placed after the GROUP BY clause in SQL.

Syntax:
SELECT column1, function_name(column2) FROM table_name WHERE condition
GROUP BY column1, column2 ORDER BY column1, column2;
function_name: Table name.
Condition: which we used.

Group By single column: Group By single column is used to place all the rows with the same value. These
values are of that specified column in one group. It signifies that all rows will put an equal amount through a
single column, which is of one appropriate column in one group.

Consider the below query:


SELECT NAME, SUM (SALARY) FROM Employee GROUP BY NAME;
o Groups based on several columns: A group of some columns are GROUP BY column 1, column2, etc.
Here, we are placing all rows in a group with the similar values of both column 1 and column 2.

Consider the below query: SELECT SUBJECT, YEAR, Count (*) FROM Student

Group BY SUBJECT, YEAR;

HAVING Clause

WHERE clause is used for deciding purpose. It is used to place conditions on the columns to determine the part of
the last result-set of the group. Here, we are not required to use the combined functions like COUNT (), SUM
(), etc. with the WHERE clause. After that, we need to use a HAVING clause.

Having clause Syntax:


SELECT column1, function_name(column2) FROM table_name WHERE condition GROUP BY column1,
column2 HAVING condition ORDER BY column1, column2;

function_name: Mainly used for name of the function, SUM(), AVG().


table_name: Used for name of the table.
condition: Condition used.

Example:
SELECT NAME, SUM(SALARY) FROM Employee GROUP BY NAME HAVING SUM(SALARY)>23000;

The GROUP BY Clause is used to group the rows, which have the same values.The SELECT statement
in SQL is used with the GROUP BY clause.In the Group BY clause, the SELECT statement can
use constants, aggregate functions, expressions, and column names.The GROUP BY Clause is called when the
HAVING clause is used to reduce the results.

SQL ORDER BY Clause


o Whenever we want to sort the records based on the columns stored in the tables of the SQL database, then
we consider using the ORDER BY clause in SQL.
o The ORDER BY clause in SQL will help us to sort the records based on the specific column of a table.
This means that all the values stored in the column on which we are applying ORDER BY clause will be
sorted, and the corresponding column values will be displayed in the sequence in which we have obtained
the values in the earlier step.
o Using the ORDER BY clause, we can sort the records in ascending or descending order as per our
requirement. The records will be sorted in ascending order whenever the ASC keyword is used with
ORDER by clause. DESC keyword will sort the records in descending order.
o If no keyword is specified after the column based on which we have to sort the records, in that case, the
sorting will be done by default in the ascending order.

Before writing the queries for sorting the records, let us understand the syntax.

Syntax to sort the records in ascending order:


SELECT ColumnName1,...,ColumnNameN FROM TableName ORDER BY ColumnName ASC;

Syntax to sort the records in descending order:


SELECT ColumnName1,...,ColumnNameN FROM TableName ORDER BY ColumnName DESC;

mysql> SELECT *FROM customers ORDER BY Name ASC;


SQL JOIN

As the name shows, JOIN means to combine something. In case of SQL, JOIN means "to combine two or more
tables".The SQL JOIN clause takes records from two or more tables in a database and combines it together.

ANSI standard SQL defines five types of JOIN :

1. inner join,
2. left outer join,
3. right outer join,
4. full outer join, and
5. cross join.

In the process of joining, rows of both tables are combined in a single table.
Why SQL JOIN is used?

If you want to access more than one table through a select statement.

If you want to combine two or more table then SQL JOIN statement is used .it combines rows of that tables in one
table and one can retrieve the information by a SELECT statement.

The joining of two or more tables is based on common field between them.

SQL INNER JOIN also known as simple join is the most common type of join.

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

SQL INNER JOIN Keyword The INNER JOIN keyword selects records that have matching values in both
tables.

SELECT column_name(s) FROM table1INNER JOIN table2ON table1.column_name = table2.column_name;

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 table1LEFT JOIN table2ON table1.column_name = table2.column_name;


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.
RIGHT JOIN Syntax
SELECT column_name(s)FROM table1RIGHT JOIN table2ON table1.column_name = table2.column_name;
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.

Tip: FULL OUTER JOIN and FULL JOIN are the same.

FULL OUTER JOIN Syntax


SELECT column_name(s)FROM table1FULL OUTER JOIN table2
ON table1.column_name = table2.column_name WHERE condition;
SQL Self Join A self join is a regular join, but the table is joined with itself.
Self Join Syntax

SELECT column_name(s)FROM table1 T1, table1 T2WHERE condition;

T1 and T2 are different table aliases for the same table.

SQL ANY and ALL Operators

The ANY and ALL operators allow you to perform a comparison between a single column value and a range of
other values.

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.

ANY Syntax

SELECT column_name(s)FROM table_nameWHERE column_name operator ANY (SELECT column_name


FROM table_name WHERE condition);

Note: The operator must be a standard comparison operator (=, <>, !=, >, >=, <, or <=).

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.
ALL Syntax With SELECT
SELECT ALL column_name(s)FROM table_name WHERE condition;

ALL Syntax With WHERE or HAVING


SELECT column_name(s)FROM table_nameWHERE column_name operator ALL (SELECT column_name
FROM table_name WHERE condition);

Note: The operator must be a standard comparison operator (=, <>, !=, >, >=, <, or <=).

Exists

The EXISTS operator in MySQL is a type of Boolean operator which returns the true or false result. It is used in
combination with a subquery and checks the existence of data in a subquery. It means if a subquery returns any
record, this operator returns true. Otherwise, it will return false. The true value is always represented numeric
value 1, and the false value represents 0. We can use it with SELECT, UPDATE, DELETE, INSERT statement.

Syntax
SELECT col_names FROM tab_name WHERE [NOT] EXISTS (SELECT col_names FROM tab_name
WHERE condition);

The NOT operator is used to negates the EXISTS operator. It returns true when the subquery does not return any
row. Otherwise, it returns false.

Generally, the EXISTS query begins with SELECT *, but it can start with the SELECT column, SELECT
a_constant, or anything in the subquery.

SQL Views
Views in SQL are kind of virtual tables. A view also has rows and columns as they are in a real table in the
database. We can create a view by selecting fields from one or more tables present in the database. A View can
either have all the rows of a table or specific rows based on certain condition.

Creating Views
Database views are created using the CREATE VIEW statement. Views can be created from a single table,
multiple tables or another view.
CREATE VIEW Syntax CREATE VIEW view_name AS SELECT column1, column2, ...FROM table_name
WHERE condition;

CREATE VIEW [Brazil Customers] AS


SELECT CustomerName,ContactName FROM CustomersWHERE Country = 'Brazil';

CREATE VIEW [Products Above Average Price] AS


SELECT ProductName, Price FROM Products WHERE Price > (SELECT AVG(Price) FROM Products);

UPDATING VIEWS
There are certain conditions needed to be satisfied to update a view. If any one of these conditions is not met,
then we will not be allowed to update the view.
1. The SELECT statement which is used to create the view should not include GROUP BY clause or ORDER
BY clause.
2. The SELECT statement should not have the DISTINCT keyword.
3. The View should have all NOT NULL values.
4. The view should not be created using nested queries or complex queries.
5. The view should be created from a single table. If the view is created using multiple tables then we will not be
allowed to update the view.
We can use the CREATE OR REPLACE VIEW statement to add or remove fields from a view.
Syntax:
REATE OR REPLACE VIEW view_name AS SELECT column1,coulmn2,..FROM table_name
WHERE condition;

For example, if we want to update the view MarksView and add the field AGE to this View
from StudentMarks Table, we can do this as:

CREATE OR REPLACE VIEW MarksView AS SELECT


StudentDetails.NAME,StudentDetails.ADDRESS, StudentMarks.MARKS, StudentMarks.AGE
FROM StudentDetails, StudentMarks WHERE StudentDetails.NAME = StudentMarks.NAME;
SQL Dropping a View

A view is deleted with the DROP VIEW statement.

SQL DROP VIEW Syntax


DROP VIEW view_name;

The following SQL drops the "Brazil Customers" view:

DROP VIEW [Brazil Customers];

*******************************************

You might also like

pFad - Phonifier reborn

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

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


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy