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

Ch-7 MYSQL

The document provides an overview of MySQL, a free open-source Relational Database Management System (RDBMS) that utilizes Structured Query Language (SQL) for managing data stored in tables. It discusses various data models, advantages of Database Management Systems (DBMS), SQL commands categorized into DDL, DML, TCL, and DCL, and explains key concepts such as primary keys, foreign keys, and referential integrity. Additionally, it outlines MySQL features, data types, and commands for creating, accessing, modifying, and deleting databases and tables.

Uploaded by

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

Ch-7 MYSQL

The document provides an overview of MySQL, a free open-source Relational Database Management System (RDBMS) that utilizes Structured Query Language (SQL) for managing data stored in tables. It discusses various data models, advantages of Database Management Systems (DBMS), SQL commands categorized into DDL, DML, TCL, and DCL, and explains key concepts such as primary keys, foreign keys, and referential integrity. Additionally, it outlines MySQL features, data types, and commands for creating, accessing, modifying, and deleting databases and tables.

Uploaded by

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

Ch- 7 Database Management System

MYSQL
It is freely available open source Relational Database Management System (RDBMS) that uses Structured Query
Language(SQL). In MySQL database , information is stored in Tables. A single MySQL database can contain many
tables at once and store thousands of individual records.

SQL (Structured Query Language)


SQL is a language that enables you to create and operate on relational databases, which are sets of related
information stored in tables.
Advantages of DBMS:
 Control of data redundancy
 Data consistency
 Sharing of data
 Data Integrity
 Privacy and Security
DATA MODELS:
Data models describe the structure of the database. There are four data models in DBMS:
1. Relational Data Model
2. Hierarchical Data Model
3. Network Model
4. Object Oriented Data Model
1. Relational Data Model: This database consists of a collection of table. These tables are called relations. A row in a
table represents a relationship among a set of values.
 Relation: A relation is a table with columns and rows.
 Tuple: A row of a relation OR a row of a table.
 Domain: A set of values for the columns.
 Attribute: Column name of a relation.
 Degree: Number of attributes in a table.
 Cardinality: Number of tuples OR Number of rows in a table.

2. Hierarchical Data Model: In this model the data are represented by collection and relationship between data are
represented by links. In this model the collection of data are organized as tree.
3. Network Data Model: This is same as the hierarchical model but in this model the collection of data is organized
as arbitrary graphs.
4. Object Oriented Data Model: In this model the data and its operations are represented by objects.

NOTE: Some Definitions:-


Record: Collection of attributes
File: Collection of records
KEYS- A key allows us to identify a set of attributes that distinguish entities from each other.
There are four keys:
1. Primary Key

2. Candidate Key
3. Alternate Key
4. Foreign Key
1. Primary Key: A primary key is a set of one or more attributes that can uniquely identify tuples within the relation.
This key does not have duplicate values in the relation. There must be any value for this key, it cannot be NULL.
2. Candidate Key: All attributes combination inside a relation that can serve as a primary key, is called candidate key.

3. Alternate Key: A candidate key that is not the primary key is called an alternate key.

4. Foreign Key: A non-key attribute whose values are derived from the primary key of some other table, is known as
foreign key in its current table.

REFERENTIAL INTEGRITY - A referential integrity is a system of rules that a DBMS uses to ensure that relationships
between records in related tables are valid, and that users don’t accidentally delete or change related data. This
integrity is ensured by foreign key.

INTRODUCTION TO MySQL-

 MySQL stands for My Structured Query Language.


 MySQL is freely available, open source Relational Database Management System (RDBMS).
Features of MySQL-
 Cost: Freely available
 Performance: MySQL is fast.
 Simplicity: MySQL is easy to install.
 High Performance
 Data Security: In has powerful mechanism for ensuring only authorized users have
 Access the data.
SQL-
 SQL stands for Structured Query Language.
 This is non-procedural Language.
 This is the common language for relational database. Means this language is used in MySQL.
Difference between SQL and MySQL
SQL MySQL
This is the language that used in database. This is the open source database.
This language is used in MySQL to write the This is the database. It uses the SQL to write the
commands in queries. queries.

 CLASSIFICATION OF SQL STATEMENTS


