You are on page 1of 36

Unit III: Database Management System Visit to website: https://www.learnpython4cbse.

com

Chapter 15 - Structured Query Language - SQL

In this tutorial we will discuss the following topics


S. No. Topics
1 Introduction
2 Advantages of using SQL
3 Types of SQL Statements
4 Data Definition Language (DDL) Statements
5 Data Manipulation Language (DML) Statements
6 Data Type of Attribute
7 SQL commands
8 CREATE Database
9 Opening a database
10 Getting listings of database and tables
11 CREATE Table
12 DESCRIBE Table
13 ALTER Table
14 DROP Statement
15 INSERTION of Records
16 The SELECT Command
17 Operators in SQL
18 Where Clause
19 Example: Use of Arithmetic Operator

Page 1 of 36
Unit III: Database Management System Visit to website: https://www.learnpython4cbse.com

Chapter 15 - Structured Query Language - SQL

20 Example: Use of Relational Operator


21 Example: Use of Logical Operator
22 Use of DISTINCT Keyword
23 Use of Between And Operator
24 Use of IN Operator
25 Use of LIKE Operator
26 Handling NULL Values
27 ORDER BY Clause
28 Update Command
29 DELETE Command
30 Aggregate functions
31 1.SUM()
32 2.AVG()
33 3.MAX()
34 4.MIN()
35 5.COUNT()
36 GROUP BY CLAUSE
37 HAVING CLAUSE
38 SQL JOINS

Page 2 of 36
Unit III: Database Management System Visit to website: https://www.learnpython4cbse.com

Chapter 15 - Structured Query Language - SQL

INTRODUCTION
 Structured Query Language (SQL) is a standard language used for
accessing databases.
 The Structured Query Language (SQL) is the most popular query
language used by major relational database management systems such
as MySql, ORACLE, SQL Server, etc.
 SQL is easy to learn as the statements comprise of descriptive English
words and are not case sensitive.

SQL provides statements for a variety of tasks, including:

 Querying data
 Inserting, updating, and deleting rows in a table
 Creating, replacing, altering, and dropping objects (tables)
 Controlling access to the database and its objects (tables)
 Guaranteeing database consistency and integrity
 SQL unifies all of the proceeding tasks in one consistent language.

Advantages of using SQL:

i) SQL is portable: SQL is running in all servers, mainframes, PCs,


laptops, and even mobile phones.
ii) High speed: SQL queries can be used to retrieve large amounts of
records from a database quickly and efficiently.

Page 3 of 36
Unit III: Database Management System Visit to website: https://www.learnpython4cbse.com

Chapter 15 - Structured Query Language - SQL

iii) Easy to learn and understand: SQL generally consists of English

statements and as such, it is very easy to learn and understand.


Besides, it does not require much coding unlike in programming
languages.
iv) SQL is used with any DBMS system with any vendor: SQL is used by

all the vendors who develop DBMS. It is also used to create


databases, manage security for a database, etc. It can also be used
for updating, retrieving and sharing data with users.
v) SQL is used for relational databases: SQL is widely used for relational
databases.
vi) SQL acts as both programming language and interactive language:

SQL can do both the jobs of being a programming language as well as


an interactive language at the same time.
vii) Client/Server language: SQL is used for linking front end computers

and back end databases. It provides client server architecture (Email,


and the World Wide Web - all apply the client-server architecture).
viii) Supports object based programming: SQL supports the latest object

based programming and is highly flexible.

Page 4 of 36
Unit III: Database Management System Visit to website: https://www.learnpython4cbse.com

Chapter 15 - Structured Query Language - SQL

Types of SQL Statements


The SQL statements are categorized into different categories based upon
the purpose. They are-

i) Data Definition Language (DDL) statement


ii) Data Manipulation Language (DML) statement
iii) Transaction Control Statement iv) Session Control Statement
v) System Control Statement vi) Embedded SQL Statement
Out of these six, we will be studying only the first two types in this course.

Data Definition Language (DDL) Statements

Data Definition Language (DDL) or Data Description Language (DDL) is a


standard for commands that defines the different structures in a
database. DDL statements are used to create structure of a table, modify
the existing structure of the table and remove the existing table. Some of
the DDL statements are CREATE TABLE, ALTER TABLE and DROP TABLE.

Data Manipulation Language (DML) Statements

Data Manipulation Language (DML) statements are used to access and


manipulate data in existing tables. The manipulation includes inserting
data into tables, deleting data from the tables, retrieving data and
modifying the existing data. The common DML statements are SELECT,
UPDATE, DELETE and INSERT.

