SQL Structured Query Language Notes
SQL Structured Query Language Notes
O
H
A
M
M
ED
M
AT
H
EE
N
L
R
STUDENT NOTES || CHAPTER 9 STRUCTURED QUERY LANGUAGE (SQL) April 23, 2025
Contents
LICENSE 3
R
9.2.1 Installing MySQL . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5
9.3 Data Types and Constraints in MySQL . . . . . . . . . . . . . . . . . . . . . . . 6
L
9.4 SQL for Data Definition . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8
N
9.4.4 — ALTER TABLE . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10
9.4.5 — DROP Statement . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 14
EE
9.5 — SQL for Data Manipulation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 15
9.6 — SQL for Data Query . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 18
9.6.2 — Querying Using Database OFFICE . . . . . . .
H . . . . . . . . . . . . . . . . . 19
AT
9.7 — Data Updation and Deletion . . . . . . . . . . . . . . . . . . . . . . . . . . . . 32
9.8: Functions in SQL . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 34
9.9 — GROUP BY Clause in SQL . . . . . . . . . . . . . . . . . . . . . . . . . . . . 38
M
LICENSE
This work is licensed under the Creative Commons Attribution-NonCommercial-NoDerivs 4.0 Interna-
tional License. To view a copy of this license, visit [Link] or
send a letter to Creative Commons, PO Box 1866, Mountain View, CA 94042, USA.
“Karnataka Second PUC Computer Science Study Material / Student Notes” by L R Mohammed Matheen
is licensed under CC BY-NC-ND 4.0.
R
L
N
Figure 1: Licence
EE
This work is licensed under the Creative Commons Attribution-NonCommercial-NoDerivs 4.0 Interna-
tional License.
H
Portions of this work may include material under separate copyright. These materials are not covered by
AT
this Creative Commons license and are used by permission or under applicable copyright exceptions.
tional License.
ED
M
M
A
H
O
M
CHAPTER NOTES
Introduction
R
• In the previous chapter, you learned about Relational Database Management Systems
(RDBMS) — systems that organize data in tables called relations.
L
• Examples of RDBMS:
N
– MySQL
– Microsoft SQL Server
EE
– PostgreSQL
– Oracle
H
AT
Purpose of RDBMS
• Allows us to:
M
• The tool used to perform all these actions is called SQL (Structured Query Language).
M
What is SQL?
A
• SQL (Structured Query Language) is a special-purpose language used to access and manipulate
data in a database.
H
• It is used instead of writing application programs, especially in the context of Database Man-
O
– MySQL
– ORACLE
– SQL Server
Feature Description
Easy to Learn SQL uses descriptive English words; it’s readable and intuitive.
Case-Insensitive Commands like SELECT and select are treated the same.
Declarative You tell SQL what you want, not how to do it.
R
Powerful SQL does more than just queries. It includes commands to define data,
insert data, update, and manage constraints.
L
N
Capabilities of SQL
EE
• Define data structures (tables, attributes, constraints)
• Manipulate data (insert, delete, update)
• Query data (retrieve specific or filtered data)
H
AT
• Declare constraints (rules on what kind of data can go into tables)
M
• The textbook uses the StudentAttendance database (introduced in Chapter 8) to explain SQL
ED
queries.
• Students will create, populate, and query this database using SQL.
M
What is MySQL?
A
– Once started, the terminal (or command-line interface) will show the prompt:
mysql>
Point Description
R
Case Insensitivity SQL keywords, table names, and column names are not case-sensitive.
End Statements with ;
L
Always terminate SQL commands with a semicolon.
Multiline Statements If an SQL statement is long: → Write it over multiple lines → Don’t
N
put ; until the last line → mysql> prompt changes to -> for
EE
continuation
H
Activity 9.1 Q: Find and list other types of databases besides RDBMS.
AT
Example Answers:
• Hierarchical databases
• Object-oriented databases
ED
• Network databases
M
• Each attribute:
H
– May have constraints — rules that restrict the values entered into that column.
M
R
to 65535. - Only actual input length occupies
space.
L
INT Integer values. - Occupies 4 bytes. - Use
N
BIGINT (8 bytes) for larger numbers.
EE
FLOAT Decimal (floating-point) numbers. - Occupies 4
bytes.
DATE
H
Stores dates in 'YYYY-MM-DD' format. - Range:
'1000-01-01' to '9999-12-31'.
AT
M
Activity 9.2: What other data types are supported in MySQL? Are there other variants of integer and
float?
ED
Examples:
9.3.2 Constraints
H
Definition: Constraints are rules or restrictions placed on data in a table to ensure accuracy and
O
reliability.
M
Constraint Description
Constraint Description
R
Used to create relationships.
L
N
Concept Check: Q: Which two constraints, when applied together, produce a Primary Key? NOT
NULL + UNIQUE
EE
9.4 SQL for Data Definition
H
AT
Purpose This section explains how to:
• Create a database
M
GUARDIAN)
SQL Command
SDateofBirth DATE,
GUID CHAR(12),
PRIMARY KEY (RollNumber)
);
DESCRIBE Output
R
+--------------+-------------+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra |
L
+--------------+-------------+------+-----+---------+-------+
| RollNumber | int | NO | PRI | NULL | |
N
| SName | varchar(20) | YES | | NULL | |
EE
| SDateofBirth | date | YES | | NULL | |
| GUID | char(12) | YES | | NULL | |
+--------------+-------------+------+-----+---------+-------+
H
AT
2. GUARDIAN Table Attributes & Description
M
The SHOW TABLES; command is used to list all tables present in the currently selected database.
Syntax:
SHOW TABLES;
Example:
R
USE StudentAttendance;
L
SHOW TABLES;
N
Output
EE
+------------------------------+
| Tables_in_studentattendance |
+------------------------------+
H
AT
| STUDENT |
| GUARDIAN |
| ATTENDANCE |
M
+------------------------------+
3 rows in set (0.00 sec)
ED
This shows that the database contains three tables: STUDENT, GUARDIAN, and ATTENDANCE.
M
Purpose of ALTER TABLE Once a table is created, you might need to:
A
H
All these structural changes are done using the ALTER TABLE command.
General Syntax:
ALTER TABLE table_name
<alteration_action>;
Example:
ALTER TABLE GUARDIAN
ADD PRIMARY KEY (GUID);
R
Composite Primary Key: Combines multiple columns to uniquely identify a record.
L
(B) Add Foreign Key to a Table
N
Ensure:
EE
• The referenced table exists.
• The referenced column is a primary key.
• Data types must match.
H
AT
Syntax:
M
Example:
M
(C) Add UNIQUE Constraint Ensures all values in a column are distinct.
H
O
Example:
M
Syntax:
ALTER TABLE table_name
ADD column_name datatype;
Example:
ALTER TABLE GUARDIAN
ADD Income INT;
R
(E) Modify Data Type of Attribute
L
N
Syntax:
EE
ALTER TABLE table_name
MODIFY column_name NEW_DATATYPE;
Example: H
AT
ALTER TABLE GUARDIAN
MODIFY GAddress VARCHAR(40);
M
Example:
M
Syntax:
M
Example:
ALTER TABLE STUDENT
MODIFY SDateofBirth DATE DEFAULT '2000-05-15';
Syntax:
ALTER TABLE table_name
DROP column_name;
Example:
R
ALTER TABLE GUARDIAN
L
DROP Income;
N
(I) Remove Primary Key
EE
Syntax:
ALTER TABLE table_name
H
AT
DROP PRIMARY KEY;
Example:
M
Note: Each table should have a primary key for data integrity. You can re-add it using ADD PRIMARY
KEY.
M
M
Add Primary To define a column(s) as a ALTER TABLE table_name ADD PRIMARY KEY
O
Add UNIQUE To ensure all values in a ALTER TABLE GUARDIAN ADD UNIQUE
Constraint column are unique (GPhone);
Add New To add a new column to an ALTER TABLE GUARDIAN ADD Income INT;
Attribute existing table
Modify Data To change data type of an ALTER TABLE GUARDIAN MODIFY GAddress
R
Type existing column VARCHAR(40);
L
Modify To enforce NOT NULL or ALTER TABLE STUDENT MODIFY SName
Constraint other constraints VARCHAR(20) NOT NULL;
N
Add To provide a default value ALTER TABLE STUDENT MODIFY SDateofBirth
EE
DEFAULT for a column DATE DEFAULT '2000-05-15';
Value
Remove
Attribute
To delete a column from a
table H
ALTER TABLE GUARDIAN DROP Income;
AT
Remove To drop an existing primary ALTER TABLE GUARDIAN DROP PRIMARY KEY;
Primary Key key
M
ED
Purpose of the DROP Statement The DROP statement in SQL is used to permanently delete a:
M
• Table, or
M
• Entire database
A
Once dropped:
H
A. DROP a Table
Syntax:
DROP TABLE table_name;
Example:
DROP TABLE STUDENT;
This command will delete the STUDENT table, including all its data and structure from the database.
B. DROP a Database
R
L
Syntax:
N
DROP DATABASE database_name;
EE
Example:
DROP DATABASE StudentAttendance;
H
This will delete the entire database and all tables (STUDENT, GUARDIAN, ATTENDANCE, etc.) within it.
AT
Important Notes:
M
• There is no undo for DROP. Once executed, the data is gone permanently.
• Always double-check before dropping tables or databases.
ED
• If you’re testing, it’s good practice to back up data or use temporary test tables.
• After defining tables (DDL), we use Data Manipulation Language (DML) commands to:
A
– Insert
H
– Update
O
– Delete
M
Use this when inserting values for all attributes in the same order as the table.
R
Result:
L
Query OK, 1 row affected (0.01 sec)
N
View the Inserted Record:
EE
SELECT * FROM GUARDIAN;
H
+--------------+--------------+-----------+----------------------------+
AT
| GUID | GName | GPhone | GAddress |
+--------------+--------------+-----------+----------------------------+
M
Or
+------------+--------------+--------------+--------------+
| RollNumber | SName | SDateofBirth | GUID |
+------------+--------------+--------------+--------------+
| 1 | Atharv Ahuja | 2003-05-15 | 444444444444 |
+------------+--------------+--------------+--------------+
R
Example 4: Insert Student with NULL GUID (Allowed)
L
INSERT INTO STUDENT
VALUES (3, 'Taleem Shah', '2002-02-28', NULL);
N
EE
Or using selected columns:
+------------+--------------+--------------+--------------+
| RollNumber | SName | SDateofBirth | GUID |
M
+------------+--------------+--------------+--------------+
M
+------------+--------------+--------------+--------------+
H
Tip:
O
If the order of attributes is not known, always use Syntax 2 (with column names).
M
Q: Can we insert two records with the same RollNumber? No, because RollNumber is a
PRIMARY KEY, it must be unique.
What is Data Querying? Once data is inserted into tables, we use SQL to retrieve specific infor-
mation. This process is called querying.
R
• Apply conditions to filter rows
L
N
EE
9.6.1 SELECT Statement Syntax:
Explanation:
ED
Output:
M
+------------+--------------+--------------+--------------+
M
Output:
+------------+--------------+
| RollNumber | SName |
+------------+--------------+
| 1 | Atharv Ahuja |
| 3 | Taleem Shah |
+------------+--------------+
R
WHERE GUID IS NOT NULL;
L
Output:
N
+------------+--------------+--------------+--------------+
EE
| RollNumber | SName | SDateofBirth | GUID |
+------------+--------------+--------------+--------------+
| 1 | Atharv Ahuja | 2003-05-15 | 444444444444 |
+------------+--------------+--------------+--------------+
H
AT
9.6.2 — Querying Using Database OFFICE
M
Context Many organizations manage data using databases like OFFICE, which include related ta-
bles such as EMPLOYEE and DEPARTMENT. Each employee belongs to a department, and the DeptId in
ED
R
SELECT EmpNo FROM EMPLOYEE;
L
Output:
N
+-------+
EE
| EmpNo |
+-------+
|
|
101 |
102 | H
AT
| 103 |
| 104 |
M
| 105 |
| 106 |
ED
| 107 |
| 108 |
| 109 |
M
| 110 |
+-------+
M
A
Query 2:
H
Output:
M
+-------+----------+
| EmpNo | Ename |
+-------+----------+
| 101 | Aaliya |
| 102 | Kritika |
| 103 | Shabbir |
| 104 | Gurpreet |
| 105 | Joseph |
| 106 | Sanya |
| 107 | Vergese |
| 108 | Nachaobi |
| 109 | Daribha |
| 110 | Tanya |
+-------+----------+
R
L
(B) Renaming Columns (Using Alias) Query:
N
SELECT Ename AS Name FROM EMPLOYEE;
EE
Output:
+----------+
| Name | H
AT
+----------+
| Aaliya |
M
| Kritika |
| Shabbir |
ED
| Gurpreet |
| Joseph |
| Sanya |
M
| Vergese |
| Nachaobi |
M
| Daribha |
A
| Tanya |
+----------+
H
O
Output:
+----------+-----------+
| Name | Salary*12 |
+----------+-----------+
| Aaliya | 120000 |
| Kritika | 720000 |
| Shabbir | 540000 |
| Gurpreet | 228000 |
| Joseph | 408000 |
| Sanya | 576000 |
| Vergese | 180000 |
| Nachaobi | 348000 |
R
| Daribha | 504000 |
L
| Tanya | 600000 |
+----------+-----------+
N
To rename the calculated column:
EE
Query (Using Alias with Space):
H
SELECT Ename AS Name, Salary*12 AS 'Annual Income' FROM EMPLOYEE;
AT
Output:
+----------+---------------+
M
| Aaliya | 120000 |
| Kritika | 720000 |
| Shabbir | 540000 |
M
| Gurpreet | 228000 |
M
| Joseph | 408000 |
| Sanya | 576000 |
A
| Vergese | 180000 |
| Nachaobi | 348000 |
H
| Daribha | 504000 |
O
| Tanya | 600000 |
M
+----------+---------------+
Note: Aliased column names with spaces should be enclosed in single quotes ('Annual Income').
(D) Using DISTINCT — To Avoid Duplicates Purpose: The DISTINCT clause is used to retrieve
unique values only, avoiding repetitions.
Query: Display Unique Department IDs
Output:
+--------+
| DeptId |
+--------+
| D01 |
R
| D02 |
| D04 |
L
| D03 |
N
| D05 |
+--------+
EE
Without DISTINCT, repeated DeptIds would be shown for each employee.
H
AT
(E) Using WHERE Clause — To Filter Rows Purpose: The WHERE clause helps select only those
rows that satisfy a specific condition.
M
Output:
M
+-------+----------+--------+-------+--------+
M
+-------+----------+--------+-------+--------+
| 102 | Kritika | 60000 | 123 | D01 |
H
Output:
+-------+--------+--------+-------+--------+
| EmpNo | Ename | Salary | Bonus | DeptId |
+-------+--------+--------+-------+--------+
| 101 | Aaliya | 10000 | 234 | D02 |
| 106 | Sanya | 48000 | 695 | D02 |
+-------+--------+--------+-------+--------+
R
Query 3: Employees with Salary > 25000
L
FROM EMPLOYEE
WHERE Salary > 25000;
N
Output:
EE
+-------+----------+--------+
| EmpNo | Ename | Salary |
H
AT
+-------+----------+--------+
| 102 | Kritika | 60000 |
| 103 | Shabbir | 45000 |
M
Query 4 Query: Display all details of employees from department D04 who earn more than 5000.
A
Output:
M
+-------+----------+--------+-------+--------+
| EmpNo | Ename | Salary | Bonus | DeptId |
+-------+----------+--------+-------+--------+
| 104 | Gurpreet | 19000 | 565 | D04 |
| 109 | Daribha | 42000 | NULL | D04 |
+-------+----------+--------+-------+--------+
Query 5
Query: Display all employee records except Aaliya.
Output:
+-------+----------+--------+-------+--------+
R
| EmpNo | Ename | Salary | Bonus | DeptId |
L
+-------+----------+--------+-------+--------+
| 102 | Kritika | 60000 | 123 | D01 |
N
| 103 | Shabbir | 45000 | 566 | D01 |
| 104 | Gurpreet | 19000 | 565 | D04 |
EE
| 105 | Joseph | 34000 | 875 | D03 |
| 106 | Sanya | 48000 | 695 | D02 |
| 107 | Vergese | 15000 | NULL | D01 |
H
AT
| 108 | Nachaobi | 29000 | NULL | D05 |
| 109 | Daribha | 42000 | NULL | D04 |
| 110 | Tanya | 50000 | 467 | D05 |
M
+-------+----------+--------+-------+--------+
ED
FROM EMPLOYEE
WHERE Salary BETWEEN 20000 AND 50000;
M
Output:
A
H
+----------+--------+
| Ename | DeptId |
O
+----------+--------+
M
| Shabbir | D01 |
| Joseph | D03 |
| Sanya | D02 |
| Nachaobi | D05 |
| Daribha | D04 |
| Tanya | D05 |
+----------+--------+
Query 7 Query: Employees from departments D01, D02, or D04 using OR:
Output:
R
L
+-------+----------+--------+-------+--------+
| EmpNo | Ename | Salary | Bonus | DeptId |
N
+-------+----------+--------+-------+--------+
| 101 | Aaliya | 10000 | 234 | D02 |
EE
| 102 | Kritika | 60000 | 123 | D01 |
| 103 | Shabbir | 45000 | 566 | D01 |
| 104 | Gurpreet | 19000 | 565 | D04 |
H
AT
| 106 | Sanya | 48000 | 695 | D02 |
| 107 | Vergese | 15000 | NULL | D01 |
| 109 | Daribha | 42000 | NULL | D04 |
M
+-------+----------+--------+-------+--------+
ED
(F) Using IN — Multiple Matching Values Purpose: The IN operator allows checking if a value
matches any value in a list.
M
Output:
H
O
+-------+----------+--------+-------+--------+
M
Query: Select all employees except those working in departments D01 or D02.
R
WHERE DeptId NOT IN ('D01', 'D02');
L
Output:
N
+-------+----------+--------+-------+--------+
EE
| EmpNo | Ename | Salary | Bonus | DeptId |
+-------+----------+--------+-------+--------+
| 104 | Gurpreet | 19000 | 565 | D04 |
| 105 | Joseph | 34000 | 875 | D03 |
H
AT
| 108 | Nachaobi | 29000 | NULL | D05 |
| 109 | Daribha | 42000 | NULL | D04 |
M
(G) Using IS NULL — Check for Missing Data Purpose: To check whether a column contains a
NULL (empty) value.
M
Output:
O
+-------+----------+-------+
M
Query: Select names of employees with bonus and working in department D01.
Output:
R
L
+----------+
| EName |
N
+----------+
EE
| Kritika |
| Shabbir |
+----------+
H
AT
(H) Using LIKE — Pattern Matching Purpose: The LIKE operator is used to match text patterns
using wildcards:
M
Output:
A
+----------+
H
| Ename |
O
+----------+
| Shabbir |
M
| Sanya |
+----------+
Output:
+----------+
| Ename |
+----------+
| Aaliya |
| Kritika |
| Sanya |
R
| Daribha |
L
| Tanya |
+----------+
N
EE
Query: Names containing ‘ya’
+--------+
M
| Ename |
+--------+
ED
| Sanya |
| Tanya |
M
+--------+
M
Output:
O
M
+-------+---------+--------+-------+--------+
| EmpNo | Ename | Salary | Bonus | DeptId |
+-------+---------+--------+-------+--------+
| 102 | Kritika | 60000 | 123 | D01 |
+-------+---------+--------+-------+--------+
Query: Select employees whose name ends with ‘a’ and earn salary > 45000.
Output:
+-------+--------+--------+-------+--------+
| EmpNo | Ename | Salary | Bonus | DeptId |
R
+-------+--------+--------+-------+--------+
| 102 | Kritika| 60000 | 123 | D01 |
L
| 106 | Sanya | 48000 | 695 | D02 |
| 110 | Tanya | 50000 | 467 | D05 |
N
+-------+--------+--------+-------+--------+
EE
Query: Select employees whose names are exactly 5 letters and have ‘ANYA’ starting from second
character.
H
AT
SELECT * FROM EMPLOYEE
WHERE Ename LIKE '_ANYA';
M
Output:
ED
+-------+-------+--------+-------+--------+
| EmpNo | Ename | Salary | Bonus | DeptId |
+-------+-------+--------+-------+--------+
M
+-------+-------+--------+-------+--------+
A
H
Purpose of ORDER BY The ORDER BY clause in SQL is used to sort the result set of a query by:
O
Basic Syntax:
Output:
+----------+--------+
R
| Ename | Salary |
+----------+--------+
L
| Aaliya | 10000 |
N
| Vergese | 15000 |
| Gurpreet | 19000 |
EE
| Joseph | 34000 |
| Nachaobi | 29000 |
| Shabbir | 45000 |
H
AT
| Daribha | 42000 |
| Sanya | 48000 |
| Tanya | 50000 |
M
| Kritika | 60000 |
+----------+--------+
ED
Output:
O
+----------+--------+
M
| Ename | Salary |
+----------+--------+
| Kritika | 60000 |
| Tanya | 50000 |
| Sanya | 48000 |
| Shabbir | 45000 |
| Daribha | 42000 |
| Joseph | 34000 |
| Nachaobi | 29000 |
| Gurpreet | 19000 |
| Vergese | 15000 |
| Aaliya | 10000 |
+----------+--------+
R
L
9.7 — Data Updation and Deletion
N
9.7.1 Data Updation Syntax:
EE
UPDATE table_name
SET column1 = value1, column2 = value2, ...
WHERE condition;
H
AT
Caution: Missing the WHERE clause will update all rows.
The student with roll number 3 is a sibling of student 5, so assign same GUID.
ED
Output:
M
Output:
After Update:
R
+--------------+---------------+------------+--------------------------------------+
L
| GUID | GName | GPhone | GAddress |
N
+--------------+---------------+------------+--------------------------------------+
| 444444444444 | Amit Ahuja | 5711492685 | G-35, Ashok Vihar, Delhi |
EE
| 111111111111 | Baichung B. | 7110047139 | Flat 5, Darjeeling Appt., Shimla |
| 101010101010 | Himanshu Shah | 9818184855 | 26/77, West Patel Nagar, Ahmedabad |
| 333333333333 | Danny Dsouza | NULL
| 466444444666 | Sujata P. H
| S -13, Ashok Village, Daman
| 9010810547 | WZ - 68, Azad Avenue, Bijnour, MP
|
|
AT
+--------------+---------------+------------+--------------------------------------+
M
Caution: Omitting WHERE will delete all records from the table.
M
Output:
O
M
After Deletion:
+------------+--------------+--------------+--------------+
| RollNumber | SName | SDateofBirth | GUID |
+------------+--------------+--------------+--------------+
| 1 | Atharv Ahuja | 2003-05-15 | 444444444444 |
| 3 | Taleem Shah | 2002-02-28 | 101010101010 |
| 4 | John Dsouza | 2003-08-18 | 333333333333 |
| 5 | Ali Shah | 2003-07-05 | 101010101010 |
| 6 | Manika P. | 2002-03-10 | 466444444666 |
R
+------------+--------------+--------------+--------------+
L
9.8: Functions in SQL
N
EE
Introduction Functions in SQL are predefined commands that perform operations on data. They are
used for:
• Performing calculations
H
AT
• Modifying strings
• Extracting date components
• Summarizing data
M
1. Single Row Functions (Scalar Functions): Operate on individual row values (return one result
per row)
2. Multiple Row Functions (Aggregate Functions): Work on groups of rows (return one result per
M
group)
M
• CUSTOMER
• EMPLOYEE
• INVENTORY
• SALE
R
L
1. Single Row (Scalar) Functions
N
A. Math Functions
EE
Function Description Example Output
1. GST Calculation:
M
3. Rounded Commission:
M
B. String Functions
R
LEFT(str,n) Leftmost n characters SELECT LEFT(‘Email’, 4); Emai
L
INSTR(s,sub)Position of substring in string SELECT 6
N
INSTR(‘Informatics’,‘ma’);
EE
TRIM() Remove leading/trailing/specific SELECT TRIM(‘.com’ FROM abc@gmail
chars ‘abc@[Link]’);
C. Date Functions
M
R
DAYNAME(‘2019-07-11’);
L
N
Examples with EMPLOYEE table:
EE
1. DOJ components:
3. Day of birth:
ED
FROM MANAGER;
M
COUNT(DISTINCT)
Unique values SELECT COUNT(DISTINCT Model) 6
FROM INVENTORY;
SUM() Total of numeric column SELECT SUM(Price) FROM 4608733.00
INVENTORY;
AVG() Average of numeric column SELECT AVG(Price) FROM 576091.625
INVENTORY;
R
Examples with INVENTORY/SALE tables:
L
1. Count cars with model VXI:
N
SELECT COUNT(*) FROM INVENTORY WHERE Model = 'VXI';
EE
2. Distinct models:
Basic Syntax:
A
FROM table_name
O
GROUP BY column_name;
M
Output:
+--------+------------------+
R
| CustID | Number of Cars |
+--------+------------------+
L
| C0001 | 2 |
N
| C0002 | 2 |
| C0003 | 1 |
EE
| C0004 | 1 |
+--------+------------------+
H
AT
Displays how many cars each customer bought
Output:
M
+----------+---------------------------+
| Model | COUNT(DISTINCT EmpID) |
A
+----------+---------------------------+
H
| LXI | 2 |
| VXI | 1 |
O
+----------+---------------------------+
M
Combines two tables using JOIN condition (implicit syntax), then groups
Output:
+--------------+----------+
| PaymentMode | COUNT(*) |
+--------------+----------+
| Cheque | 1 |
| Credit Card | 1 |
| Online | 1 |
R
+--------------+----------+
L
Finds frequency of each payment type
N
Display Customers Who Bought More Than 1 Car
EE
SELECT CustID, COUNT(*)
FROM SALE
GROUP BY CustID
HAVING COUNT(*) > 1; H
AT
Output:
M
+--------+----------+
| CustID | COUNT(*) |
ED
+--------+----------+
| C0001 | 2 |
M
| C0002 | 2 |
+--------+----------+
M
Displays customers and number of cars bought, but only if more than 1 car was purchased.
A
FROM SALE
M
GROUP BY PaymentMode
HAVING COUNT(*) > 1
ORDER BY PaymentMode;
Output:
+--------------+--------------------+
| PaymentMode | Count(PaymentMode) |
+--------------+--------------------+
| Bank Finance | 2 |
| Credit Card | 2 |
+--------------+--------------------+
Filters only those payment modes used more than once, after grouping all SALE records by Payment-
Mode.
R
9.10 – Operations on Relations
L
Introduction SQL allows operations that involve multiple tables (relations). These are called set
N
operations and work when:
EE
• Both tables have the same number of columns
• Corresponding columns have the same data types (domain compatibility)
1 Aastha 7A
2 Mahira 6A
3 Mohit 7B
4 Sanjay 7A
Table: MUSIC
1 Mehak 8A
2 Mahira 6A
3 Lavanya 7A
4 Sanjay 7A
R
5 Abhay 8A
L
9.10.1 – UNION ( ∪ ) Query:
N
SELECT * FROM DANCE
EE
UNION
SELECT * FROM MUSIC;
1 Aastha 7A
2 Mahira 6A
ED
3 Mohit 7B
4 Sanjay 7A
M
1 Mehak 8A
M
3 Lavanya 7A
A
5 Abhay 8A
H
O
2 Mahira 6A
4 Sanjay 7A
R
Finds students common to both DANCE and MUSIC
L
N
EE
9.10.3 – MINUS ( - ) Query:
1 Mehak 8A
3 Lavanya 7A
M
5 Abhay 8A
M
• Degree (columns): 6
• Cardinality (rows): 4 × 5 = 20 rows
1 Aastha 7A 1 Mehak 8A
1 Aastha 7A 2 Mahira 6A
… … … … … …
4 Sanjay 7A 5 Abhay 8A
R
Generates all possible combinations of students from both tables
L
N
For more information Visit:
EE
[Link]
H
AT
M
ED
M
M
A
H
O
M
The WHERE clause in SQL allows for selective retrieval of rows based on specific conditions, enhancing query precision and efficiency by filtering data according to criteria, such as specific values or ranges . Examples include retrieving employees from department D01 with SELECT * FROM EMPLOYEE WHERE DeptId = 'D01'; and selecting employees with a salary greater than 25000 using SELECT EmpNo, Ename, Salary FROM EMPLOYEE WHERE Salary > 25000; .
The IN operator in SQL checks if a value matches any value within a list, providing a succinct way to filter records based on multiple possible matches . It is preferred over multiple OR conditions as it simplifies queries, making them more readable and reduces the likelihood of errors. For example, selecting employees from departments D01, D02, or D04 can be done with SELECT * FROM EMPLOYEE WHERE DeptId IN ('D01', 'D02', 'D04'); instead of using separate OR clauses for each department .
The DISTINCT clause is used to eliminate duplicate records from query results, which is particularly useful in aggregating data for reporting or analysis where uniqueness is required . It impacts query results by showing only unique values in the columns specified, such as retrieving unique Department IDs with SELECT DISTINCT DeptId FROM EMPLOYEE;, preventing redundancy and often simplifying data interpretation .
SQL uses the LIKE operator for pattern matching to filter data based on partial matches rather than exact values, utilizing wildcards like % (zero or more characters) and _ (exactly one character). Benefits include flexible searches, enabling queries to identify records that meet complex criteria, such as searching for names starting with 'S' using SELECT Ename FROM EMPLOYEE WHERE Ename LIKE 'S%';. This enhances user capability in discovering trends and detailing granular data within large datasets .
ALTER TABLE is powerful for making structural changes without losing data, such as adding/removing columns, modifying data types, or changing constraints . The main advantage is flexibility in updating databases according to evolving data needs without restructuring the schema entirely. However, downsides include potential disruptions if used on large tables while being live, as well as increased complexity in ensuring proper integrity and performance are maintained during the changes .
A PRIMARY KEY uniquely identifies each row and requires that the values are both unique and not null, ensuring each row is distinguishable from others in the table . A UNIQUE constraint also enforces uniqueness for values in a column, but unlike a primary key, it allows null values. When used together by applying UNIQUE and NOT NULL, they effectively create a primary key if applied to a single column .
MySQL handles fixed-length character data using the CHAR data type, which always reserves the space specified (n characters) by padding unused space with spaces, which can be advantageous in cases requiring strict formatting or when minor disk usage variability is not an issue . In contrast, variable-length character data is handled by VARCHAR, which allocates only the space needed for actual characters, up to a defined maximum (n), saving storage space and potentially reducing memory and processing overhead in larger datasets .
The DROP statement is high-risk as it permanently deletes a table or database along with its data, structure, and constraints, making recovery impossible . Precautions before executing DROP include ensuring thorough backups of data and schema, double-checking the necessity of the action, and preferably performing the operation during maintenance windows to minimize the risk and impact of accidental data loss .
Constraints in SQL, like NOT NULL and FOREIGN KEY, enforce rules that maintain the accuracy and reliability of database data. NOT NULL ensures that a column cannot have null values, requiring meaningful data entries . FOREIGN KEY establishes links between tables, ensuring that relationships between datasets are maintained accurately. These constraints prevent data anomalies and uphold data integrity in relational databases by ensuring consistency and correctness in data entry .
A composite primary key is chosen when the uniqueness of a record in a database is determined by the combination of two or more columns rather than a single column. This is often used in associative tables that connect many-to-many relationships, such as between STUDENT and ATTENDANCE, where both date and roll number uniquely identify each attendance record . Unlike a single-column primary key, a composite key leverages multiple columns to manage complex database relationships, providing more granular control over record identification .