SQL commands can be mainly divided into following categories:
1. Data Definition Language (DDL) These commands are used to define and modify the structure of a database.
 Create :- This statement is used to create database or tables.
 Alter :- This statement is used to modify structure of table.
 Drop :- This statement is used to delete database objects.
 Rename.
2. Data Manipulation Language (DML) These Commands that allow you to perform data manipulation e.g.
 SELECT :- This statement is used to retrieves information from the database.
 INSERT :- This statement is used to insert new record into the database.
 DELETE :- This statement is used for deletion of information in the database.
 UPDATE :- This statement is used for modification of information in the database

3. Transaction Control Language (TCL) Commands that allow you to manage and control the transactions e.g.,
 Creating save points
 Rollback
 Commit
4. Data control Language (DCL)- This language is used to control data and access to the databases. It is used for
protecting the data from unauthorized access.
 GRANT
 REVOKE

MySQL ELEMENTS
1. Literals 2. Data types 3. Nulls 4. Comments
1. LITERALS
It refer to a fixed data value. This fixed data value may be of character type or numeric type. For example,
‘replay’ , ‘Raj’, ‘8’ , ‘306’ are all character literals.
Numbers not enclosed in quotation marks are numeric literals. E.g. 22 , 18 , 1997 are all numeric literals.
Numeric literals can either be integer literals i.e., without any decimal or be real literals i.e. with a decimal
point
e.g. 17 is an integer literal but 17.0 and 17.5 are real literals.
2. DATA TYPES
Data types are means to identify the type of data and associated operations for handling it. MySQL data
types are divided into three categories:
 Numeric
 Date and time
 String types
Numeric Data Type
 int – used for number without decimal.
 Decimal(m,d) – used for floating/real numbers. m denotes the total length of number and d is number
of decimal digits.
 Float- Holds Number with decimal points. Each float value occupies 4 bytes.
Date and Time Data Type
 date – used to store date in YYYY-MM-DD format.
 time – used to store time in HH:MM:SS format.
String Data Types
 char(n) – used to store a fixed length string. n denotes max. number of characters.
 varchar(n) – used to store a variable length string. n denotes max. no. of characters.

Char Data type Varchar Data type


It specifies a fixed length character string. It specifies a variable length character string.
When a column is given data type as CHAR(n), then When a column is given data type as VARCHAR(n),
MySQL ensures that all values stored in that column then the maximum size a value in this column can
have this length i.e. n bytes. If a value is shorter than have is n bytes. Each value that is stored in this
this length n then blanks are added, but the size of column store exactly as you specify it i.e. no blanks
value remains n bytes. are added if the length is shorter than maximum
length n.

Binary Data Type: Stores the data in binary objects, such as graphics, images, multimedia etc.

3. NULL values: If a column in a row has no value, then column is said to be null. NULLs can appear in a column if the
column is not restricted by NOT NULL or Primary Key. You should use a null value when the actual value is not
known. Null and Zero is not equivalent. Any arithmetic expression containing a null always evaluates to null.
Example: 7 + null = null
7+0=7 Difference between null and zero.
4. Comments: Comment is a text that is not executed. There are two types of comments that we use in MySQL.
(i) Single line Comment: Beginning with two hyphens (--) OR beginning with # symbol.
(ii) Multi Line Comment: /*……………………………………….. …………………………………….*/

DATABASE COMMNADS
VIEW EXISTING DATABASE
To view existing database names, the command is- SHOW DATABASES ;

Data Definition Language (DDL) Commands-


1. CREATING DATABASE IN MYSQL
For creating the database in MySQL, we write the following command :
CREATE DATABASE <databasename> ;
e.g. In order to create a database Student, command is :
 CREATE DATABASE Student ;
2. ACCESSING DATABASE
For accessing already existing database we write :
USE <databasename> ;
e.g. to access a database named Student , we write command as :
 USE Student ;
3. DELETING DATABASE
For deleting any existing database , the command is :
DROP DATABASE <databasename> ;
e.g. to delete a database , say student, we write command as-
 DROP DATABASE Student ;
4. VIEWING TABLE IN DATABASE
In order to view tables present in currently accessed database command is-
 SHOW TABLES ;
5. CREATING TABLES IN MYSQL: Tables are created using CTREATE TABLE command. A table has rows and columns.
The column name must be specified along the data type. Each table must have at least one column.
 CREATE TABLE Student(RollNo int(6) not null , Name varchar(30) not null, Gender char(1), Marks integer
(10), DOB Date);