Page 5 of 36
Unit III: Database Management System Visit to website: https://www.learnpython4cbse.com

Chapter 15 - Structured Query Language - SQL

Data Type of Attribute


Data type indicates the type of data value that an attribute can have.
Commonly used data types in MySql are:

Data type Description


Specifies character type data of length n where n could be any
CHAR(n) value from 0 to 255. CHAR is of fixed length, means, declaring
Specifies character type data of length ‘n’ where n could be any
value from 0 to 65535. But unlike CHAR, VARCHAR is a variable-
length data type. That is, declaring VARCHAR (30) means a

VARCHAR(n) maximum of 30 characters can be stored but the actual


allocated bytes will depend on the length of entered string. So
‘city’ in VARCHAR (30) will occupy the space needed to store 4
characters only.
INT specifies an integer value. Each INT value occupies 4 bytes
of storage. The range of values allowed in integer type is -
INT 2147483648 to 2147483647. For values larger than that, we
have to use BIGINT, which occupies 8 bytes.
Holds numbers with decimal points. Each FLOAT value occupies
FLOAT 4 bytes.
The DATE type is used for dates in 'YYYY-MM-DD' format. YYYY

DATE is the 4 digit year, MM is the 2 digit month and DD is the 2 digit
date. The supported range is '1000-01-01' to '9999-12-31'.

Page 6 of 36
Unit III: Database Management System Visit to website: https://www.learnpython4cbse.com

Chapter 15 - Structured Query Language - SQL

SQL commands:

CREATE Database
To create a database, we use the CREATE DATABASE statement as shown
in the following syntax:
CREATE DATABASE databasename;
Example: To create a database called Record, we will type following
command at mysql prompt.

mysql> CREATE DATABASE Record;


Query OK, 1 row affected (0.02 sec)

Opening a database
Write the following SQL statement for using/opening the database:
mysql> USE Record;
Database changed

Getting listings of database and tables


1) Show Databases command that lists names of all the databases.

mysql> SHOW DATABASES;


2) Show tables command that lists names of all the tables within a
database.

mysql> SHOW TABLES;

Page 7 of 36
Unit III: Database Management System Visit to website: https://www.learnpython4cbse.com

Chapter 15 - Structured Query Language - SQL

CREATE Table
 Create table command is used to create a table in SQL. It is a DDL
type of command.
 Each table must have at least one column.
Syntax:
CREATE TABLE tablename(
attributename1 datatype constraint,
attributename2 datatype constraint,
:
attributenameN datatype constraint);

Example: Create the following table: STUDENT


Column Name Data Type Size
SAdno Numeric 6
SName Varchar 25
SClass Numeric 2
Sec Char 2
SFees Double 10, 2

mysql> CREATE TABLE STUDENT(


-> SAdmNo INT,
-> SName VARCHAR(25),
-> DOB DATE,
-> SClass NUMERIC(2),
-> Sec CHAR(2),
-> SFees DOUBLE(10,2));
Query OK, 0 rows affected (0.91 sec)

Page 8 of 36
Unit III: Database Management System Visit to website: https://www.learnpython4cbse.com

Chapter 15 - Structured Query Language - SQL

DESCRIBE Table
We can view the structure of an already created table using the describe
statement.
Syntax:

DESCRIBE tablename;

MySQL also supports the short form DESC of DESCRIBE to get description
of table.

To retrieve details about the structure of relation STUDENT, we can write


DESC or DESCRIBE followed by table name:

mysql> DESC STUDENT;

OUTPUT:
+------------+-----------+-----+-----+-------+------+
| Field | Type |Null | Key | Default | Extra |
+------------+-----------+-----+-----+-------+------+
| SAdmNo | int | YES | | NULL | |
+------------+-----------+-----+-----+-------+------+
|SName |varchar(25) | YES | | NULL | |
+------------+-----------+-----+-----+-------+------+
| DOB | date | YES | | NULL | |
+------------+-----------+-----+-----+-------+------+
| SClass | numeric(2) | YES | | NULL | |
+------------+-----------+-----+-----+-------+------+
| Sec | char(2) | YES | | NULL | |
+------------+-----------+-----+-----+-------+------+
| Sfees |double(10,2)| YES | | NULL | |
+------------+-----------+-----+-----+-------+------+
6 rows in set (0.06 sec)

Page 9 of 36
Unit III: Database Management System Visit to website: https://www.learnpython4cbse.com

Chapter 15 - Structured Query Language - SQL