6. VIEWING STRUCTURE OF A TABLE - If we want to know the structure of a table, we can use DESCRIBE or DESC
command, as per following syntax : DESCRIBE | DESC ; to view the structure of table EMPLOYEE,
command is : DESCRIBE EMPLOYEE ; OR DESC EMPLOYEE ;

7- Alter Table command- The alter table command is used to perform the following operation.
 To add column to an existing table.
 To add a column specific position.
 To rename any existing column.
 To change the data type of any column or to modify its size.
 To remove or physically delete a column.

a) Add Column To An Existing Table. add a column to a table, ALTER TABLE command can be used as per following
syntax: ALTER TABLE ADD ; e.g. to add a new column Mob_no to the Student table, we can write command as :

 ALTER TABLE Student ADD Mob_no integer(50);


A new column by the name ADDRESS will be added to the table, where each row will contain NULL value for the new
column.
Rollno Name Gender Marks DOB Mob_no
1 Raj kumar M 50 2012-06-11 NULL
2 Deep singh M 56 2001-08-12 NULL

b) Add a Column with default value- We can add the column with default value

 Alter table Student add City varchar(15) default ‘Hathras’;

Rollno Name Gender Marks DOB Mob_no City


1 Raj kumar M 50 2012-06-11 NULL Delhi
2 Deep singh M 56 2001-08-12 NULL Delhi

c) Modifying an existing column definition- To change the data-type and size of the any column, we use the
MODIFY command.
 Alter table Student Modify City varchar(25) ;
The above command will modify the data type size for the City field form 15 to 25 characters.
d) Renaming a column- The existing column in a relation can be renamed using Alter table command.
Alter table Student <old column name > <new column name > column definition;

 Alter table Student change city to State varchar(20);


Rollno Name Gender Marks DOB Mob_no State
1 Raj kumar M 50 2012-06-11 NULL Delhi
2 Deep singh M 56 2001-08-12 NULL Delhi

e) Removing a column- To remove or drop a column in a table, Alter table command is used.
 Alter table Student Drop State ;
Above command will drop state column from the Student table.
Rollno Name Gender Marks DOB Mob_no
1 Raj kumar M 50 2012-06-11 NULL
2 Deep singh M 56 2001-08-12 NULL

f) Adding and deleting Primary key constraints- by Alter table command add a primary key constraint on the
column Rollno in the table Student.
 Alter table Student Add Primary Key Rollno ;
Note- make sure while using alter table command to add a primary key that the primary key column must be
declared with NOT NULL.
Delete Primary key constraints-
 Alter table Student Drop Primary Key ;

FOREIGN KEY CONSTRAINT-


- Foreign key is a non-key column of a table (child table) that draws its values from primary key of another
Table (parent table).
- The table in which a foreign key is defined is called a referencing table or child table. A table to which a
foreign key points is called referenced table or parent table.
 CREATE TABLE SCORE ( ROLL_NO integer , MARKS integer , FOREIGN KEY(ROLL_NO)
REFERNCES STUDENT(ROLL_NO) ) ;
To remove foreign key constraint:-
 ALTER TABLE table1 DROP FOREIGN KEY fkey_column;

Add column by Position-


Last (default)- We can add a column Mob_no in Student table by default last position (see the above command a)
First-
 ALTER TABLE Student ADD LastName varchar(50) First ;

LastNam Rollno Name Gender Marks DOB Mob_no


e
NULL 1 Raj kumar M 50 2012-06-11 NULL
NULL 2 Deep singh M 56 2001-08-12 NULL

After -
 ALTER TABLE Student ADD LastName varchar(50) After Name ;
Rollno Name LastName Gender Marks DOB Mob_no
1 Raj kumar NULL M 50 2012-06-11 NULL
2 Deep singh NULL M 56 2001-08-12 NULL

8. DROP TABLE COMMAND- Drop table command is used to remove/delete a table permanently. If you drop a table
all the rows in the table are deleted along with its structure. Once a table is dropped we cannot get it back and all
other references to the table become invalid. This command completely destroys the table structure.
 Drop table Student;
DML COMMANDS- Data Manipulation using a database means either insertion of new data, removal of existing data
or modification of existing data in the database.
1. Inserting Data into a table- The Insert into command is used to insert a new record/row/tuple in a table. Insert
into statement in the following different forms-
a) Inserting data ( for all the ) into a table- in the first method, while inserting a row if we are adding value for all the
column of the table we need not specify the column(s) name in the SQL query. But we need to make sure that the
same order of the values is in the same order as the columns represented in the structure of the table.
-> the argument/ value of character or text and date data type are always enclosed in double or single quotation
marks.
-> NULL values are stored and displayed as NULL only without any quotes.
 Insert into Student Values(3, ‘mohit kumar’, ‘M’, 42, ‘2000-01-12’, 9658535);
b) Inserting data by specifying all the columns and associated values into a table- the second form specifies both
the column names and the values to be inserted.
 Insert into Student(Rollno,Name,Gender,Marks,DOB,Mob_no) Values(4, ‘Priyanshi’, ‘F’, 24, ‘2005-01-10’,
975859);
c) Inserting data into specific columns of a table- This command insert a record into the student table for the
columns Rollno, Name, Marks Only.
 Insert into Student(Rollno,Name,Marks) Values(5, ‘Riya sharma’, 50);
Note-Remaining of columns shall hold the values as NULL.
d) Inserting NULL values into a table-If a column in a row has no value or missing value then the column is said to be
null or holding NULL value. Null value can be given to any column other than being assigned as primary key or
Not Null constraint. It can be done by typing NULL without quotes.
 Insert into Student(Rollno,Name,Gender,Marks,DOB,Mob_no) Values(4, ‘Priyanshi’, ‘F’, 24, NULL, NULL);
2. Modifying Data in a table- To modify data in a table or to make changes for some or all of the values in the
existing records in a table, we use the UPDATE statement. The update command specifies the rows to be
modified using the WHERE clause and the new data is written into the respective record using the SET keyword.
a) Updating single column- The below statement shall change the value of Marks field to 85 for the Student whose
Rollno is 1.
 Update Student Set Marks=85 Where Rollno=1;
b) Updating multiple columns- Modifying the values in more than one column can be done by separating the
columns along with the new values using SET clause, separated by commas.
 Update Student Set Marks=95 , DOB= ‘2000-05-02’ Where Rollno=2;
d) Updating to NULL values- the values for the attributes in a relation can be entered as NULL using UPDATE
command.
 Update Student Set LastName= ‘Sharma’, Where Rollno=2;
 Update Student Set Marks=NULL Where Rollno=1;
e) Updating using an expression or formula- we can update the value with an expression.
 Update Student Set Marks=Marks+8 Where Rollno=2 or Rollno 4 ;
The above statement shall increment the value of marks by 8 for all the records with Rollno 2 or 4.
f) Updating all rows using an expression or formula-
 Update Student Set Marks=Marks+15 ;
The above statement shall increase the value of marks of all the students by 15.
3. Delete (Removing) data from a table- The DELETE statement is used to delete row from table.
 Delete form Student Where Rollno=4
The above statement shall delete the record only for roll number 4.
Note- the Where clause in the SQL delete command is optional and is identifies the rows in the column that
get deleted. If you do not include the where clause, all the roes in the table are deleted.
Deleting all the rows from the table- to delete all the rows from the student table the delete statement will
be-
 Delete from Student;
SQL TRUNCATE statement- The SQL Truncate command is used to delete all the rows from the table and
free the space containing the table.
 Truncate table Student;
Difference between DELETE and TRUNCATE Statement –
Delete Statement- This command deletes only the rows from the table based on the condition given the
where clause or deletes all the row form the tables if no condition is specified. But it does not free the space
containing the table.
TRUNCATE Statement – The SQL Truncate command is used to delete all the rows from the table and free
the space containing the table.
SQL SELECT Statement- This command can perform selection as well as projection. It is the most extensively used sql
command. The select statement can be used to retrieve a subset of rows or columns form one or more tables
present in a database.
1. Projection- This capability of SQL returns all rows from a relation with selective attributes.
 Select Name, Gender from Student;
Name Gender
Raj kumar M
Deep singh M
The above command displays only Name and Gender attributes from the student table.
To display all columns along with the respective rows we use the command-
 Select * from Student;