ALTER Table
It is quite possible that after creating a table, as you start using it, you
may discover you've forgot to mention any column or constraint or
specified a wrong name for the column.
In such situation you can use the ALTER TABLE statement to alter or
change an existing table by adding, changing, or deleting a column in the
table.

1. Add New Column:


The basic syntax for adding a new column to an existing table:
Syntax

ALTER TABLE table_name

ADD column_name data_type (size);

The following statement adds a new column mobile to the student table.

mysql> ALTER TABLE STUDENT


-> ADD mobile NUMERIC(12);

Query OK, 0 rows affected (0.47 sec)


Records: 0 Duplicates: 0 Warnings: 0

mysql> DESC STUDENT;

OUTPUT:
Page 10 of 36
Unit III: Database Management System Visit to website: https://www.learnpython4cbse.com

Chapter 15 - Structured Query Language - SQL

+------------+-----------+-----+-----+-------+------+
| Field | Type |Null | Key | Default | Extra |
+------------+-----------+-----+-----+-------+------+
| SAdmNo | int | YES | | NULL | |
+------------+-----------+-----+-----+-------+------+
|SName |varchar(25) | YES | | NULL | |
+------------+-----------+-----+-----+-------+------+
| DOB | date | YES | | NULL | |
+------------+-----------+-----+-----+-------+------+
| SClass | numeric(2) | YES | | NULL | |
+------------+-----------+-----+-----+-------+------+
| Sec | char(2) | YES | | NULL | |
+------------+-----------+-----+-----+-------+------+
| Sfees |double(10,2)| YES | | NULL | |
+------------+-----------+-----+-----+-------+------+
| mobile | numeric(12) | YES | | NULL | |
+------------+-----------+-----+-----+-------+------+
7 rows in set (0.06 sec)

2. Modify datatype of an attribute


We can modify data types of the existing attributes of a table using the
following ALTER statement.
Syntax:

ALTER TABLE table_name MODIFY attribute DATATYPE;

Example: Suppose we need to change the size of attribute SName from


VARCHAR(25) to VARCHAR(20) of the STUDENT table.
The MySQL statement will be:
mysql> ALTER TABLE STUDENT
-> MODIFY SName VARCHAR(20);
Query OK, 0 rows affected (0.11 sec)

Records: 0 Duplicates: 0 Warnings: 0

Page 11 of 36
Unit III: Database Management System Visit to website: https://www.learnpython4cbse.com

Chapter 15 - Structured Query Language - SQL

3. Rename Column Name:


Sometimes we want to change the name of a column. In MySQL, the SQL
syntax for ALTER TABLE Rename Column is,
Syntax

ALTER TABLE table_name

CHANGE Old_column_name new_column_name data_type (size);

Command to rename "mobile" to "mobileno"


mysql> ALTER TABLE STUDENT
-> CHANGE mobile mobileno NUMERIC(12);
Query OK, 0 rows affected (0.11 sec)

Records: 0 Duplicates: 0 Warnings: 0

4. Remove an attribute
Using ALTER, we can remove attributes from a table, as shown in the
below syntax:
Syntax

ALTER TABLE table_name DROP attribute;

To remove the attribute mobileno from the table STUDENT, we can write
the following MySQL statement:
mysql> ALTER TABLE STUDENT DROP mobileno;
Query OK, 0 rows affected (0.42 sec)

Records: 0 Duplicates: 0 Warnings: 0

Page 12 of 36
Unit III: Database Management System Visit to website: https://www.learnpython4cbse.com

Chapter 15 - Structured Query Language - SQL

DROP Statement
Sometimes a table in a database or the database itself needs to be
removed. We can use DROP statement to remove a database or a table
permanently from the system. However, one should be very cautious
while using this statement as it cannot be undone.
Syntax to drop a table:

DROP TABLE table_name;

Syntax to drop a database:

DROP DATABASE database_name;

Let us try to remove a database table using the DROP TABLE statement.
Example:

mysql> DROP TABLE STUDENT;

Similarly, you can delete a database using the DROP DATABASE statement.

The following command will permanently remove the Record database


from the database server.

Example:

mysql> DROP TABLE Record;

Page 13 of 36
Unit III: Database Management System Visit to website: https://www.learnpython4cbse.com

Chapter 15 - Structured Query Language - SQL

INSERTION of Records
INSERT INTO statement is used to insert new records in a table.
Syntax

INSERT INTO tablename

VALUES(value 1, value 2,....);

Let us insert some records in the STUDENT table:


mysql> INSERT INTO student

->VALUES (1501,’Ravi’,’2000-01-18’,11,’A’,12000);

Query OK, 1 row affected (0.01 sec)

If we want to provide values only for some of the attributes in a table