Note- the asterisk (*) means displaying all the columns from a relation.
2. Selection- Selecting Specific Rows- (Where Clause)-this capability of SQL returns some of the rows and all the
columns in the relation. Use of WHERE clause is required when specific tuples are to be fetched or manipulated. To
select all the columns from a table, the asterisk(*) can be used.
 Select * form Student Where Gender =’M’ ;
Rollno Name Gender Marks DOB Mob_no
1 Raj kumar M 50 2012-06-11 NULL
2 Deep singh M 56 2001-08-12 NULL
 Select * form Student Where Rollno<=5;
The above command shall display only those records whose Rollno is less than or equal to 5

Rollno Name Gender Marks DOB Mob_no


1 Raj kumar M 50 2012-06-11 NULL
2 Deep singh M 56 2001-08-12 NULL
3 Payal F 51 1999-02-03 NULL
4 Ankit kumar M 36 2004-12-03 NULL
5 Gauri F 40 2001-03-25 NULL

3- Reordering Columns with Select Query-


 Select Name, Marks, DOB, Gender from Student;
Name Marks DOB Gender
Raj kumar 50 2012-06-11 M
Deep singh 56 2001-08-12 M
Payal 51 1999-02-03 F
Ankit 36 2004-12-03 M
Gauri 40 2001-03-25 F

4- Eliminating Duplicating/ Redundant Data –Distinct Clause – Distinct clause is used to remove duplicate row from
the results of a Select statement. It is used to retrieve only unique values for a column in the table.
 Select Gender from Student; Select Distinct Gender from Student;
Gender Gender
M M
M F
F
M
F

Relational Operator- Equal to, Grater than, Less than, Greater than or equal to, Less than or equal to, Not equal to
 Select * from Student where Marks >=50;
Rollno Name Gender Marks DOB Mob_no
1 Raj kumar M 50 2012-06-11 NULL
2 Deep singh M 56 2001-08-12 NULL
3 Payal F 51 1999-02-03 NULL

Not Equal (!=)-This command shall display the records of all the students who are not get 50 marks.
 Select * from Student where Marks !=50;
Rollno Name Gender Marks DOB Mob_no
2 Deep singh M 56 2001-08-12 NULL
3 Payal F 51 1999-02-03 NULL
4 Ankit M 36 2004-12-03 NULL
5 Gauri F 40 2001-03-25 NULL
Logical Operators- The three logical operator in sql are-AND, OR and NOT operator. Out of these AND and OR
operator are termed as conjunctive operators since these two operators combine two or more conditions.
1- AND Operator- The AND operator displays a record and returns a true value if all the conditions (usually two
conditions) specified in the where clause are true.
 Select * from Student where Marks>= 50 AND Gender =’M’;
Rollno Name Gender Marks DOB Mob_no
1 Raj kumar M 50 2012-06-11 NULL
2 Deep singh M 56 2001-08-12 NULL

2 – OR Operator- The OR operator displays a record and returns a true value if either of the conditions (two
conditions) specified in the where clause is true.
 Select Rollno, Name, Gender ,Marks from Student where Marks>=36 OR Gender= ‘M’;

Rollno Name Gender Marks


1 Raj kumar M 50
2 Deep singh M 56
4 Ankit M 36

3-Not Operator- Not operator is also termed as a negation operator. Unlike the other two operators, This operator
takes only one condition and gives the reverse of it as the result. It returns a false value if the condition holds true
and vice versa.
 Select Name, Marks from Student where NOT Gender= ‘F’;
Name Marks
Raj kumar 50
Deep singh 56
Ankit 36

SPECIAL OPERATOR-

BETWEEN and AND Operator - The BETWEEN operator defines a range of values that the column values must fall in
to make the condition true. The range includes both lower value and upper value.
 SELECT Name , Gender ,DOB, Marks from Student WHERE Marks BETWEEN 45 AND 55;
Name Gender DOB Marks
Raj kumar M 2012-06-11 50
Payal F 1999-02-03 51

NOT BETWEEN- The not between operator works opposite to the between operator it retrieves the rows which do
not satisfy the between condition.
 SELECT Name , Gender ,DOB, Marks from Student WHERE Marks NOT BETWEEN 45 AND 55;
Name Gender DOB Marks
Deep singh M 2001-08-12 56
Ankit M 2004-12-03 36
Gauri F 2001-03-25 37
IN operator - To specify a list of values, IN operator is used. The IN operator selects value that match any value in a
given list of values. E.g.
 SELECT * FROM Student WHERE DOB IN (‘2001-08-12’ , ‘2001-03-25’);
Rollno Name Gender Marks DOB Mob_no
2 Deep singh M 56 2001-08-12 NULL
5 Gauri F 58 2001-03-25 NULL

NOT IN – The NOT IN operator work opposite to IN operator. It returns the rows that do not match the list.
 SELECT * FROM Student WHERE DOB NOT IN (‘2001-08-12’ , ‘2001-03-25’);
Rollno Name Gender Marks DOB Mob_no
1 Raj kumar M 50 2012-06-11 NULL
3 Payal F 51 1999-02-03 NULL
4 Ankit M 36 2004-12-03 NULL

Condition Based On Pattern Matches – LIKE - The LIKE operator is used to search for a specified pattern in a
column. This operator is used with the columns of type CHAR and VARCHAR. (Matches the string specified pattern)

Condition Based On Pattern Matches – WILD CARD CHARACTERS- The SQL like condition allows you to use wild card
to perform pattern matching sql provides two wild card characters that are used while comparing the strings with
LIKE operator.

1- Percent (%) Matches any string

2- Underscore ( _) matches any one character

Ex- 1

 Select * from Student Where Name Like “R%”;

Rollno Name Gender Marks DOB Mob_no


1 Raj kumar M 50 2012-06-11 NULL
The above command shall display those records where the name begins with character ‘R’

Ex- 2

 Select * from Student Where Name Like “%r”;

Rollno Name Gender Marks DOB Mob_no


1 Raj kumar M 50 2012-06-11 NULL
4 Ankit kumar M 36 2004-12-03 NULL
The above command shall display the records for those Students whose Name ends with the letter ‘r’ .

Ex- 3

 Select * from Student Where Name Like “%a%”;

Rollno Name Gender Marks DOB Mob_no


1 Raj kumar M 50 2012-06-11 NULL
3 Payal F 51 1999-02-03 NULL
4 Ankit kumar M 36 2004-12-03 NULL
5 Gauri F 40 2001-03-25 NULL
The above command displays the records of all the Students whose Name contains the character ‘a’ anywhere in it.

Ex- 4
 Select * from Student Where Name Like “_a%”;

Rollno Name Gender Marks DOB Mob_no


1 Raj kumar M 50 2012-06-11 NULL
3 Payal F 51 1999-02-03 NULL
5 Gauri F 40 2001-03-25 NULL
The above command shall display the Rollno, Name, Gender, Marks, DOB, Mob_no of all the Students whose Name
contains the letter ‘a’ at the second place.

NOT LIKE- The not like operator works opposite to like operator. It returns the rows that do not match the specified
pattern.

Ex- 1

 Select * from Student Where Name Not Like “%u_ _”;

Rollno Name Gender Marks DOB Mob_no


5 Gauri F 40 2001-03-25 NULL
The above command shall display the Rollno, Name, Gender, Marks, DOB, Mob_no of all the Students whose Name
dose not contains the letter ‘u’ from the third last position.

SEARCHING FOR NULL - The NULL value in a column can be searched for in a table using IS NULL in the WHERE
clause. E.g. to list Students details whose Mob_no contain NULL, we use the command:

 Select Name, Gender, Marks, Mob_no From Students Where Mob_no Is Null ;

Name Gender Marks Mob_no


Raj kumar M 50 NULL
Payal F 51 NULL
Ankit kumar M 36 NULL
Gauri F 40 NULL

Column Aliases- Column alias are used to make column headings in the query result set easier to read.

 Select Name As “Student_name”, DOB As “Date_of_Birth” from Student;

Student_name Date_of_Birth
Raj kumar 2012-06-11
Deep singh 2001-08-12
Payal 1999-02-03
Ankit kumar 2004-12-03
Gauri 2001-03-25

SORTING IN SQL –ORDER BY - Whenever the SELECT query is executed , the resulting rows appear in a pre-decided
order. The ORDER BY clause allow sorting of query result. The sorting can be done either in ascending or descending
order, the default is ascending