then we shall specify the attribute name alongside each data value as
shown in the following syntax of INSERT INTO statement.

Syntax:

INSERT INTO tablename (column1, column2, ...)

VALUES (value1, value2, ...);

NOTE: The values must be given in the same order in which attributes
are written in INSERT command.
Example: Write a command to insert student name, class and fees in
table student.

Page 14 of 36
Unit III: Database Management System Visit to website: https://www.learnpython4cbse.com

Chapter 15 - Structured Query Language - SQL

mysql> INSERT INTO student (SName, SClass, SFees)

->VALUES (’Raman’,,12,15000);

Query OK, 1 row affected (0.01 sec)

The SELECT Command:


The SQL statement SELECT is used to retrieve data from the tables in a
database and is also called query statement.
Syntax:

SELECT col1, col2, ...


FROM table_name
WHERE condition

Here,

 col1, col2, ... are the column names of the table table_name from
which we want to retrieve data.
 The FROM clause is always written with SELECT clause as it specifies
the name of the table from which data is to be retrieved.
 The WHERE clause is optional and is used to retrieve data that meet
specified condition(s).
Example:
1. Display student table information.

mysql> SELECT * FROM STUDENT;

Page 15 of 36
Unit III: Database Management System Visit to website: https://www.learnpython4cbse.com

Chapter 15 - Structured Query Language - SQL

 This will display all information of the particular table (student) in the
database.
2. Retrieve selected columns
The following query displays student’ admission numbers and class of
all the students:

mysql> SELECT SName, SClass FROM STUDENT;

3. To display name of 11th class student information.

mysql> SELECT SName FROM STUDENT

-> WHERE class = 11;

Operators in SQL:
The following are the commonly used operators in SQL

1. Arithmetic Operators +, -, *, /

2. Relational Operators =, <, >, <=, >=, <>

3. Logical Operators OR, AND, NOT

Arithmetic Operators are used to perform simple arithmetic operations.

Relational Operators are used when two values are to be compared and

Logical Operators are used to connect search conditions in the WHERE


Clause in SQL with other operators.

Page 16 of 36
Unit III: Database Management System Visit to website: https://www.learnpython4cbse.com

Chapter 15 - Structured Query Language - SQL

Selecting Specific ROWS – Where Clause:


With the use of WHERE clause, only those rows that satisfied the given
condition are displayed in the output

Example: Use of Relational Operator

1. Display students' admission no. and name, who are paying below
10000 fees.

mysql> SELECT SAdmno, SName FROM STUDENT

-> WHERE SFees < 10000;

SAdmno SName

1250 Qamar

2. Display students' admission no. and name, who are paying above or
equal to 10000 fees.

mysql> SELECT SAdmbo, SName FROM STUDENT

-> WHERE SFees >= 10000;

SAdmno SName
1501 Ravi
1605 Amit
1610 Sumit
1201 Annu
1520 Sunita
1001 Umar

Page 17 of 36
Unit III: Database Management System Visit to website: https://www.learnpython4cbse.com

Chapter 15 - Structured Query Language - SQL

3. Display students' information, who are not in class 10

mysql> SELECT * FROM STUDENT

-> WHERE SClass != 10;

SAdmno SName DOB SClass Sec SFees


1501 Ravi 2000-01-18 11 A 12000.00
1605 Amit 2000-02-20 11 A 12000.00
1520 Sunita 1999-08-14 12 C 12000.00
1001 Umar 2001-09-25 11 C 11000.00
1250 Qamar 2008-09-25 8 A 8000.00

Example: Use of Arithmetic Operator

mysql> SELECT SAdmno, SName, SFees + 500 FROM student;

The above command, on execution, shall increment the value for all the
rows of the field Fees by 50 and shall display the Admno, Name and Fees
for all the students, increased by 500.

Example: Use of Logical Operator

1. Display information of students in class 11A.

mysql> SELECT * FROM STUDENT

-> WHERE SClass = 11 and Sec = ‘A’;

SAdmno SName DOB SClass Sec SFees


1501 Ravi 2000-01-18 11 A 12000.00
1605 Amit 2000-02-20 11 A 12000.00

Page 18 of 36
Unit III: Database Management System Visit to website: https://www.learnpython4cbse.com

Chapter 15 - Structured Query Language - SQL

2. Display 11th and 12th class students' information.

mysql> SELECT * FROM STUDENT

-> WHERE SClass = 11 or SClass = 12;

SAdmno SName DOB SClass Sec SFees


1501 Ravi 2000-01-18 11 A 12000.00
1605 Amit 2000-02-20 11 A 12000.00
1520 Sunita 1999-08-14 12 C 12000.00
1001 Umar 2001-09-25 11 C 11000.00

3. Display students' information, who are not in 10th class.

mysql> SELECT * FROM STUDENT

-> WHERE NOT SClass = 10;

SAdmno SName DOB SClass Sec SFees


1501 Ravi 2000-01-18 11 A 12000.00
1605 Amit 2000-02-20 11 A 12000.00
1520 Sunita 1999-08-14 12 C 12000.00
1001 Umar 2001-09-25 11 C 11000.00
1250 Qamar 2008-09-25 8 A 8000.00

Eliminating Duplicate/Redundant data


(Use of DISTINCT Keyword):

 DISTINCT keyword is used to restrict the duplicate rows from the


results of a SELECT statement.

 Only one NULL value is returned in the results with DISTINCT keyword.

Page 19 of 36
Unit III: Database Management System Visit to website: https://www.learnpython4cbse.com

Chapter 15 - Structured Query Language - SQL

Example: To display different classes from table student.

mysql> SELECT DISTINCT SClass

-> FROM STUDENT;

SClass
11
10
12
8

Conditions based on a Range (Use of Between And Operator):

 SQL provides a BETWEEN operator that defines a range of values that


the column value must fall for the condition to become true.

 The range includes both lower and upper value.

Example: Display students' information, whose admission no between


1250 and 1605.

mysql> SELECT * FROM STUDENT

-> WHERE SAdmno BETWEEN 1250 AND 1605;

SAdmno SName DOB SClass Sec SFees


1501 Ravi 2000-01-18 11 A 12000.00
1605 Amit 2000-02-20 11 A 12000.00
1520 Sunita 1999-08-14 12 C 12000.00
1250 Qamar 2008-09-25 8 A 8000.00

Page 20 of 36
Unit III: Database Management System Visit to website: https://www.learnpython4cbse.com

Chapter 15 - Structured Query Language - SQL

 The operator NOT BETWEEN retrieves the rows, which are not
satisfying the BETWEEN condition.

mysql> SELECT * FROM STUDENT

-> WHERE SAdmno NOT BETWEEN 1250 AND 1605;

SAdmno SName DOB SClass Sec SFees


1610 Sumit 1999-05-20 10 B 11000.00
1201 Annu 2001-04-20 10 C 11000.00
1001 Umar 2001-09-25 11 C 11000.00

Conditions based on a List (Use of IN Operator):

 To specify a list of values, IN operator is used.

 This operator select values that match any value in the given list.

Example: Display students' information, who are in section A and B.

mysql> SELECT * FROM STUDENT

-> WHERE Sec IN(‘A’,’B’);

SAdmno SName DOB SClass Sec SFees


1501 Ravi 2000-01-18 11 A 12000.00
1605 Amit 2000-02-20 11 A 12000.00
1610 Sumit 1999-05-20 10 B 11000.00
1250 Qamar 2008-09-25 8 A 8000.00
 The NOT IN operator finds rows that do not match in the list.

mysql> SELECT * FROM STUDENT

-> WHERE Sec NOT IN(‘A’,’B’);

Page 21 of 36
Unit III: Database Management System Visit to website: https://www.learnpython4cbse.com

Chapter 15 - Structured Query Language - SQL

SAdmno SName DOB SClass Sec SFees


1201 Annu 2001-04-20 10 C 11000.00
1520 Sunita 1999-08-14 12 C 12000.00
1001 Umar 2001-09-25 11 C 11000.00

Conditions based on Pattern (Use of LIKE Operator) :

 Many a times we want to query find out names starting with ‘A’ or to
find out pin codes starting with ‘11’.
 This is called substring pattern matching. We cannot match such
patterns using = operator as we are not looking for exact match.
 SQL provides LIKE operator that can be used with WHERE clause to
search for a specified pattern in a column.
 Patterns are case – sensitive.

 The LIKE operator makes use of the following two wild card characters:
 % (percent)— used to represent zero, one, or multiple characters
 _ (underscore)— used to represent a single character
 The keyword NOT LIKE is used to select rows that do not matching the
specified pattern of characters.

Example:
1. Query displays details of all those students whose name starts with 'A'.

mysql> SELECT * FROM STUDENT

-> WHERE SName LIKE 'A%';

Page 22 of 36

-> WHERE Sec NOT IN(‘A’,’B’);


Unit III: Database Management System Visit to website: https://www.learnpython4cbse.com

Chapter 15 - Structured Query Language - SQL

SAdmno SName DOB SClass Sec SFees