1. Ascending Order- - to display the all records of students on the basis of their Name in the ascending order.

 Select * from Student order by Name;


 Select Name, Gender, Marks from Student order by Marks; # on the basis of their Marks

2. Descending Order- - to display the all records of students on the basis of their Name in the ascending order.

 Select * from Student order by Name Desc;


 Select Name, Gender, Marks from Student order by Marks desc; # on the basis of their Marks
AGGREGATE / GROUP FUNCTIONS –We have learn about single-row functions which work on a single value. Sql also
provides multiple-row functions which on multiple value. So we can apply select query on a group of records rather
than the entire table. These functions are called aggregate functions or group functions.

 COUNT( )
 AVG( )
 MIN( )
 MAX( )
 SUM ( )

Table: Emp
Empno Ename job salary Deptno City
8369 SMITH CLERK 2985 10 jaipur
8499 ANYA SALESMAN 9870 20 Kanpur
8566 AMIR SALESMAN 8760 30 Delhi
8698 BINA MANAGER 5643 20 Agra

8912 SUR NULL 3000 10 jaipur

1. AVG( )-This function computes the average of given data. e.g.

 SELECT AVG(salary) From Emp ;


Output

AVG(SAL)
6051.

2. COUNT ( ) - This function counts the number of rows in a given column. If you specify the COLUMN name in
parenthesis of function, then this function returns rows where COLUMN is not null. If you specify the asterisk (*), this
function returns all rows, including duplicates and nulls
 SELECT COUNT(*) FROM Emp ;
Output

COUNT(*)
5

 SELECT COUNT (JOB) FROM Emp;


Output

COUNT(JOB)
4

3. MAX ( )- This function returns the maximum value from a given column or expression.
 SELECT MAX (SAL) FROM Emp ;
Output

MAX(SAL)
9870
4. MIN ( )- This function returns the minimum value from a given column or expression.
 SELECT MIN (SAL) FROM Emp ;
Output

MIN(SAL)
2985

5. SUM ( )- This function returns the sum of values in given column or expression.
 SELECT SUM(SAL) FROM Emp ;
Output

SUM(SAL)
30258

Group by – The group by clause can be used in a select statement to collect data across multiple records and group
the results by one or more columns. It groups the row on the basis of the values present in one or the columns and
then the aggregate functions are applied on any column of these groups to obtain the result of the query.
Calculate the number of employees in each grade.
 SELECT JOB, COUNT (*) FROM EMP GROUP BY JOB ;

Output

JOB COUNT(*)
CLERK 1
SALESMA 2
N
MANAGER 1

Calculate the sum of salary for each department.


 SELECT DEPTNO , SUM(SAL) FROM EMPL GROUP BY DEPTNO ;
Output

DEPTNO SUM(SAL)
10 2985
20 15513
30 8760

WHERE AND HAVING- Where clause works in respect to the whole table but having clause works on group only.
If where and having both are used, then where will be executed first. Where is used to put a condition on individual
row of a table whereas having is used to put a condition on an individual group formed by group by clause in a select
statement.

 Select Sum(Salary) from Emp where City= ‘jaipur’;

 Select Sum(Salary) from Emp Group by City having City= ‘jaipur’;

SQL JOIN- An SQL JOIN clause is used to combine rows from two or more tables, based on a common field between
them. While querying for a join more than one table is considered in from clause. The process/function of combining
data from multiple tables is called a join. Usually such an attribute is the primary key in one table and foreign key in
another table.
1. Cartesian Product ( Cross Product)

2. Equi Join

Rollno Name 3. Natural Join.


1 Rohan
2 Jaya
3 Teena
1. Cartesian Product (Cross Product)- The Cartesian product is also termed
as cross product or cross-join

Table: Student
Table: Game GameNo Game
10 Football
12 Cricket

Student X games

Rohan Football
Jaya Football
Teena Football
Rohan Cricket
Jaya Cricket
Teena Cricket

Equi Join- An equi join is a simple sql join condition that uses the equal to sign(=) as a comparison operator for
defining a relationship between two tables on the basis of a common field i.e. primary key and foreign key.

There are two types –


1. Inner join/ Intersection
2. Outer join
2.1 Right outer join
2.2 left outer join

You might also like