1605 Amit 2000-02-20 11 A 12000.00
1201 Annu 2001-04-20 10 C 11000.00

2. Query displays details of all those students whose name ends with 'r'.

mysql> SELECT * FROM STUDENT

-> WHERE SName LIKE '%r';

SAdmno SName DOB SClass Sec SFees


-> WHERE Sec NOT IN(‘A’,’B’);
1001 Umar 2001-09-25 11 C 11000.00
1250 Qamar 2008-09-25 8 A 8000.00

3. Query displays details of all those students whose name consists of


exactly 5 letters and starts with any letter but has ‘mar’ after that.

mysql> SELECT * FROM STUDENT

-> WHERE SName LIKE '__mar';

SAdmno SName DOB SClass Sec SFees


->1250
WHERE Sec NOT IN(‘A’,’B’);
Qamar 2008-09-25 8 A 8000.00

4. Query displays names of all the students containing 'mi' as a substring


in name.

mysql> SELECT * FROM STUDENT

-> WHERE SName LIKE '%mi%';

Page 23 of 36
-> WHERE Sec NOT IN(‘A’,’B’);
Unit III: Database Management System Visit to website: https://www.learnpython4cbse.com

Chapter 15 - Structured Query Language - SQL

SAdmno SName DOB SClass Sec SFees


1605 Amit 2000-02-20 11 A 12000.00
1610 Sumit 1999-05-20 10 B 11000.00

5. Query displays names of all students containing 'a' as the second


character.

mysql> SELECT * FROM STUDENT

-> WHERE SName LIKE '_a%';

SAdmno SName DOB SClass Sec SFees


->1501
WHERE Sec NOT
RaviIN(‘A’,’B’);
2000-01-18 11 A 12000.00
1250 Qamar 2008-09-25 8 A 8000.00

Handling NULL Values


 The NULL value in a column can be searched for in a table using IS NULL in
WHERE clause.

 Non – NULL values can be listed using IS NOT NULL.

Example:
1. Query displays details of all those Students who have not been given
fees. This implies that the fees column will be blank.

mysql> SELECT * FROM STUDENT

-> WHERE SFees IS NULL;

2. Query displays names of all the students who have been given fees.
-> WHERE Sec NOT IN(‘A’,’B’);
This implies that the fees column will not be blank.

Page 24 of 36
Unit III: Database Management System Visit to website: https://www.learnpython4cbse.com

Chapter 15 - Structured Query Language - SQL

mysql> SELECT SName FROM STUDENT

-> WHERE SFees IS NOT NULL;

ORDER BY Clause:
-> WHERE Sec NOT IN(‘A’,’B’);
 ORDER BY clause is used to display the result of a query in a specific
order (sorted order).

 The sorting can be done in ascending or in descending order.

 It should be kept in mind that the actual data in the database is not
sorted but only the results of the query are displayed in sorted order.

 Descending order is specified by DESC.

 Ascending order is specified by ASC.

 Ordering can be performed on multiple attributes, separated by


commas.

Example:
1. Query to displays details of all the students in ascending order of their
Name.

mysql> SELECT * FROM STUDENT

-> ORDER BY SName;

-> WHERE Sec NOT IN(‘A’,’B’);

Page 25 of 36
Unit III: Database Management System Visit to website: https://www.learnpython4cbse.com

Chapter 15 - Structured Query Language - SQL

SAdmno SName DOB SClass Sec SFees


1605 Amit 2000-02-20 11 A 12000.00
1201 Annu 2001-04-20 10 C 11000.00
1250 Qamar 2008-09-25 8 A 8000.00
1501 Ravi 2000-01-18 11 A 12000.00
1610 Sumit 1999-05-20 10 B 11000.00
1520 Sunita 1999-08-14 12 C 12000.00
1001 Umar 2001-09-25 11 C 11000.00

2. Query displays details of all the employees in descending order of their


date of birth.

mysql> SELECT * FROM STUDENT

-> ORDER BY DOB DESC;

SAdmno SName DOB SClass Sec SFees


->1250
WHERE Sec NOT IN(‘A’,’B’);
Qamar 2008-09-25 8 A 8000.00
1001 Umar 2001-09-25 11 C 11000.00
1201 Annu 2001-04-20 10 C 11000.00
1605 Amit 2000-02-20 11 A 12000.00
1501 Ravi 2000-01-18 11 A 12000.00
1520 Sunita 1999-08-14 12 C 12000.00
1610 Sumit 1999-05-20 10 B 11000.00

Update Command

The UPDATE statement is used to update existing data in a table.


Syntax:
UPDATE table_name
SET column1_name = value1, column2_name = value2,...
WHERE condition;
Page 26 of 36
Unit III: Database Management System Visit to website: https://www.learnpython4cbse.com

Chapter 15 - Structured Query Language - SQL

Here,
 column1_name, column2_name,... are the names of the columns or
fields of a database table whose values you want to update.
 You can also combine multiple conditions using
the AND or OR operators,

Example: 1. Increase fees value by 500.

mysql> UPDATE STUDENT

-> SET SFees = SFees + 500

SAdmno SName DOB SClass Sec SFees


1250 Qamar 2008-09-25 8 A 8500.00
1001 Umar 2001-09-25 11 C 11500.00
1201 Annu 2001-04-20 10 C 11500.00
1605 Amit 2000-02-20 11 A 12500.00
1501 Ravi 2000-01-18 11 A 12500.00
1520 Sunita 1999-08-14 12 C 12500.00
1610 Sumit 1999-05-20 10 B 11500.00

Example: Updating a Single Column

The following SQL statement will update the SName field of


the STUDENT table and set a new value where the student admission
number i.e. SAdmno is equal to 1501.

Page 27 of 36
Unit III: Database Management System Visit to website: https://www.learnpython4cbse.com

Chapter 15 - Structured Query Language - SQL

mysql> UPDATE STUDENT

-> SET SNAME = ‘Sara’

-> WHERE SAdmno = 1501

mysql> SELECT * FROM STUDENT;

-> WHERE Sec NOT IN(‘A’,’B’);

SAdmno SName DOB SClass Sec SFees


-> WHERE Sec NOT IN(‘A’,’B’);
1250 Qamar 2008-09-25 8 A 8500.00
1001 Umar 2001-09-25 11 C 11500.00
1201 Annu 2001-04-20 10 C 11500.00
1605 Amit 2000-02-20 11 A 12500.00
1501 Sara 2000-01-18 11 A 12500.00
1520 Sunita 1999-08-14 12 C 12500.00
1610 Sumit 1999-05-20 10 B 11500.00

Example: Updating Multiple Columns:


The following example will update the SFees and Sec field of an existing student in

the student table whose SAdmno is 1605.

mysql> UPDATE STUDENT

-> SET SFees = 10500, Sec = ‘D’

-> WHERE SAdmno = 1605;

Check the output


-> WHERE Sec NOT IN(‘A’,’B’);

mysql> SELECT * FROM STUDENT;

-> WHERE Sec NOT IN(‘A’,’B’);


Page 28 of 36
Unit III: Database Management System Visit to website: https://www.learnpython4cbse.com

Chapter 15 - Structured Query Language - SQL

SAdmno SName DOB SClass Sec SFees


1250 Qamar 2008-09-25 8 A 8500.00
1001 Umar 2001-09-25 11 C 11500.00
1201 Annu 2001-04-20 10 C 11500.00
1605 Amit 2000-02-20 11 D 10500.00
1501 Sara 2000-01-18 11 A 12500.00
1520 Sunita 1999-08-14 12 C 12500.00
1610 Sumit 1999-05-20 10 B 11500.00

DELETE Command

The DELETE statement is used to delete one or more record(s) from a


table.
Syntax:
DELETE FROM table_name
WHERE condition;

Warning: The WHERE clause in the DELETE statement specifies which record

or records should be deleted. It is however optional, but if you omit or forget


the WHERE clause, all the records will be deleted permanently from the table.

Please remember that this command will delete only row information but not

the structure of the table.

Example: Suppose the student with admission number 1501 has left the school.
We can use the following MySQL statement to delete that record from the STUDENT
table.

Page 29 of 36
Unit III: Database Management System Visit to website: https://www.learnpython4cbse.com

Chapter 15 - Structured Query Language - SQL

mysql> DELETE FROM STUDENT


-> WHERE SAdmno = 1501;

Query OK, 1 row affected (0.06 sec)

mysql> SELECT * FROM STUDENT;

SAdmno SName DOB SClass Sec SFees


->1250 Qamar
WHERE Sec NOT 2008-09-25
IN(‘A’,’B’); 8 A 8000.00
1001 Umar 2001-09-25 11 C 11000.00
1201 Annu 2001-04-20 10 C 11000.00
1605 Amit 2000-02-20 11 D 10500.00
1520 Sunita 1999-08-14 12 C 12000.00
1610 Sumit 1999-05-20 10 B 11000.00

Aggregate functions

Aggregate functions are used to implement calculation based upon a


particular column. These functions always return a single value.
Aggregate functions are:
1. SUM()
2. AVG()
3. MAX()
4. MIN()
5. COUNT() AND COUNT(*)

Page 30 of 36
Unit III: Database Management System Visit to website: https://www.learnpython4cbse.com

Chapter 15 - Structured Query Language - SQL

1.SUM():

This function is used to find the total value of a particular column.

Example:
mysql> SELECT SUM (SFees)
-> FROM STUDENT;

SUM (SFees)
63500

2.AVG():

This function is used to find the average value of a particular column.


Example:
mysql> SELECT AVG (SFees)
-> FROM STUDENT;

AVG (SFees)
10583.33

3.MAX():

This function is used to find the maximum value of a particular column.


Example:
mysql> SELECT MAX (SFees)
-> FROM STUDENT;

Page 31 of 36
Unit III: Database Management System Visit to website: https://www.learnpython4cbse.com

Chapter 15 - Structured Query Language - SQL

MAX (SFees)
12000

4.MIN():

This function is used to find the minimum value of a particular column.


Example:

mysql> SELECT MIN (SFees)


-> FROM STUDENT;

MIN (SFees)
8000

5.COUNT():

This function is used to find the number of values (i.e. number of rows) of
a particular column.
A. COUNT (Column_Name):
The COUNT (Column_Name) function returns the number of values (NULL
values will not be counted) of the specified column.

Example: To count the classes from the student table.


mysql> SELECT COUNT (SClass)
-> FROM STUDENT;

Page 32 of 36
Unit III: Database Management System Visit to website: https://www.learnpython4cbse.com

Chapter 15 - Structured Query Language - SQL

COUNT (SClass)
6

B. COUNT (*):

The COUNT (*) function returns the total number of records in a table,
counts NULL values also

Example: To count the number of records from the table Employee.

mysql> SELECT COUNT (*)


-> FROM STUDENT;

COUNT (*)
6
C. COUNT (DISTINCT Column_Name):
The COUNT (DISTINCT column_name) function returns the number of
distinct values of the specified column.

Example: To count the different sections from the table STUDENT.


mysql> SELECT COUNT (DISTINCT Sec)
-> FROM STUDENT;

COUNT (DISTINCT Sec)


4
Page 33 of 36
Unit III: Database Management System Visit to website: https://www.learnpython4cbse.com

Chapter 15 - Structured Query Language - SQL

GROUP BY CLAUSE:

 The GROUP BY clause groups records into summary rows.


 GROUP BY returns one records for each group.
 GROUP BY typically also involves aggregates: COUNT, MAX, SUM,
AVG, etc.
 GROUP BY can group by one or more columns.

Syntax:
SELECT column-names FROM table-name
WHERE condition
GROUP BY column-names

Example:

1) Display number of students in each class.

mysql> SELECT COUNT (*), SClass


-> FROM STUDENT
-> GROUP BY SClass;

COUNT(*) SClass
1 8
2 10
2 11
1 12

Page 34 of 36
Unit III: Database Management System Visit to website: https://www.learnpython4cbse.com

Chapter 15 - Structured Query Language - SQL

2) Display sum of fees for each class.

mysql> SELECT SClass, SUM (SFees)


-> FROM STUDENT
-> GROUP BY SClass;

SClass SUM (SFees)


8 8000
10 22000
11 21500
12 12000

HAVING CLAUSE:

 HAVING filters records that work on summarized GROUP BY results.


 HAVING applies to summarized group records, whereas WHERE
applies to individual records.
 Only the groups that meet the HAVING criteria will be returned.
 HAVING requires that a GROUP BY clause is present.
 WHERE and HAVING can be in the same query.
Syntax:
SELECT column-names FROM table-name
WHERE condition
GROUP BY column-names
HAVING condition
ORDER BY column-names

Page 35 of 36
Unit III: Database Management System Visit to website: https://www.learnpython4cbse.com

Chapter 15 - Structured Query Language - SQL

Example: Display sum of fees which is more than 8000 for each class

mysql> SELECT SClass, SUM (SFees)


-> FROM STUDENT
-> GROUP BY SClass
-> HAVING SUM(SFEES)>8000;

SClass SUM (SFees)


10 22000
11 21500
12 12000

SQL JOINS

The process/function of combining data from multiple tables is called a


JOIN. SQL can extract data from two or even more than two related
tables by performing either a physical or virtual join on the tables using
WHERE clause.
The types of SQL joins are as follows:
1. Cartesian Product (Cross Product)
2. Equi Join
3. Self Join
4. Non-Equi Join
5. Natural Join

More on joins…… click here

Page 36 of 36

You might also like