0% found this document useful (0 votes)
25 views105 pages

Primers -RDBMS My SQL

Uploaded by

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

Primers -RDBMS My SQL

Uploaded by

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

Primers - My SQL

Introduction to Database Management Systems (DBMS)

Traditional Data Storage Approaches

1. Manual Ledger System


○ Data stored in physical ledgers/books.
○ Prone to inefficiencies and errors.
2. File-Based System
○ Data moved to digital files (e.g., .txt, .csv) on computers.
○ Benefits: Better than manual storage initially.
○ Limitations:
■ Data Redundancy: Multiple copies of the same data across
locations.
■ Inconsistency: Edits in one file may not reflect in others,
leading to confusion.
■ Security Issues: Unauthorized access to misplaced files.
■ Limited Functionality: Poor support for multi-user access and
data distribution.
■ Scalability Problems: Difficult to manage large data volumes.

Evolution to DBMS

● Introduced in the 1970s to address file-based system limitations.


● DBMS centralized data storage in one repository, minimizing redundancy and
inconsistency.

Key Advantages of DBMS

1. Centralized Storage
○ Data stored in one location (centralized repository).
○ Supports multiple storage models:
■ Relational Model
■ Hierarchical Model
■ Network Model
2. Improved Data Security
○ Access restricted to authorized users.
○ Policies enforce strict control over data usage.
3. Reduced Redundancy and Inconsistency
○ Data stored once and accessed by all authorized users.
○ Eliminates multiple unsynchronized copies of data.
4. Multi-User Access
○ Simultaneous data access for multiple users from various locations.
5. Backup and Recovery
○ Advanced features for data backup and recovery in case of system
failures.
6. Flexibility and Scalability
○ Supports large volumes of data and dynamic processing needs.

Understanding Key Concepts

1. Data
○ Raw facts/details (e.g., a number, text, or image).
○ Example: 378-400-1234 could be a phone number or ID but is
meaningless without context.
2. Information
○ Data becomes meaningful when given context (e.g., storing
378-400-1234 as a phone number).
3. Records
○ Logical fields containing items of information grouped together (e.g.,
customer details: name, phone, address).

File Management System (FMS) vs. DBMS


Aspect File Management System Database Management
System

Data Structure Flat files, no relationships. Centralized with structured


relationships.

Redundancy High redundancy (duplicate Reduced redundancy.


data).

Consistency Low consistency; files not High consistency;


synchronized. centralized updates.

Security Weak security; files prone to Strong security features.


unauthorized access.

Multi-User Limited or no multi-user access. Allows simultaneous


Access multi-user access.
Backup & Lacks robust backup/recovery Provides backup and
Recovery options. recovery mechanisms.

Flexibility Limited functionality and High flexibility and


scalability. processing power.

Modern DBMS Capabilities

1. Greater flexibility and processing power.


2. Efficient storage and retrieval of large volumes of data.
3. Multi-user, simultaneous access.
4. Backup and recovery controls.
5. Advanced security features.

Entity-Relationship (ER) Model and Normalization

Introduction to ER Model

1. Key Concepts:
○ Entities: Real-world objects or things represented in a database.
■ Example: John Doe (Employee), Sales (Department).
○ Attributes: Properties describing an entity.
■ Example: Name, ID, Address, DOB.
■ Simple Attributes: Single atomic values (e.g., ID).
■ Composite Attributes: Made of components (e.g., Address =
Street + City + Zip).
2. Entity Type:
○ Grouping of entities sharing similar attributes.
○ Example: Employee with attributes like Name, Address, and Age.
3. Key Attributes:
○ Unique Identifiers: Distinguish each entity instance (e.g., Employee
ID).
○ Composite Keys: Combination of attributes ensuring uniqueness
(e.g., Dept No + Employee No).
4. Relationships:
○ Link Between Entities: E.g., John works in Sales.
○ Relationship Type: Grouping of similar relations (e.g., Works In).
○ Degree of Relationship: Number of participating entities:
■ Binary: Two entities (e.g., Employee-Department).
■ Cardinality:
■ 1:1: One employee works in one department.
■ 1:N: One employee works in multiple departments.
■ M:N: Multiple employees work on multiple projects.
■ Optionality: Determines if relationships are mandatory or
optional.
5. ER Diagram Components:
○ Entities: Represented by rectangles.
○ Relationships: Lines connecting entities, labeled with the relationship
name.
○ Cardinality: Crowfoot notation (1:1, 1
,M
).
○ Optionality: Marked as O for optional or vertical line for mandatory.

Normalization

1. Definition: Process of organizing data to minimize redundancy and avoid


anomalies (update, insertion, deletion).
○ Ensures database flexibility and optimized design.
2. Key Steps in Normalization:
○ Group entities and attributes.
○ Remove repeating groups of data.
○ Assign unique keys to entities.
3. Normal Forms:
○ First Normal Form (1NF):
■ Eliminate repeating groups.
■ Create new entities linked by 1
relationships.
■ Example: Orders and items in Order 7623 linked by 1
relation.
○ Second Normal Form (2NF):
■ Remove partial dependencies (attributes dependent on part of a
composite key).
■ Example: Split Items Purchase table into:
■ Part Order: Attributes fully dependent on Order
Number + Item.
■ Price: Attributes dependent only on Item.
○ Third Normal Form (3NF):
■ Eliminate transitive dependencies (non-key attributes dependent
on each other).
■ Example: Separate Customer details from Account details.
Denormalization

1. Definition: Process of optimizing database performance by intentionally


adding redundant data.
2. Purpose: To improve query speed at the cost of storage efficiency.

Conclusion

● ER Model: Defines the structure and relationships of data in the database.


● Normalization: Reduces redundancy and anomalies for better database
design.
● Both contribute to efficient, scalable, and secure database systems.

What is DDL?

● DDL (Data Definition Language) manages database structure and objects.


● Common operations:
○ CREATE TABLE: Create a new table.
○ ALTER TABLE: Modify an existing table (add, rename, or drop
columns).
○ TRUNCATE TABLE: Remove all data while retaining table structure.
○ DROP TABLE: Remove the table and its structure permanently.
○ RENAME TABLE: Rename an existing table.

Key DDL Statements:

1. CREATE TABLE

Syntax:
sql
Copy code
CREATE TABLE table_name (

column1 data_type [size],

column2 data_type [size],

...
);

Example:
sql
Copy code
CREATE TABLE student (

student_id INT,

student_name VARCHAR(20),

address VARCHAR(50),

department_id CHAR(2)

);

2. ALTER TABLE

Add columns:
sql
Copy code
ALTER TABLE table_name ADD column_name data_type [AFTER
existing_column];

Example: Add date_of_birth after student_name:


sql
Copy code
ALTER TABLE student ADD date_of_birth DATE AFTER student_name;

Drop columns:
sql
Copy code
ALTER TABLE table_name DROP COLUMN column_name;

Example: Drop address:


sql
Copy code
ALTER TABLE student DROP COLUMN address;

Modify column data type:


sql
Copy code
ALTER TABLE table_name MODIFY column_name data_type [size];

Example: Change student_name size from 20 to 50:


sql
Copy code
ALTER TABLE student MODIFY student_name VARCHAR(50);

Rename columns:
sql
Copy code
ALTER TABLE table_name CHANGE old_column_name new_column_name
data_type;

Example: Rename st_name to student_name:


sql
Copy code
ALTER TABLE student CHANGE st_name student_name VARCHAR(50);

3. DROP TABLE

Removes the table entirely:


sql
Copy code
DROP TABLE table_name;

Example:
sql
Copy code
DROP TABLE student;

4. RENAME TABLE
Rename the table:
sql
Copy code
RENAME TABLE old_table_name TO new_table_name;

Example:
sql
Copy code
RENAME TABLE student TO participant;

5. TRUNCATE TABLE

Removes all data but retains structure:


sql
Copy code
TRUNCATE TABLE table_name;

Example:
sql
Copy code
TRUNCATE TABLE participant;

Additional Notes:

Primary Key Addition: After creating a table, you can add a primary key:
sql
Copy code
ALTER TABLE table_name ADD PRIMARY KEY (column_name);

1.
2. Checking Table Structure: Use DESCRIBE table_name to view columns,
data types, and constraints.
3. Saving Scripts: Query scripts can be saved and executed as a whole or
selectively.
4. Execution: Use MySQL Workbench’s interface to run individual or multiple
queries.
Creating a Table with a Primary Key

1. Defining a Primary Key During Table Creation:


○ Use a comma to separate the column definitions.

Syntax example:
sql
Copy code
CREATE TABLE table_name (

column_name datatype,

PRIMARY KEY (primary_key_column)

);


2. Using Constraints for Primary Keys:
○ You can explicitly define a constraint for the primary key.

Syntax example:
sql
Copy code
CREATE TABLE table_name (

column_name datatype,

CONSTRAINT constraint_name PRIMARY KEY


(primary_key_column)

);


3. Importance of Naming Constraints:
○ Naming constraints is recommended because:
■ It avoids the system assigning a default name.
■ Makes management tasks, such as dropping constraints,
easier.
○ Without a named constraint, you would need to query the metadata to
find the auto-generated constraint name.
4. Dropping a Named Constraint:
○ Using a named constraint simplifies dropping it later.

Example:
sql
Copy code
ALTER TABLE table_name

○ DROP CONSTRAINT constraint_name;

DDL Statements: CREATE TABLE

1. Purpose:
○ The CREATE TABLE statement is used in SQL to create a table within
a schema or database.

Basic Syntax:
sql
Copy code
CREATE TABLE table_name (

column_name1 datatype(size),

column_name2 datatype(size),

...

);

2.
○ Steps:
1. Start with CREATE TABLE followed by the table_name.
2. Define the columns and their properties (e.g., datatype, size)
within parentheses.
3. Use commas to separate column definitions, except after the
last column.
3. Defining a Primary Key:

Add a PRIMARY KEY constraint to a column directly:


sql
Copy code
column_name datatype(size) PRIMARY KEY,

Example:
sql
Copy code
CREATE TABLE table_name (

column1 INT PRIMARY KEY,

column2 VARCHAR(30)

);


4. Adding a Foreign Key:

Define the foreign key at the end of column definitions:


sql
Copy code
FOREIGN KEY (column_name) REFERENCES
referenced_table(referenced_column),


○ The referenced column must be a primary key in the other table.

Example:
sql
Copy code
CREATE TABLE staff (

staff_id INT PRIMARY KEY,

staff_name VARCHAR(30),

department_id INT,

FOREIGN KEY (department_id) REFERENCES


department(department_id)

);


5. Constraints Overview:
○ Primary Key: Ensures unique, non-null values for the specified
column(s).
○ Foreign Key: Establishes a link between two tables, referencing the
primary key of another table.
○ Syntax:
1. Primary Key: Directly with the column or using CONSTRAINT.
2. Foreign Key: Add at the end of column definitions.
6. Tips:
○ Use descriptive names for constraints to simplify dropping or modifying
them later.

Example with named constraints:


sql
Copy code
CREATE TABLE staff (

staff_id INT,

staff_name VARCHAR(30),

department_id INT,

CONSTRAINT pk_staff PRIMARY KEY (staff_id),

CONSTRAINT fk_department FOREIGN KEY (department_id)


REFERENCES department(department_id)

);


7. Practical Demo:
○ Task: Create a staff table with the following specifications:
1. staff_id: Integer, Primary Key.
2. staff_name: VARCHAR(30).
3. department_id: Integer, Foreign Key referencing
department(department_id).

Code:
sql
Copy code
CREATE TABLE staff (

staff_id INT PRIMARY KEY,

staff_name VARCHAR(30),

department_id INT,

FOREIGN KEY (department_id) REFERENCES


department(department_id)
);


○ Steps to execute:
1. Write the query in the editor.
2. Compile to check for syntax errors.
3. Evaluate for successful execution.

DDL Statement: ALTER TABLE

1. Purpose:
○ The ALTER TABLE statement modifies an existing table in a schema
or database.

Basic Syntax:
sql
Copy code
ALTER TABLE table_name

<modification_clause>;

2.
○ Replace <modification_clause> with the desired action (e.g.,
adding, dropping, or modifying a column).
3. Use Cases for ALTER TABLE:
○ Add a Column:
1. Add a new column to the table.

Syntax:
sql
Copy code
ALTER TABLE table_name

ADD column_name datatype(size);

2.

Example:
sql
Copy code
ALTER TABLE busses

ADD AC_available VARCHAR(10);

3.
○ Drop a Column:
1. Remove an existing column from the table.

Syntax:
sql
Copy code
ALTER TABLE table_name

DROP COLUMN column_name;

2.

Example:
sql
Copy code
ALTER TABLE busses

DROP COLUMN AC_available;

3.
○ Modify a Column:
1. Change the data type or size of an existing column.

Syntax:
sql
Copy code
ALTER TABLE table_name

MODIFY column_name new_datatype(new_size);

2.

Example:
sql
Copy code
ALTER TABLE busses

MODIFY AC_available CHAR(5);

3.
○ Rename a Column:
1. Rename an existing column and define its datatype.

Syntax:
sql
Copy code
ALTER TABLE table_name

CHANGE old_column_name new_column_name datatype(size);

2.

Example:
sql
Copy code
ALTER TABLE employee

CHANGE Name Employee_Name VARCHAR(50);

3.
4. Example Task:
○ Problem: Add a new column AC_available of type VARCHAR(10) to
the busses table.

Solution:
sql
Copy code
ALTER TABLE busses

ADD AC_available VARCHAR(10);


○ Steps:
1. Write the query in the code editor.
2. Save and compile to check for errors.
3. Evaluate for successful execution.
5. Key Points:
○ Use ADD for new columns.
○ Use DROP COLUMN for removing columns (enclose multiple column
names in parentheses if needed).
○ Use MODIFY to adjust data types or sizes.
○ Use CHANGE to rename columns and redefine their properties.

DML (Data Manipulation Language):

Data Manipulation Language (DML)

1. Definition:
○ DML is used to manipulate data within database objects such as
tables. Once the structure (schema) of the database is created, DML
commands handle data insertion, updates, and deletions.
2. Primary DML Commands:
○ INSERT: Adds new rows to a table.
○ UPDATE: Modifies existing data in one or more rows.
○ DELETE: Removes rows based on a condition, or all rows if no
condition is specified.
3. Overview of DML Commands:
○ INSERT Command:
■ Adds data to a table.

Syntax:
sql
Copy code
INSERT INTO table_name (column1, column2, ...)

VALUES (value1, value2, ...);

Example:
sql
Copy code
INSERT INTO students (id, name, age)

VALUES (101, 'Alice', 20);


○ UPDATE Command:
■ Modifies existing data.

Syntax:
sql
Copy code
UPDATE table_name

SET column1 = value1, column2 = value2, ...

WHERE condition;

Example:
sql
Copy code
UPDATE students

SET age = 21

WHERE id = 101;


■ Note: Omitting the WHERE clause updates all rows in the table.
○ DELETE Command:
■ Removes specific rows or all rows from a table.

Syntax:
sql
Copy code
DELETE FROM table_name

WHERE condition;

Example:
sql
Copy code
DELETE FROM students

WHERE age > 20;

Without a WHERE clause, it deletes all rows in the table:


sql
Copy code
DELETE FROM students;


4. TRUNCATE vs. DELETE:
○ TRUNCATE:
■ Removes all rows from a table but retains its structure.
■ Faster than DELETE as it doesn’t log individual row deletions.
■ Not a DML command; it’s a DDL command.
○ DELETE:
■ Allows conditional row deletion.
■ Logs each row deletion, which is slower for large datasets.
5. Key Takeaways:
○ Use INSERT to populate tables.
○ Use UPDATE for modifying specific rows.
○ Use DELETE cautiously, especially without a WHERE clause.
○ Use TRUNCATE when you want to clear all rows quickly without
retaining transactional logs.

Data Manipulation Language (DML)

1. Definition:
○ DML is used to manipulate data within database objects like tables.
○ Common operations include INSERT, UPDATE, and DELETE.

DML Commands and Syntax:

1. INSERT:
○ Used to add records to a table.

Syntax:
sql
Copy code
INSERT INTO table_name (column1, column2, ...)

VALUES (value1, value2, ...);

Example:
sql
Copy code
INSERT INTO customer (customer_id, name, dob)

VALUES (101, 'John Doe', '1990-05-15');


○ Notes:
■ Date, CHAR, and VARCHAR values must be enclosed in single
quotes (').
■ To insert data into specific columns, mention their names in
parentheses.
2. UPDATE:
○ Used to modify existing records in a table.
Syntax:
sql
Copy code
UPDATE table_name

SET column1 = value1, column2 = value2, ...

WHERE condition;

Example:
sql
Copy code
UPDATE customer

SET email = '[email protected]'

WHERE customer_id = 101;


○ Notes:
■ Without a WHERE clause, all rows in the table will be updated.
3. DELETE:
○ Used to remove records from a table.

Syntax:
sql
Copy code
DELETE FROM table_name

WHERE condition;

Example:
sql
Copy code
DELETE FROM customer

WHERE customer_id = 101;


○ Notes:
■ Without a WHERE clause, all rows in the table will be deleted.
■ Foreign Key Constraints:
■ ON DELETE CASCADE: Deletes parent and child rows.
■ ON DELETE SET NULL: Sets foreign key in child rows to
NULL when the parent is deleted.
■ RESTRICT (default): Prevents deletion if the record has
dependencies.

Comparison: DELETE vs. TRUNCATE

DELETE TRUNCATE

DML command DDL command

Deletes specific rows Removes all rows

Logs individual Does not log


deletions deletions

Retains table structure Retains table


structure

Allows WHERE No conditional


condition deletion

Transaction Control:

1. ACID Properties:
○ Atomicity: Transactions are all-or-nothing.
○ Consistency: Ensures data validity.
○ Isolation: Prevents interference between transactions.
○ Durability: Changes persist even after failures.
2. Key Commands:
○ COMMIT:
■ Saves changes permanently.

Syntax:
sql
Copy code
COMMIT;


○ ROLLBACK:
■ Undoes changes made in the current transaction.

Syntax:
sql
Copy code
ROLLBACK;


○ SAVEPOINT:
■ Sets a marker in a transaction to rollback to a specific point.

Syntax:
sql
Copy code
SAVEPOINT savepoint_name;

ROLLBACK TO savepoint_name;


3. Transaction Behavior:
○ Start: A transaction begins when a DML statement is executed.
○ End: Must end with COMMIT or ROLLBACK.
○ DDL Commands: Auto-commit by default.

Locking Mechanisms:

1. Purpose:
○ Ensures data integrity and prevents conflicts between transactions.
2. Types of Locks:
○ Explicit Locking: Manually applied by users.
○ Implicit Locking: Automatically handled by the database.
3. Lock Modes:
○ Exclusive Lock: Prevents other users from accessing the data.
○ Shared Lock: Allows multiple users to read data but restricts
modifications.
4. Lock Behavior:
○ For INSERT, UPDATE, and DELETE: A shared lock is applied on the
table, and an exclusive lock is applied on the row.
○ For SELECT: No lock is required.
○ For DDL: Locks the object definition.
5. Lock Duration:
○ Locks are retained until a COMMIT or ROLLBACK is issued.

Key Takeaways:

● Use INSERT to populate tables, UPDATE to modify records, and DELETE to


remove them.
● Always use COMMIT or ROLLBACK to manage transaction permanency.
● Understand the implications of locking to avoid deadlocks and improve
concurrency.
● Leverage foreign key constraints like ON DELETE CASCADE and ON DELETE
SET NULL for referential integrity.

Overview of DML Statements

DML (Data Manipulation Language) is used to manipulate data in existing database


tables. The three primary commands demonstrated are:

1. INSERT: Add new data into a table.


2. UPDATE: Modify existing data in a table.
3. DELETE: Remove specific or all rows from a table.

1. INSERT Statement

Used to add data to a table.

Syntax 1: Specify Columns

sql

Copy code

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

VALUES (value1, value2, ...);


● This method is used when you want to insert values into specific columns.

Example:
sql
Copy code
INSERT INTO employee (id, name, department)

VALUES (101, 'John', 'IT');


● Notes:
○ You must specify values for columns defined as NOT NULL.
○ If the table contains nullable columns, you can omit them.

Syntax 2: Without Specifying Columns

sql

Copy code

INSERT INTO table_name

VALUES (value1, value2, ...);

● Use this method only if you know the exact structure and order of columns in
the table.

Example:
sql
Copy code
INSERT INTO employee

VALUES (102, 'Jane', 'HR');

2. UPDATE Statement

Used to modify existing data in a table.

Syntax
sql

Copy code

UPDATE table_name

SET column_name = value

[WHERE condition];

● Without WHERE Clause:


○ Updates all rows in the table.

Example:
sql
Copy code
UPDATE employee

SET salary = 50000;


● With WHERE Clause:
○ Updates specific rows based on a condition.

Example:
sql
Copy code
UPDATE employee

SET salary = 60000

WHERE department = 'IT';

Conditional Updates

● Allows updates only for rows meeting a specific condition.

Example:
sql
Copy code
UPDATE employee
SET salary = 70000

WHERE department = 'HR' AND experience > 5;

3. DELETE Statement

Used to remove data from a table.

Syntax

sql

Copy code

DELETE FROM table_name

[WHERE condition];

● Without WHERE Clause:


○ Deletes all rows in the table.

Example:
sql
Copy code
DELETE FROM employee;


○ Warning: This clears the table but retains its structure.
● With WHERE Clause:
○ Deletes specific rows based on a condition.

Example:
sql
Copy code
DELETE FROM employee

WHERE department = 'HR';

Use Case Example


Deleting all employees from a specific department:
sql
Copy code
DELETE FROM employee

WHERE department = 'Sales';

Key Highlights

● INSERT:
○ Use column names when inserting values selectively.
○ Be cautious of constraints like NOT NULL.
● UPDATE:
○ Can update all rows or a subset of rows with a condition.
○ Ensure correct use of WHERE to avoid unintended modifications.
● DELETE:
○ Deletes data but not the structure of the table.
○ Use WHERE to target specific rows; otherwise, all rows are removed.

DEMO - INSERT:

process for inserting multiple records into a department table as described:

Task Description

Insert three records into the department table based on the schema provided.

Table Schema

Column Data Type Description

department_ Integer Unique identifier for the department.


id
department_ VARCHA Name of the department.
name R

block_numbe Integer The block number where the department is


r located.

Steps to Insert Records

Step 1: Analyze the Input Data

● Record 1: department_id = 1, department_name = 'CSE',


block_number = 1
● Record 2: department_id = 2, department_name = 'ECE',
block_number = 2
● Record 3: department_id = 3, department_name = 'MECH',
block_number = 3

Step 2: SQL Statements

For inserting data, use the INSERT INTO statement. Since all columns are being
filled, column names can be omitted.

sql

Copy code

INSERT INTO department VALUES (1, 'CSE', 1);

INSERT INTO department VALUES (2, 'ECE', 2);

INSERT INTO department VALUES (3, 'MECH', 3);

Step 3: Code Execution

1. Open the code editor in your platform.


2. Enter the above SQL commands.
3. Ensure each statement is terminated with a semicolon (;) to execute them as
separate commands.
Step 4: Test the Query

1. Save and run the script.


2. Evaluate the execution status. If completed successfully, all records will be
inserted into the table.

Validation

Once executed:

Check the table using a SELECT query to confirm the data was added:
sql
Copy code
SELECT * FROM department;


● The output should display:

departmen department_ block_num


t_id name ber

1 CSE 1

2 ECE 2

3 MECH 3

Best Practices

1. Semicolon Usage: Always terminate SQL statements with ; to avoid syntax


errors.
2. Syntax Accuracy: Verify table and column names match the schema.
3. Validation: Use SELECT queries post-insertion to confirm the accuracy of the
data.
DEMO - UPDATE:

how to update specific rows in the schedule table by adding 5 days to the
travel_date for specific conditions:

Task Description

Goal: Update the travel_date for rows in the schedule table where:

● source = 'Chennai'
● destination = 'Bangalore'

Table Schema

Column Data Type Description

schedule Integer Unique identifier for the schedule.


_id

travel_d Date Date of travel.


ate

source VARCHA Source location of the bus.


R

destinat VARCHA Destination location of the bus.


ion R

bus_numb Integer Bus number assigned to the


er schedule.

duration Integer Duration of the trip (hours).


Steps to Perform the Update

Step 1: Analyze the Update Requirement

● Modify the travel_date by adding 5 days (+ 5).


● Conditions: Apply only to rows where:
○ source = 'Chennai'
○ destination = 'Bangalore'

Step 2: Write the SQL Query

Use the UPDATE statement to update specific rows. The WHERE clause ensures only
the targeted rows are updated.

sql

Copy code

UPDATE schedule

SET travel_date = travel_date + INTERVAL 5 DAY

WHERE source = 'Chennai' AND destination = 'Bangalore';

Step 3: Execution on the Platform

1. Open the Code Editor: Navigate to the editor on your platform.


2. Input the Query: Enter the above SQL statement.
3. Execute the Query: Run the script to apply the changes.

Validation

Post-update, verify the changes using a SELECT query:

sql

Copy code

SELECT * FROM schedule


WHERE source = 'Chennai' AND destination = 'Bangalore';

● The travel_date for the filtered rows should now reflect the original date
plus 5 days.

Best Practices

Test on a Subset of Data: Use a SELECT query first to ensure the correct rows are
identified:
sql
Copy code
SELECT * FROM schedule

WHERE source = 'Chennai' AND destination = 'Bangalore';

1.
2. Backup Data: If working on production databases, back up the data before
performing updates.
3. Format Dates Correctly: Ensure the travel_date column uses a
compatible date format for arithmetic operations.

Key Notes

● Condition Importance: Without the WHERE clause, the update applies to all
rows in the table.
● SQL Syntax: The addition of INTERVAL 5 DAY ensures compatibility with
standard SQL date arithmetic.

DEMO - DELETE:

how you can delete specific rows from a table based on a condition using SQL.
This example focuses on deleting rows from the payments table where the
discount_id matches 'd1'.

Task Description

Goal: Delete all records from the payments table where:


● discount_id = 'd1'

Steps to Perform the Delete Operation

Step 1: Analyze the Table

The payments table includes the following relevant column:

● discount_id: This column stores the discount coupon IDs used during
payment. The data is case-sensitive.

Step 2: Write the SQL Query

Use the DELETE statement with a WHERE clause to ensure only specific rows are
deleted.

DELETE FROM payments

WHERE discount_id = 'd1';

Execution on the Platform

1. Open the Code Editor: Navigate to the SQL code editor on your platform.

Input the Query:


sql

DELETE FROM payments

WHERE discount_id = 'd1';

○ Note the use of single quotes for the discount_id value.


2. Execute the Query: Run the script.

Validation
After execution, validate the changes by querying the table to confirm that no records
with discount_id = 'd1' remain:

sql

SELECT * FROM payments

WHERE discount_id = 'd1';

If the query returns no results, the deletion was successful.

Important Notes

1. Case Sensitivity: Ensure the discount_id is matched exactly as it appears


in the table, considering case sensitivity.
2. Avoid Accidental Deletion: Always include a WHERE clause in DELETE
statements to prevent unintended deletions of all rows.
3. Backup Data: If working with production data, back up the table before
executing the delete operation.

Key SQL Concepts

● DELETE Statement: Used to remove rows from a table.


● WHERE Clause: Specifies conditions to determine which rows should be
deleted.
● Semicolon: Ends the SQL statement.

Example Workflow

1.Write the query:

DELETE FROM payments

WHERE discount_id = 'd1';

2.Save and execute.


3.Validate with:
SELECT * FROM payments

WHERE discount_id = 'd1';

Understanding the SELECT Statement in SQL

The SELECT statement is one of the most commonly used and essential SQL
commands. Unlike other DML statements like INSERT, UPDATE, and DELETE, which
modify data, the SELECT statement is primarily used to retrieve data from tables.
Although it is considered a part of the DML family, it does not manipulate the data
but rather queries it.

Basic SELECT Statement

The simplest form of the SELECT statement retrieves all columns and rows from a
table:

sql

Copy code

SELECT * FROM table_name;

● *: Denotes all columns in the table.

Example:
sql
Copy code
SELECT * FROM employees;

● This retrieves all data from the employees table.

Specific Columns Selection

To fetch only certain columns, list the column names in the SELECT clause:

sql
Copy code

SELECT column1, column2 FROM table_name;

Example:
sql
Copy code
SELECT first_name, last_name FROM employees;

● This retrieves only the first_name and last_name columns from the
employees table.

Conditional Selection (Using WHERE)

To filter rows based on conditions, use the WHERE clause:

sql

Copy code

SELECT column1, column2 FROM table_name WHERE condition;

Example:
sql
Copy code
SELECT first_name, last_name FROM employees WHERE
department_id = 10;

● This retrieves names of employees in department 10.

Ordering Results

Use the ORDER BY clause to sort the query results:

sql

Copy code
SELECT column1, column2 FROM table_name ORDER BY column_name
[ASC|DESC];

Example:
sql
Copy code
SELECT first_name, last_name FROM employees ORDER BY last_name
ASC;

● This sorts employees by their last names in ascending order.

Limiting Results

To fetch a specific number of rows, use LIMIT (or TOP in some SQL dialects):

sql

Copy code

SELECT column1, column2 FROM table_name LIMIT number_of_rows;

Example:
sql
Copy code
SELECT first_name, last_name FROM employees LIMIT 5;

● This retrieves the first 5 rows from the employees table.

Combining Conditions (AND, OR)

You can combine multiple conditions in a WHERE clause using logical operators:

sql

Copy code

SELECT column1, column2 FROM table_name WHERE condition1 AND


condition2;
SELECT column1, column2 FROM table_name WHERE condition1 OR
condition2;

Example:
sql
Copy code
SELECT first_name, last_name FROM employees WHERE
department_id = 10 AND salary > 5000;

Aggregations and Functions

The SELECT statement supports aggregate functions like COUNT, SUM, AVG, MAX,
and MIN:

sql

Copy code

SELECT COUNT(*) FROM employees;

SELECT AVG(salary) FROM employees;

SELECT department_id, SUM(salary) FROM employees GROUP BY


department_id;

Advanced Queries

Join Operations: Combine data from multiple tables.


sql
Copy code
SELECT e.first_name, d.department_name

FROM employees e

JOIN departments d ON e.department_id = d.department_id;


1.

Subqueries: Nest a query within another.


sql
Copy code
SELECT first_name, last_name FROM employees

WHERE department_id = (SELECT department_id FROM departments


WHERE department_name = 'HR');

2.

Key Points About SELECT

● Retrieves data but does not modify it.


● Can handle simple queries (e.g., all rows) or complex ones (e.g., joins,
subqueries, and aggregations).
● It is the foundation for working with data in SQL.

Welcome to the SQL SELECT Statement Module!

This module introduces the SQL SELECT statement, a fundamental part of


querying data in relational databases. Throughout this module, we will use an
insurance management system database, which consists of three primary tables:

1. Customer table: Stores customer information.


2. Policy table: Stores policy details.
3. Policy enrollment table: Tracks which policies have been purchased by
which customers.

Let’s dive into the key concepts covered in this module.

1. The SQL SELECT Statement

The SELECT statement is used to fetch data from a database table. This operation
is often referred to as Data Retrieval Language (DRL) or Data Query Language
(DQL).

Capabilities of the SELECT Statement:

● Retrieve all rows from a table.


● Retrieve specific rows that match a condition.
● Retrieve specific columns or expressions.
● Retrieve data from one or more tables.

Basic Syntax:

sql

Copy code

SELECT column1, column2 FROM table_name;

To retrieve all columns:

sql

Copy code

SELECT * FROM table_name;

Case Sensitivity:

● SQL statements are not case-sensitive. For example, SELECT and select
are treated the same.
● Data stored in the database is case-sensitive. For instance, "Tom" and
"tom" are treated as different values.

2. Retrieving Specific Columns

You can select specific columns from a table by listing their names in the SELECT
clause:

sql

Copy code

SELECT customer_name, customer_address FROM customer;

3. Using Arithmetic Expressions


The SELECT statement supports arithmetic operations to perform calculations on
data. For example:

sql

Copy code

SELECT policy_amount + (policy_amount * 0.10) AS total_amount


FROM policy;

● This calculates the policy amount including a 10% GST.


● The result column can be renamed using an alias (AS total_amount).

4. Concatenating Strings

To combine columns or strings, use the concatenation operator (||):

sql

Copy code

SELECT customer_name || ', ' || customer_address AS


customer_info FROM customer;

● This displays customer names along with their addresses in a single column.

5. Eliminating Duplicates with DISTINCT

The DISTINCT keyword removes duplicate rows in the query results:

sql

Copy code

SELECT DISTINCT customer_city FROM customer;


6. Filtering Data with WHERE Clause

The WHERE clause filters rows based on specified conditions.

Example:

Retrieve customers from Chennai:

sql

Copy code

SELECT * FROM customer WHERE customer_city = 'Chennai';

Operators Used in WHERE Clause:

● Comparison Operators:
○ <, >, <=, >=, =

Example:
sql
Copy code
SELECT * FROM policy WHERE minimum_amount < 1500;


● LIKE: Used for pattern matching.

Example:
sql
Copy code
SELECT * FROM customer WHERE customer_name LIKE 'A%'; -- Names
starting with 'A'


● BETWEEN: Selects values within a range.

Example:
sql
Copy code
SELECT * FROM policy WHERE minimum_amount BETWEEN 1000 AND
2000;


● IN: Matches any value in a list.
Example:
sql
Copy code
SELECT * FROM customer WHERE customer_city IN ('Chennai',
'Bangalore');


● IS NULL: Checks for NULL values.

Example:
sql
Copy code
SELECT * FROM policy WHERE policy_description IS NULL;

7. Combining Conditions

Use logical operators (AND, OR, NOT) to combine multiple conditions:

Example:
sql
Copy code
SELECT * FROM policy WHERE minimum_amount < 1500 AND
policy_type = 'Health';

8. Sorting Results with ORDER BY

The ORDER BY clause sorts query results in ascending (default) or descending


order:

Example (Ascending):
sql
Copy code
SELECT * FROM customer ORDER BY customer_name;


Example (Descending):
sql
Copy code
SELECT * FROM customer ORDER BY customer_name DESC;

Summary

In this module, we explored:

1. The SELECT statement and its capabilities.


2. How to retrieve data using the WHERE clause and various operators.
3. Techniques for sorting and eliminating duplicate records using ORDER BY
and DISTINCT.
4. Using arithmetic expressions, aliases, and string concatenation in queries.

Practice Task

Try writing a query to retrieve all policies with a minimum amount greater than 2000,
sorted by their policy name in descending order.

sql

Copy code

SELECT policy_name, minimum_amount FROM policy

WHERE minimum_amount > 2000

ORDER BY policy_name DESC;

SQL Clauses and Their Order of Execution

1. FROM Clause: Specifies the table or view to retrieve data from.


○ Example: SELECT * FROM employees;
2. WHERE Clause: Filters rows based on conditions (supports AND, OR, and
BETWEEN).
○ Example: SELECT * FROM employees WHERE salary > 15000;
3. GROUP BY Clause: Aggregates data based on columns.
○ Example: SELECT department_id, AVG(salary) FROM
employees GROUP BY department_id;
4. HAVING Clause: Filters grouped data.
○ Example: SELECT department_id FROM employees GROUP BY
department_id HAVING AVG(salary) > 20000;
5. SELECT Clause: Specifies the columns to retrieve.
○ Example: SELECT name, salary FROM employees;
6. ORDER BY Clause: Sorts the result set.
○ Example: SELECT * FROM employees ORDER BY salary DESC;

Practical Query Demonstrations

1. Filtering Rows

● Single condition:
SELECT * FROM employees WHERE salary > 15000;
● Multiple conditions with logical operators:
SELECT * FROM employees WHERE salary > 10000 AND
commission < 30000;

2. Removing Duplicates

● Use DISTINCT:
SELECT DISTINCT department_id FROM employees;

3. Combining Queries

UNION: Combines results while removing duplicates.


Example:
sql
Copy code
SELECT name FROM employees WHERE salary > 15000

UNION

SELECT name FROM employees WHERE department_id = 5001;


● UNION ALL: Combines results without removing duplicates.

4. Range Conditions

Use BETWEEN:
sql
Copy code
SELECT * FROM employees WHERE salary BETWEEN 12000 AND 18000;

5. Sorting

Order results:
sql
Copy code
SELECT name, salary FROM employees ORDER BY salary DESC;

6. Prioritizing Conditions

Parentheses to enforce precedence:


sql
Copy code
SELECT * FROM employees

WHERE (salary > 15000 OR commission < 20000) AND department_id


= 5002;

7. Intersect-like Functionality

Use EXCEPT for a "difference" operation:


sql
Copy code
SELECT name FROM employees WHERE department_id = 5001

EXCEPT

● SELECT name FROM employees WHERE salary < 15000;

Key Points About the SQL SELECT Statement:

1. Basic Syntax:

General Form:
sql
Copy code
SELECT column1, column2, ...
FROM table_name

WHERE condition(s);


○ Select All Columns: Use SELECT * to retrieve all columns from a
table.
2. Key Clauses:
○ WHERE: Filters rows based on specified conditions.
○ GROUP BY: Groups rows for aggregation (e.g., COUNT, SUM).
○ HAVING: Filters groups created by GROUP BY based on conditions.
○ ORDER BY: Sorts results. Defaults to ascending (ASC), but DESC can
be specified for descending order.
3. Column Aliases:

Use AS to rename columns in the output. For example:


sql
Copy code
SELECT column_name AS alias_name

FROM table_name;


○ Enclose aliases in double quotes for names containing spaces or
reserved keywords.
4. Examples:

Retrieve employees in department 5001:


sql
Copy code
SELECT *

FROM employee

WHERE department_id = 5001;

Retrieve department names in block 3, sorted by name (ascending):


sql
Copy code
SELECT department_name

FROM department
WHERE block_number = 3

ORDER BY department_name;

Pro Tips:

Use Comments:
Include comments to clarify complex queries for better readability.
sql
Copy code
-- Retrieve department names from block 3 in ascending order

SELECT department_name

FROM department

WHERE block_number = 3

ORDER BY department_name;


● Practice With Real Data:
Use sample databases like Sakila or AdventureWorks to explore complex
queries.
● Test Different Clauses:
Experiment with combinations of GROUP BY, HAVING, and ORDER BY to
solidify understanding.
● Online SQL Editors:
Use platforms like SQL Fiddle or db-fiddle.com to practice writing and testing
queries.

Example 1: Retrieve All Employees in Department 5001

Code:

sql

Copy code

SELECT *

FROM employee
WHERE department_id = 5001;

Explanation:

1. SELECT *:
○ The * means "select all columns" from the table employee. This will
return all the fields for the employees who match the condition.
2. FROM employee:
○ Specifies the table to fetch data from, in this case, the employee table.
3. WHERE department_id = 5001:
○ This clause filters the rows, so only employees who belong to
department 5001 are included in the result.

Example 2: Retrieve Department Names in Block 3, Sorted by Name

Code:

sql

Copy code

SELECT department_name

FROM department

WHERE block_number = 3

ORDER BY department_name;

Explanation:

1. SELECT department_name:
○ Retrieves only the department_name column from the table.
2. FROM department:
○ Indicates that the data should be fetched from the department table.
3. WHERE block_number = 3:
○ Filters rows to include only departments located in block number 3. If
there are rows with other block numbers, they will be excluded from the
result.
4. ORDER BY department_name:
○ Sorts the results by the department_name column alphabetically in
ascending order.
○ If no ASC or DESC is mentioned, the default is ascending (ASC).

Results (Assumed Data):

Let’s say the department table has the following data:

department_name block_numb
er

Software 3
Engineering

IT 3

CAC 3

Marketing 2

The query will return:

department_name

CAC

IT

Software
Engineering
Explanation of Sorting:

● The names are sorted alphabetically. If we used DESC in the ORDER BY


clause, the result would be reversed: Software Engineering, IT, CAC.

Add-On Example: Using Column Aliases

If you want the column to display a more descriptive name in the results, you can
use an alias:

Code:

sql

Copy code

SELECT department_name AS "Department Name"

FROM department

WHERE block_number = 3

ORDER BY department_name;

Result (Display Output):

Department Name

CAC

IT

Software
Engineering
The AS "Department Name" ensures the output column is labeled "Department
Name" instead of department_name.

Practice Ideas:

Add Multiple Columns:


Try retrieving multiple columns:
sql
Copy code
SELECT department_name, block_number

FROM department

WHERE block_number = 3

ORDER BY department_name;

1.

Using Aggregate Functions:


Count the number of departments in each block:
sql
Copy code
SELECT block_number, COUNT(*) AS "Total Departments"

FROM department

2. GROUP BY block_number;

Example 1: Retrieve Employees Whose Names Begin With 'J'

Code:

sql

Copy code

SELECT *

FROM employee

WHERE name LIKE 'J%';


Explanation:

1. SELECT *:
○ Selects all columns from the table employee.
2. FROM employee:
○ Specifies the source table, which is employee.
3. WHERE name LIKE 'J%':
○ The LIKE operator checks the name column for values matching the
pattern 'J%'.
○ J%:
■ J indicates the first character must be "J".
■ % (wildcard) matches any sequence of characters after "J"
(including no characters).
○ Examples of matching values: John, Janet, James.
○ Examples of non-matching values: Michael, Steve.

Result (Assumed Data):

For a table with the following data:

ID Name Departmen
t

1 John HR

2 Janet IT

3 Michae Sales
l

4 James Marketing

The query will return:


ID Nam Departmen
e t

1 John HR

2 Janet IT

4 Jame Marketing
s

Example 2: Retrieve Students Whose Names Start With 'A' and Sort Results

The task here involves retrieving names that start with "A" from a student table and
sorting them in ascending order.

Code:

sql

Copy code

SELECT student_name

FROM student

WHERE student_name LIKE 'A%'

ORDER BY student_name ASC;

Explanation:

1. SELECT student_name:
○ Retrieves only the student_name column.
2. FROM student:
○ Specifies the source table, which is student.
3. WHERE student_name LIKE 'A%':
○ Filters for names starting with "A" and allows any number of characters
after it.
○ Matches examples: Alice, Adam, Aarav.
4. ORDER BY student_name ASC:
○ Sorts the results by student_name in ascending order.
○ Adding ASC is optional because ascending is the default order.

Result (Assumed Data):

For a table with the following data:

ID Student_Na Grad
me e

1 Alice A

2 Bob B

3 Adam A

4 Aaron C

The query will return:

Student_Na
me

Aaron

Adam

Alice
Using Wildcards in LIKE

The LIKE operator supports wildcards for flexible pattern matching:

1. %: Matches zero or more characters.


○ 'A%': Names starting with "A" (e.g., Alice, Aaron).
○ '%son': Names ending with "son" (e.g., Johnson, Harrison).
○ '%ar%': Names containing "ar" (e.g., Carter, Maria).
2. _: Matches exactly one character.
○ 'J_n': Matches Jan, Jon, but not John.

Introduction to Functions in Database Systems

Functions in database systems are used to perform operations on data to simplify


queries, enhance readability, and provide calculated results. They are broadly
categorized into two types:

1. Single-Row Functions
2. Multi-Row Functions (Aggregate Functions)

1. Single-Row Functions

Single-row functions operate on one row at a time and return one result per row.
They are commonly used in queries to manipulate or format data.

Types of Single-Row Functions

Single-row functions can be further categorized into:

1. String Functions
Used for operations on strings.
Examples:

UPPER(): Converts text to uppercase.


sql
Copy code
SELECT UPPER('hello') AS uppercase_text;

-- Result: HELLO


○ LOWER(): Converts text to lowercase.

CONCAT(): Concatenates two strings.


sql
Copy code
SELECT CONCAT('Hello', ' World') AS full_text;

-- Result: Hello World


2. Numeric Functions
Perform operations on numeric data.
Examples:

ROUND(): Rounds a number to a specified number of decimal places.


sql
Copy code
SELECT ROUND(123.456, 1) AS rounded_number;

-- Result: 123.5


○ ABS(): Returns the absolute value of a number.

POWER(): Raises a number to a specified power.


sql
Copy code
SELECT POWER(2, 3) AS result;

-- Result: 8


3. Date Functions
Used to manipulate and format dates.
Examples:

NOW(): Returns the current date and time.


sql
Copy code
SELECT NOW() AS current_datetime;

-- Result: 2024-11-22 12:34:56


○ DATE_ADD(): Adds a specified interval to a date.

DATEDIFF(): Finds the difference between two dates.


sql
Copy code
SELECT DATEDIFF('2024-12-01', '2024-11-22') AS
days_difference;

-- Result: 9


4. Conversion Functions
Convert data types.
Examples:

CAST(): Converts a value from one data type to another.


sql
Copy code
SELECT CAST('123' AS INT) AS numeric_value;

-- Result: 123


○ CONVERT(): Another method for data type conversion.

Example of a Single-Row Function:

sql

Copy code

SELECT employee_id,

UPPER(first_name) AS uppercase_name,

ROUND(salary, 2) AS rounded_salary

FROM employee;

This query:

● Converts first_name to uppercase.


● Rounds salary to 2 decimal places for each row.
2. Multi-Row Functions (Aggregate Functions)

Multi-row functions, also known as group functions, operate on a set of rows and
return a single summarized result. These are typically used with GROUP BY
clauses.

Types of Multi-Row Functions

SUM()
Calculates the total of a numeric column.
sql
Copy code
SELECT SUM(salary) AS total_salary

FROM employee;

1.

AVG()
Returns the average value of a numeric column.
sql
Copy code
SELECT AVG(salary) AS average_salary

FROM employee;

2.

COUNT()
Counts the number of rows or non-NULL values.
sql
Copy code
SELECT COUNT(employee_id) AS employee_count

FROM employee;

3.

MAX()
Finds the maximum value in a column.
sql
Copy code
SELECT MAX(salary) AS highest_salary
FROM employee;

4.

MIN()
Finds the minimum value in a column.
sql
Copy code
SELECT MIN(salary) AS lowest_salary

FROM employee;

5.

Example of a Multi-Row Function:

sql

Copy code

SELECT department_id,

COUNT(employee_id) AS employee_count,

AVG(salary) AS average_salary

FROM employee

GROUP BY department_id;

This query:

● Groups employees by department_id.


● Calculates the number of employees and the average salary in each
department.

Key Differences Between Single-Row and Multi-Row Functions

Feature Single-Row Functions Multi-Row Functions


Operates One row at a time A set (group) of rows
On

Returns One result per row One result for the


group

Usage Direct manipulation of Summarized


data information

Example UPPER(), ROUND() SUM(), COUNT()

Practice Task

Task 1: Single-Row Function

Write a query to display the employee names in uppercase along with their salaries
rounded to 2 decimal places.

sql

Copy code

SELECT UPPER(employee_name) AS uppercase_name,

ROUND(salary, 2) AS rounded_salary

FROM employee;

Task 2: Multi-Row Function

Write a query to find the total and average salaries for each department.

sql

Copy code

SELECT department_id,
SUM(salary) AS total_salary,

AVG(salary) AS average_salary

FROM employee

GROUP BY department_id;

Overview of SQL Functions and Concepts

In this module, we have delved into the functionality of SQL functions and their
applications in database management systems, specifically within the context of an
insurance management system. SQL functions are essential for performing
operations, manipulating data, and retrieving meaningful insights.

Types of SQL Functions

SQL functions are broadly categorized into:

1. Single-Row Functions
○ Operate on one row at a time.
○ Return one result per row.
2. Multi-Row (Aggregate) Functions
○ Operate on a group of rows.
○ Return one result for the entire group.

1. Single-Row Functions

Single-row functions are further divided into:

A. Character Functions

● Accept character data as input and return either character or numeric values.

Examples:

UPPER(): Converts text to uppercase.


sql
Copy code
SELECT UPPER(customer_name) AS uppercase_name FROM customer;
1.

LOWER(): Converts text to lowercase.


sql
Copy code
SELECT LOWER(policy_name) AS lowercase_name FROM policy;

2.

LENGTH(): Returns the length of a string.


sql
Copy code
SELECT LENGTH(customer_name) AS name_length FROM customer;

3.

B. Numeric Functions

● Accept numeric input and return numeric values.

Examples:

ROUND(): Rounds a number to a specified decimal place.


sql
Copy code
SELECT ROUND(premium_amount, 2) AS rounded_premium FROM
policy_enrollment;

1.

ABS(): Returns the absolute value of a number.


sql
Copy code
SELECT ABS(-200) AS absolute_value;

2.

POWER(): Raises a number to the power of another.


sql
Copy code
SELECT POWER(2, 3) AS result; -- Output: 8

3.
C. Date Functions

● Work with date and time values to perform operations or format output.

Examples:

NOW(): Returns the current date and time.


sql
Copy code
SELECT NOW() AS current_datetime;

1.

DATEDIFF(): Returns the difference between two dates.


sql
Copy code
SELECT DATEDIFF('2024-12-01', '2024-11-22') AS
days_difference;

2.

DATE_FORMAT(): Formats a date in a specified way.


sql
Copy code
SELECT DATE_FORMAT(policy_start_date, '%d-%m-%Y') AS
formatted_date FROM policy_enrollment;

3.

D. General Functions

● These are functions that work with any data type.

Examples:

IFNULL(): Returns an alternative value if the input is NULL.


sql
Copy code
SELECT IFNULL(min_premium_amount, 0) AS adjusted_amount FROM
policy;

1.

COALESCE(): Returns the first non-null value from a list.


sql
Copy code
SELECT COALESCE(address, 'Unknown') AS customer_address FROM
customer;

2.

E. Nesting Functions

● Functions can be nested, where the result of one function is used as input to
another.

Example:

sql

Copy code

SELECT UPPER(CONCAT(customer_name, ' - ', policy_name)) AS


detailed_info

FROM customer

JOIN policy_enrollment ON customer.customer_id =


policy_enrollment.customer_id

JOIN policy ON policy_enrollment.policy_id = policy.policy_id;

2. Multi-Row (Aggregate) Functions

These functions operate on a set of rows and return a summarized result. Common
examples include:

SUM(): Calculates the total.


sql
Copy code
SELECT SUM(premium_amount) AS total_premium FROM
policy_enrollment;

1.
AVG(): Calculates the average.
sql
Copy code
SELECT AVG(premium_amount) AS average_premium FROM
policy_enrollment;

2.

COUNT(): Counts the number of rows.


sql
Copy code
SELECT COUNT(*) AS total_policies FROM policy;

3.

MAX(): Finds the maximum value.


sql
Copy code
SELECT MAX(premium_amount) AS highest_premium FROM
policy_enrollment;

4.

MIN(): Finds the minimum value.


sql
Copy code
SELECT MIN(premium_amount) AS lowest_premium FROM
policy_enrollment;

5.

3. GROUP BY and HAVING Clauses

● GROUP BY is used to organize data into groups for aggregation.


● HAVING is used to filter groups based on conditions.

Example with GROUP BY and HAVING:

sql

Copy code

SELECT policy_type,
COUNT(*) AS total_customers,

SUM(premium_amount) AS total_premium

FROM policy_enrollment

GROUP BY policy_type

HAVING SUM(premium_amount) > 10000;

Summary of Topics Covered:

1. Character Functions: UPPER(), LOWER(), LENGTH()


2. Numeric Functions: ROUND(), ABS(), POWER()
3. Date Functions: NOW(), DATEDIFF(), DATE_FORMAT()
4. General Functions: IFNULL(), COALESCE()
5. Nested Functions: Combining multiple functions.
6. Aggregate Functions: SUM(), AVG(), COUNT(), MAX(), MIN()
7. GROUP BY and HAVING Clauses: Grouping and filtering summarized
results.

SQL Functions Overview: Scalar and Aggregate Functions

In MySQL, functions are divided into two main types based on their scope of
operation:

1. Scalar Functions
2. Aggregate Functions

1. Scalar Functions

● Definition: These operate on a row-by-row basis. They take individual


values as input and return a single value as output for each row.
● Scope: Often called column-level functions because they act on values
from a specific column or subset of columns.

Common Scalar Functions:

1. Character Functions:
○ Work on character/string data.
○ Examples:

UPPER(column_name): Converts text to uppercase.


sql
Copy code
SELECT UPPER(customer_name) AS uppercase_name FROM customers;

CONCAT(string1, string2): Concatenates strings.


sql
Copy code
SELECT CONCAT(first_name, ' ', last_name) AS full_name FROM
employees;


2. Numeric Functions:
○ Work on numeric data.
○ Examples:

ROUND(column_name, decimals): Rounds a value to a specified number of


decimal places.
sql
Copy code
SELECT ROUND(salary, 2) AS rounded_salary FROM employees;

MOD(number, divisor): Returns the remainder of a division.


sql
Copy code
SELECT MOD(15, 4) AS remainder; -- Output: 3


3. Date and Time Functions:
○ Operate on date/time values.
○ Examples:

NOW(): Returns the current date and time.


sql
Copy code
SELECT NOW() AS current_datetime;


DATE_ADD(date, INTERVAL value unit): Adds an interval to a date.
sql
Copy code
SELECT DATE_ADD('2024-01-01', INTERVAL 7 DAY) AS new_date;


4. Conversion Functions:
○ Convert data types.
○ Examples:

CAST(value AS type): Converts a value to a specified data type.


sql
Copy code
SELECT CAST('123' AS UNSIGNED) AS converted_value;

2. Aggregate Functions

● Definition: Operate on a group of rows to perform calculations and return a


summarized result.
● Scope: Often used in conjunction with GROUP BY to aggregate data across
rows.

Common Aggregate Functions:

COUNT(column_name): Counts the number of rows (excluding NULL values).


sql
Copy code
SELECT COUNT(customer_id) AS total_customers FROM customers;

1.

SUM(column_name): Calculates the total of a numeric column.


sql
Copy code
SELECT SUM(order_amount) AS total_sales FROM orders;

2.

AVG(column_name): Calculates the average of a numeric column.


sql
Copy code
SELECT AVG(salary) AS average_salary FROM employees;
3.

MAX(column_name): Finds the maximum value in a column.


sql
Copy code
SELECT MAX(salary) AS highest_salary FROM employees;

4.

MIN(column_name): Finds the minimum value in a column.


sql
Copy code
SELECT MIN(salary) AS lowest_salary FROM employees;

5.

Comparison: Scalar vs. Aggregate Functions

Feature Scalar Functions Aggregate Functions

Scope Operates on a single row at a Operates on a group of rows.


time.

Output Returns one value per row. Returns one value for a group of
rows.

Example UPPER(), ROUND(), NOW() SUM(), COUNT(), AVG()


s

Usage Applied to individual Summarizes data across rows.


columns/rows.

Practical Example

Suppose we have a table named orders:


order_i customer_ order_amou order_dat
d id nt e

1 101 500 2024-11-2


0

2 102 300 2024-11-2


1

3 101 700 2024-11-2


2

Using Scalar Functions:

sql

Copy code

-- Convert order_date to a different format

SELECT DATE_FORMAT(order_date, '%d-%M-%Y') AS formatted_date

FROM orders;

Using Aggregate Functions:

sql

Copy code

-- Find the total order amount for each customer

SELECT customer_id, SUM(order_amount) AS total_amount

FROM orders

GROUP BY customer_id;
Scalar functions focus on row-by-row operations, while aggregate functions
summarize data for analysis across multiple rows. Both are essential for working with
data in MySQL effectively!

Exploring Scalar Functions in SQL: A Practical Example

Scalar functions in SQL operate on individual rows and return a single value per row.
These are highly useful for performing operations like string manipulation, date
formatting, numeric adjustments, and more.

Overview of Scalar Functions

1. String Functions:
○ Used for manipulating string data.
○ Examples: SUBSTRING, UPPER, LOWER, CONCAT, TRIM, etc.
2. Date Functions:
○ Used for date/time manipulation.
○ Examples: DATE, DAYNAME, MONTHNAME, NOW, DATE_FORMAT, etc.
3. Numeric Functions:
○ Perform calculations on numeric data.
○ Examples: ROUND, FLOOR, CEIL, TRUNCATE.
4. Conversion Functions:
○ Convert data types or format data.
○ Examples: CAST, CONVERT, FORMAT.
5. Null Handling Functions:
○ Manage null values.
○ Examples: IFNULL, COALESCE.

Example 1: Uppercase Employee Names

Scenario: Convert all employee names to uppercase.

Table: employee

Employee_I Employee_Na Salar Department_I


D me y D
101 Alice 5000 1

102 Bob 6000 2

103 Charlie 7000 1

SQL Query:

sql

Copy code

SELECT UPPER(Employee_Name) AS Uppercase_Name

FROM employee;

Output:

Uppercase_Na
me

ALICE

BOB

CHARLIE

Example 2: Generate Passwords

Scenario: Generate passwords by concatenating the first 3 characters of the


username and the first 3 digits of the phone number.
Table: users

Name Phone_Numb
er

John 9876543210

Sarah 8765432109

Michae 7654321098
l

SQL Query:

sql

Copy code

SELECT

Name,

CONCAT(SUBSTRING(Name, 1, 3), SUBSTRING(CAST(Phone_Number


AS CHAR), 1, 3)) AS Password

FROM users

ORDER BY Name;

Explanation:

1. SUBSTRING(Name, 1, 3): Extracts the first 3 characters from the Name


column.
2. CAST(Phone_Number AS CHAR): Converts the Phone_Number (numeric)
to a string for substring manipulation.
3. SUBSTRING(..., 1, 3): Extracts the first 3 digits from the phone number.
4. CONCAT(...): Combines the two substrings into a single string.
5. ORDER BY Name: Sorts the result by the Name column.

Output:

Name Passwor
d

John Joh987

Michae Mic765
l

Sarah Sar876

Key Points:

● Scalar functions like SUBSTRING, UPPER, and CONCAT process each row
independently.
● They can be used to dynamically generate or modify data in a table.
● Results can be labeled using an alias (AS keyword).
● Conversion functions like CAST ensure compatibility when manipulating
numeric and string data together.

Scalar functions are versatile tools in SQL, enabling efficient row-level operations
tailored to specific data transformation needs.

SQL Aggregate Functions: Overview and Example

Aggregate functions in SQL are used to perform calculations on multiple rows and
return a single result for the group of rows. Unlike scalar functions, which operate on
individual rows, aggregate functions summarize data across multiple rows. Common
aggregate functions include:

1. MAX: Returns the maximum value in a column.


2. MIN: Returns the minimum value in a column.
3. SUM: Returns the sum of values in a numeric column.
4. COUNT: Returns the count of rows or non-null values in a column.
5. AVG: Returns the average of values in a numeric column.

Key Characteristics of Aggregate Functions:

● Null Handling: Aggregate functions ignore NULL values unless explicitly


handled (e.g., with COALESCE or CASE statements).
● Group Operations: Aggregate functions operate on a group of rows, and
often you’ll use a GROUP BY clause to specify how the data should be
grouped.

Example 1: Calculating Total Salary

Scenario: Calculate the total salary of all employees.

Table: employee

Employee_I Employee_Na Salar Department_I


D me y D

101 Alice 5000 1

102 Bob 6000 2

103 Charlie 7000 1

SQL Query:

sql

Copy code

SELECT SUM(Salary) AS Total_Salary

FROM employee;
Explanation:

● SUM(Salary): Sums up all the values in the Salary column.


● The result is a single value representing the total salary.

Output:

Total_Salar
y

18000

Example 2: Grouping and Counting Bus Types

Scenario: Display the types of buses and the number of buses in each type, sorted
by the count in descending order.

Table: busses

Bus_Typ Bus_Numb
e er

AC 101

Non-AC 102

AC 103

Non-AC 104

AC 105
AC 106

SQL Query:

sql

Copy code

SELECT Bus_Type, COUNT(Bus_Number) AS Bus_Count

FROM busses

GROUP BY Bus_Type

ORDER BY Bus_Count DESC;

Explanation:

1. COUNT(Bus_Number): Counts the number of buses for each bus type.


2. GROUP BY Bus_Type: Groups the rows by the Bus_Type column.
3. ORDER BY Bus_Count DESC: Sorts the results in descending order based
on the bus count.

Output:

Bus_Typ Bus_Cou
e nt

AC 4

Non-AC 2

Key Takeaways:

● Aggregate functions summarize data across multiple rows.


● They are typically used with GROUP BY to organize data into groups.
● The functions ignore NULL values, unless specifically handled.
● ORDER BY can be used to sort the results of aggregated data.

Aggregate functions are powerful tools for analyzing large datasets and generating
summarized information.

SQL Joins and Subqueries

In SQL, when you need to retrieve data from multiple tables, joins and subqueries
are commonly used mechanisms. Let's break down both concepts, including their
types and use cases.

Joins

A join allows you to combine rows from two or more tables based on a related
column between them. Joins are essential when you need to work with normalized
data spread across multiple tables. Without a join, you'd end up with multiple
separate queries, making the database operations inefficient.

Types of Joins:

1. Inner Join:
○ Definition: Returns only the rows where there is a match in both
tables.
○ Use Case: To find matching records between two tables.

SQL Syntax:
sql
Copy code
SELECT *

FROM table1

INNER JOIN table2

ON table1.column_name = table2.column_name;


2. Left Outer Join (Left Join):
○ Definition: Returns all rows from the left table and the matching rows
from the right table. If there is no match, NULL values will be returned
for columns from the right table.
○ Use Case: To return all records from the left table and matching
records from the right.

SQL Syntax:
sql
Copy code
SELECT *

FROM table1

LEFT JOIN table2

ON table1.column_name = table2.column_name;


3. Right Outer Join (Right Join):
○ Definition: Similar to the left join, but it returns all rows from the right
table and the matching rows from the left table. Non-matching rows
from the left table will contain NULL values.
○ Use Case: When you need to return all records from the right table and
the matching records from the left.

SQL Syntax:
sql
Copy code
SELECT *

FROM table1

RIGHT JOIN table2

ON table1.column_name = table2.column_name;


4. Full Outer Join:
○ Definition: Combines the results of both left and right joins. It returns
all rows when there is a match in either the left or right table. If there’s
no match, NULL values will be filled in for the missing side.
○ Use Case: To return all records from both tables, with NULL where
there’s no match.

SQL Syntax:
sql
Copy code
SELECT *
FROM table1

FULL OUTER JOIN table2

ON table1.column_name = table2.column_name;


5. Cross Join:
○ Definition: Returns the Cartesian product of the two tables, i.e., every
row from the first table combined with every row from the second table.
○ Use Case: To combine all rows from two tables, but be careful as this
can produce a large number of results.

SQL Syntax:
sql
Copy code
SELECT *

FROM table1

CROSS JOIN table2;


6. Natural Join:
○ Definition: Automatically joins tables based on columns with the same
name and data type.
○ Use Case: When you have tables with columns of the same name and
want to join them based on these columns automatically.

SQL Syntax:
sql
Copy code
SELECT *

FROM table1

NATURAL JOIN table2;

Subqueries
A subquery (or inner query) is a query that is nested inside another query. It is
typically used when the result of the inner query is required by the outer query for
filtering or computing results.

How Subqueries Work:

● The inner query executes first.


● The outer query then uses the result from the inner query for further
processing.

Types of Subqueries:

1. Scalar Subquery:
○ Definition: Returns a single value (one row, one column).
○ Use Case: For example, to retrieve a specific value for filtering.

SQL Syntax:
sql
Copy code
SELECT *

FROM table1

WHERE column_name = (SELECT MAX(column_name) FROM table2);


2. Correlated Subquery:
○ Definition: A subquery that references columns from the outer query.
○ Use Case: When you want to use data from the outer query to filter the
results of the inner query.

SQL Syntax:
sql
Copy code
SELECT *

FROM table1 t1

WHERE column_name > (SELECT AVG(column_name)

FROM table2 t2

WHERE t1.column_name = t2.column_name);


3. Exists Subquery:
○ Definition: Checks for the existence of rows returned by the subquery.
○ Use Case: To check whether at least one row exists that meets the
condition.

SQL Syntax:
sql
Copy code
SELECT *

FROM table1

WHERE EXISTS (SELECT 1 FROM table2 WHERE table1.column_name =


table2.column_name);


4. IN Subquery:
○ Definition: Tests whether a value matches any value returned by the
subquery.
○ Use Case: When you want to check if a value exists in a set of values
returned by a subquery.

SQL Syntax:
sql
Copy code
SELECT *

FROM table1

WHERE column_name IN (SELECT column_name FROM table2);

Join vs. Subquery

● Performance: Generally, joins are preferred over subqueries because joins


are more efficient in combining data from multiple tables.
● Readability: Subqueries can sometimes make queries more complex, but
they are useful when working with conditions that require nested queries.
● Use Case: Joins are typically used when you need to combine columns from
multiple tables, while subqueries are useful for filtering or retrieving specific
values based on the results of another query.
Example Scenario:

Let's say we have two tables: employees and departments.

employees table:

emp_i emp_nam dept_i salar


d e d y

101 Alice 1 5000

102 Bob 2 6000

103 Charlie 1 7000

departments table:

dept_i dept_nam
d e

1 HR

2 Finance

Query 1: Join Example (Inner Join):

sql

Copy code

SELECT emp_name, dept_name

FROM employees

INNER JOIN departments


ON employees.dept_id = departments.dept_id;

Result:

emp_nam dept_nam
e e

Alice HR

Bob Finance

Charlie HR

Query 2: Subquery Example (Find employees with salary higher than average salary
in their department):

sql

Copy code

SELECT emp_name

FROM employees e

WHERE salary > (SELECT AVG(salary) FROM employees WHERE


dept_id = e.dept_id);

Result:

emp_nam
e

Charlie
Conclusion:

● Joins are used to combine data from multiple tables based on related
columns.
● Subqueries are used when you need to nest a query inside another,
especially for filtering or computing based on the results of an inner query.
● Choosing between a join and a subquery depends on the specific
requirements and performance considerations of your query.

1. Joins in SQL

A join allows you to retrieve data from multiple tables based on a related column
between them. There are several types of joins, each serving different purposes.

Cartesian Product (Cross Join)

● Definition: A Cartesian join (or cross join) combines every row from one table
with every row from another, leading to a Cartesian product.
● Use Case: This happens when no join condition is specified.
● Example: If you want to combine customer data with policy enrollment without
specifying a condition, you'll get every customer’s details combined with every
policy enrollment, leading to a huge number of results.

Equi Join (Inner Join)

● Definition: This join uses the equal to operator to match records between two
tables. It returns only the rows where there is a match in both tables.
● Example: You can join the customer table with the policy enrollment table
based on a customer ID that exists in both.

Non-Equi Join

● Definition: This join uses any operator other than the equality operator, like >,
<, >=, <=, <>, in the join condition.
● Example: Joining based on some condition like “penalty > 1000” instead of a
direct equality.

Outer Joins

Outer joins return rows even if there is no match in one of the tables.
● Left Outer Join: Returns all rows from the left table and matching rows from
the right table. If there's no match, NULL is returned for columns of the right
table.
● Right Outer Join: Returns all rows from the right table and matching rows
from the left table. If there's no match, NULL is returned for columns of the left
table.
● Full Outer Join: In systems that support it (like Oracle), it returns all rows
from both tables. If no match exists, NULL is returned for missing data from
either side. In MySQL, you can emulate a full outer join using a combination of
LEFT JOIN, RIGHT JOIN, and the UNION operator.

Self Join

● Definition: A self join is a join where a table is joined with itself. This is useful
for relationships within the same table, such as hierarchical data (e.g.,
employees and managers).
● Example: Using aliases to distinguish between different instances of the
same table in the join.

Natural Join

● Definition: A natural join automatically joins tables based on columns with the
same name and data type.
● Example: If two tables have a column named customer_id, the natural join
will automatically match rows based on that column.
● Using the USING clause: When multiple columns with the same name exist
but not the same data type, you can specify which column to join on using the
USING clause.

Joining Multiple Tables

● To join n tables, you need at least n-1 join conditions.


● Example: Joining three tables requires two conditions.

2. Subqueries in SQL

A subquery is a query nested inside another query, and the result of the subquery is
used by the outer query.

Types of Subqueries:

1. Single-Row Subquery:
○ Definition: Returns only one row (and typically one value).
○ Example: You can use a subquery to find customers who paid a higher
penalty than the average penalty of all customers.
2. Multi-Row Subquery:
○ Definition: Returns more than one row.
○ Example: A subquery that returns multiple penalty amounts to
compare with each customer.
○ Operators used: IN, ANY, ALL.
■ IN: Checks if a value is in a set returned by the subquery.
■ ANY: Compares with any value returned by the subquery.
■ ALL: Compares with every value returned by the subquery.
3. Correlated Subquery:
○ Definition: A correlated subquery references columns from the outer
query. It is evaluated once for each row processed by the outer query.
○ Example: For each customer, you can compare their penalty with the
highest penalty paid by a different customer.
4. Subqueries in Different Clauses:
○ SELECT Clause: A subquery can return a value that will be selected in
the outer query.
○ FROM Clause: A subquery can act as a derived table, providing a
temporary result set for the outer query.
○ INSERT/UPDATE/DELETE Statements: Subqueries can be used to
specify values or conditions for these statements.

Example Queries:

Using a Subquery in the SELECT Clause:


sql
Copy code
SELECT customer_id,

(SELECT MAX(penalty) FROM penalties WHERE customer_id =


customers.customer_id) AS highest_penalty

FROM customers;

1.

Using a Correlated Subquery in the WHERE Clause:


sql
Copy code
SELECT customer_id
FROM customers c

WHERE c.penalty > (SELECT AVG(penalty) FROM penalties p WHERE


p.customer_id = c.customer_id);

2.

Emulating a Full Outer Join in MySQL:


sql
Copy code
(SELECT * FROM customer LEFT JOIN policy_enrollment ON
customer.customer_id = policy_enrollment.customer_id)

UNION

(SELECT * FROM customer RIGHT JOIN policy_enrollment ON


customer.customer_id = policy_enrollment.customer_id);

3.

Summary of Key Concepts:

● Joins: Used to combine data from multiple tables. The main types are Inner
Join, Outer Joins (Left, Right, Full), and Self Join.
● Subqueries: Queries nested inside another query. They can be single-row,
multi-row, or correlated subqueries.
● Equi Join: The most common type of join where tables are joined based on
equality.
● Non-Equi Join: Uses operators other than equality.
● Outer Joins: Return unmatched rows from one or both tables.
● Natural Join: Automatically joins tables based on columns with the same
name.

By mastering joins and subqueries, you can efficiently retrieve and manipulate data
across multiple tables in SQL.

DEMO:

In this demo, the explanation revolves around the SQL join operation and how it can
be used to retrieve data from multiple tables. The two tables in the example are:
● Employee Table: Contains information about employees, including the
employee_id (primary key) and department_id (foreign key referring to
the department).
● Department Table: Contains information about departments, including
department_id (primary key) and location.

Types of Joins:

1. Inner Join (Equi Join):


○ Retrieves only the matching rows between two tables.
○ Example: If you're joining employee data with department data, you
only get employees that belong to a department.
2. Full Outer Join:
○ Retrieves all rows from both tables: matching rows and unmatched
rows.
○ Useful when you want to see data from both tables, even if there's no
match.
3. Left Outer Join (Left Join):
○ Retrieves all rows from the left table (employee table), and only
matching rows from the right table (department table).
○ Example: If an employee doesn’t belong to any department, their name
will still be included, but the department name will be NULL.
4. Right Outer Join (Right Join):
○ Retrieves all rows from the right table (department table), and only
matching rows from the left table (employee table).
○ Example: This will show all departments, even if no employee is
assigned to them.

Example SQL Query: Employee and Department Names

The goal is to display all employee names along with their department locations. The
query uses a Left Outer Join to ensure that all employees are included, even those
without a department.

Here is how you might write the SQL query:

sql

Copy code

SELECT e.employee_name, d.location

FROM employee e
LEFT JOIN department d

ON e.department_id = d.department_id;

● SELECT: Specifies the columns you want to retrieve — in this case,


employee_name and location.
● FROM employee e: Specifies the employee table, using e as its alias.
● LEFT JOIN department d: Specifies a left outer join with the department
table, using d as its alias.
● ON e.department_id = d.department_id: The condition to match rows — the
department ID in the employee table should match the department ID in the
department table.

This query ensures that you get all employee names, and for employees who do not
have a department, the location column will be NULL.

SQL Query for Student Data with Department and Sorted by School

For a similar scenario where you need to display student names and their respective
department names, sorted by school, here’s an example query based on the
scenario:

sql

Copy code

SELECT s.student_name, d.department_name

FROM student s

LEFT JOIN department d

ON s.department_id = d.department_id

ORDER BY s.school;

● SELECT: Retrieves the student name and department name.


● FROM student s: Specifies the student table, using s as its alias.
● LEFT JOIN department d: Performs a left join with the department table,
using d as its alias.
● ON s.department_id = d.department_id: The join condition, matching the
department ID in the student table to the department table.
● ORDER BY s.school: Sorts the results by the school column in the student
table.

This query will return all students and their department names (if available), sorted
by their school.

Problem:

You need to find the employee who is getting the maximum salary in the employee
table. Instead of manually entering the maximum salary value (like 20,000), you want
to calculate the maximum salary dynamically and use it in the query.

Traditional (Hardcoding) Approach:

sql

Copy code

SELECT employee_name

FROM employee

WHERE salary = 20000;

This approach hardcodes the value 20,000, which works if the salary is fixed, but
isn't flexible.

Solution Using a Subquery:

To avoid hardcoding the salary value, you can use a subquery that retrieves the
maximum salary from the employee table and pass it to the main query. The
subquery will dynamically return the maximum salary, and the outer query will then
use that value.

Here’s how you can write the query:

sql

Copy code
SELECT employee_name

FROM employee

WHERE salary = (SELECT MAX(salary) FROM employee);

Explanation:

1. Subquery: (SELECT MAX(salary) FROM employee)


○ This subquery fetches the maximum salary from the employee table.
○ The result of this subquery will be a single value (the maximum salary).
2. Outer Query: SELECT employee_name FROM employee WHERE salary
= ...
○ The outer query retrieves the employee_name from the employee
table.
○ It compares the salary of each employee to the value returned by the
subquery (the maximum salary).
○ The employee(s) who match the maximum salary will be returned.

Example:

Let’s assume the employee table looks like this:

employee_na salar
me y

Alice 2000
0

Bob 2500
0

Charlie 3000
0
Dave 3000
0

The query will return:

● Charlie and Dave because they both have the maximum salary of 30,000.

Benefits:

● No Hardcoding: The maximum salary is dynamically calculated using the


subquery, making the query more flexible and adaptable.
● Scalable: If the maximum salary changes, the subquery will automatically
return the updated value.

This approach avoids hardcoding and makes the query more robust for varying
data scenarios.

DEMO:

In this demo on SQL subqueries, you're explaining how subqueries can be used to
handle dynamic conditions in queries, allowing you to write more flexible and
reusable SQL code. Let’s summarize the key concepts and queries explained:

1. Using a Subquery to Find the Employee with the Maximum Salary

Problem:

You need to find the employee who earns the maximum salary in the employee
table. Instead of hardcoding the maximum salary (e.g., 20,000), you use a subquery
to dynamically calculate the maximum salary.

Approach:

Step 1: Retrieve the maximum salary using a subquery:


sql
Copy code
SELECT MAX(salary) FROM employee;

Step 2: Use the result of the subquery to find the employee with that salary:
sql
Copy code
SELECT employee_name
FROM employee

WHERE salary = (SELECT MAX(salary) FROM employee);

This approach ensures that the query adapts to future changes in salary values, so it
will always return the employee with the current maximum salary.

2. Finding Staff Members Who Are Not Handling Any Subjects

Problem:

You need to display the names of staff members who are not handling any
subjects. This requires checking the staff table and the subject table. If a staff ID
does not appear in the subject table, that staff member is not handling any subjects.

Approach:

Step 1: Retrieve all staff IDs from the subject table, representing staff who are
handling subjects:
sql
Copy code
SELECT staff_id

FROM subject;

Step 2: Use a subquery to filter out staff members who are handling subjects and
select staff who are not in the subject table:
sql
Copy code
SELECT staff_name

FROM staff

WHERE staff_id NOT IN (SELECT staff_id FROM subject WHERE


staff_id IS NOT NULL)

ORDER BY staff_name;

Key Points:
● The subquery inside the NOT IN clause fetches the staff IDs of employees
handling subjects.
● The outer query checks for staff members whose IDs do not appear in the
subject table, indicating they are not handling any subjects.
● Handling NULL values: If the subquery contains NULL values (e.g., due to
missing staff IDs), the outer query will return an empty result. To avoid this, we
use the condition WHERE staff_id IS NOT NULL inside the subquery.

This ensures that you correctly identify and display the staff members who are not
handling any subjects, and the results are sorted by staff name in ascending order.

Conclusion:

● Subqueries help to make SQL queries more dynamic and flexible.


● The inner query (subquery) runs first, returning data that the outer query
uses to filter or compute results.
● Using subqueries in this way allows you to avoid hardcoding values and
ensures the query works even as data changes over time.

Data Control Language (DCL) and Database Objects, several concepts related to
managing permissions, views, indexing, and optimizing database queries are
covered. Let's break down the key points discussed:

1. DCL Commands: Grant and Revoke

Grant: Used to give a user certain privileges (permissions) on database objects


(e.g., tables). For example, if a user should only have read access to a table, you
would use the GRANT command to allow SELECT permission.
sql
Copy code
GRANT SELECT ON table_name TO 'user';

Revoke: Cancels previously granted permissions. If a user no longer needs access


to a table, you can revoke the permissions.
sql
Copy code
REVOKE SELECT ON table_name FROM 'user';

2. Views and Virtual Tables


● A view is a virtual table in SQL. It doesn't store data but rather provides a way
to view data from other tables.
○ Simple View: Derived from a single table.
○ Complex View: Derived from multiple tables (using JOIN, etc.).

Example of creating a view:


sql
Copy code
CREATE VIEW policy_view AS

SELECT policy_id, policy_name

FROM policy;

● Views allow you to abstract complex queries and show only the data needed,
helping to simplify data access and improve security by controlling which data
a user can see.

Read-Only Views: In MySQL, there isn't a built-in option to make views read-only.
However, you can indirectly ensure read-only behavior by creating a user with
SELECT privileges only and using the SQL SECURITY DEFINER clause in the
CREATE VIEW statement.
Example:
sql
Copy code
CREATE VIEW policy_view

SQL SECURITY DEFINER

AS SELECT policy_id, policy_name FROM policy;

3. Inline Views

● An inline view is a subquery in the FROM clause of another SELECT


statement.
○ It's used to simplify complex queries by embedding a SELECT
statement directly in the FROM clause.

Example:
sql
Copy code
SELECT *
FROM (SELECT policy_id, policy_name FROM policy WHERE
policy_type = 'Health') AS subquery;

● Inline views are temporary and are only available during the execution of the
query.

4. Top N Analysis

● This involves retrieving the top N or bottom N records based on a column's


value (e.g., top 10 highest salaries).

Example for the top 10 highest salaries:


sql
Copy code
SELECT employee_name, salary

FROM employee

ORDER BY salary DESC

LIMIT 10;

5. Auto Increment

● The AUTO_INCREMENT option automatically generates unique values for a


column, typically used for primary key columns.
○ It starts with 1 by default but can be customized to start from a different
number.

Example:
sql
Copy code
CREATE TABLE customer (

customer_id INT AUTO_INCREMENT PRIMARY KEY,

customer_name VARCHAR(100)

);

6. Indexes
● Indexes are used to speed up query performance, especially on large tables.
They can be created on columns that are frequently searched or used in joins.
○ You can create an index at the time of table creation or after the table
has been created.

Example:
sql
Copy code
CREATE INDEX idx_policy_name ON policy(policy_name);


● Viewing and Dropping Indexes:
○ To view indexes: SHOW INDEX FROM table_name;

To drop an index:
sql
Copy code
DROP INDEX idx_policy_name ON policy;

7. Key Takeaways:

● DCL commands allow you to control user access to data using GRANT and
REVOKE.
● Views are used to simplify complex queries and control data access. Views
can be simple or complex and provide a virtual layer over actual data.
● Inline views are used for temporary query simplification and don't persist
beyond the query execution.
● Top N Analysis helps to retrieve the highest or lowest values from a dataset,
like the top 10 salaries.
● Auto Increment helps automatically generate unique values for columns,
typically used for primary keys.
● Indexes improve query performance, especially on large tables or columns
with a wide range of values.

What is a View?

● A view is a virtual table that does not store any data. Instead, it stores a
query definition that retrieves data from other tables when executed.
● Views are used to simplify complex queries and to ensure security by
exposing only relevant data to users.
● For example, if a table has many columns but you only want to show a few,
you can create a view to restrict which columns or rows are displayed.
View Syntax

To create a view, the syntax is similar to creating a table, but instead of defining a
structure, you specify a SELECT query.

sql

Copy code

CREATE OR REPLACE VIEW view_name AS

SELECT column1, column2, ...

FROM table_name

WHERE condition;

The CREATE OR REPLACE part ensures that if the view already exists, it will be
replaced with the new definition.

Example 1: Simple View

Consider an employee table with columns like employee_id, name, salary, etc.
You want to create a view showing only the employees from a specific department
(e.g., department ID 50,001).

sql

Copy code

CREATE OR REPLACE VIEW sales_employees AS

SELECT *

FROM employee

WHERE department_id = 50001;

Now, querying sales_employees will show only employees from department


50,001:

sql
Copy code

SELECT * FROM sales_employees;

Example 2: Complex View with Joins

In the case of a bus management system, you might need a view that joins data
from multiple tables, like users, tickets, and schedule.

1. Tables:
○ users: Contains user_id, username, etc.
○ tickets: Contains user_id, schedule_id, etc.
○ schedule: Contains schedule_id, source, destination, etc.
2. Goal: Create a view that shows user_id, username, source, and
destination from these tables.

sql

Copy code

CREATE OR REPLACE VIEW user_travel_details AS

SELECT u.user_id, u.username, s.source, s.destination

FROM users u

INNER JOIN tickets t ON u.user_id = t.user_id

INNER JOIN schedule s ON t.schedule_id = s.schedule_id

ORDER BY u.user_id;

This query joins the users, tickets, and schedule tables on their respective
keys, and then creates a view showing the travel details for each user, ordered by
user_id.

Key Points to Remember:

● Views simplify complex queries: By using views, you can abstract away the
complexity of complex JOINs and WHERE conditions.
● Security: Views allow you to control what data users can access. For
example, you can create a view that shows only relevant columns or rows,
hiding sensitive information.
● Performance: While views simplify data retrieval, they don't store data
themselves, so every time you query a view, it executes the underlying query.
● Ambiguity in Joins: When using joins from multiple tables that have common
column names (e.g., user_id in both users and tickets), specify the
table alias to avoid ambiguity (e.g., u.user_id vs. t.user_id).

Conclusion:

Views are a powerful tool for simplifying data access, improving security, and making
your SQL queries more readable and maintainable. By using views, you can create a
cleaner, more controlled way of interacting with your data.

1. Choose the Right Answer

1. What is a view in SQL?


○ A) A table that stores data
○ B) A stored procedure that manipulates data
○ C) A virtual table that stores query definitions
○ D) A backup of a database
2. Answer: C) A virtual table that stores query definitions
3. Which of the following is true about SQL views?
○ A) Views store data on disk
○ B) Views are always updated automatically when the underlying tables
are updated
○ C) Views can be indexed like regular tables
○ D) Views are primarily used for simplifying complex queries and
improving security
4. Answer: D) Views are primarily used for simplifying complex queries and
improving security
5. How do you create a view in SQL?
○ A) CREATE TABLE view_name AS SELECT ...
○ B) CREATE VIEW view_name AS SELECT ...
○ C) CREATE OR REPLACE VIEW view_name AS SELECT ...
○ D) CREATE PROCEDURE view_name AS SELECT ...
6. Answer: C) CREATE OR REPLACE VIEW view_name AS SELECT ...
7. Which SQL command is used to remove a view from the database?
○ A) DELETE VIEW
○ B) DROP VIEW
○ C) REMOVE VIEW
○ D) ALTER VIEW
8. Answer: B) DROP VIEW
2. Choose One or More Right Options

5. Which of the following are valid uses for SQL views? (Choose all that
apply)
○ A) To show only specific columns or rows from a table
○ B) To store data permanently
○ C) To simplify complex queries
○ D) To hide sensitive data from users
6. Answer: A) To show only specific columns or rows from a table, C) To simplify
complex queries, D) To hide sensitive data from users
7. Which of the following statements about views are true? (Choose all that
apply)
○ A) A view stores a subset of data from a table
○ B) A view can be used to prevent data modifications through the view
○ C) A view can be indexed like a table
○ D) A view is always updated when the underlying tables change
8. Answer: A) A view stores a subset of data from a table, B) A view can be
used to prevent data modifications through the view, D) A view is always
updated when the underlying tables change

3. True or False

7. True or False: A view in SQL physically stores the data it displays.


Answer: False
8. True or False: You can query a view in the same way you query a table in
SQL.
Answer: True
9. True or False: A view cannot be updated directly in SQL.
Answer: False (Though updating a view may not be allowed depending on its
complexity or the SQL system in use)
10. True or False: When you create a view, you must use the SELECT *
statement to retrieve all columns from the base tables.

Answer: False (You can select specific columns)

4. Match the Following

Match the SQL command with its purpose:


Command Purpose

1. CREATE OR A) Deletes a view from the database


REPLACE VIEW

2. SELECT * FROM B) Creates a virtual table based on a SELECT


view_name query

3. DROP VIEW C) Fetches data from a view as if it were a regular


table

4. ALTER VIEW D) Modifies the definition of an existing view

Answer: 1 - B) Creates a virtual table based on a SELECT query


2 - C) Fetches data from a view as if it were a regular table
3 - A) Deletes a view from the database
4 - D) Modifies the definition of an existing view

5. Fill in the Blanks

11. A view is a ________ table that contains a SQL query definition, which is
executed when queried.

Answer: virtual

12. To create a view, the correct SQL syntax is ________ followed by the
view name and the SELECT query.

Answer: CREATE OR REPLACE VIEW

6. Scenario-based Question
13. You have a table employees with 1000 rows and 50 columns. You want
to create a view that shows only the employee_id, name, and salary
columns for employees in department 50,001. What is the correct SQL
to create this view?

A)
sql
Copy code
CREATE VIEW sales_employees AS

SELECT employee_id, name, salary FROM employees WHERE


department_id = 50001;

B)
sql
Copy code
CREATE VIEW sales_employees AS

SELECT * FROM employees WHERE department_id = 50001;

C)
sql
Copy code
CREATE VIEW sales_employees AS

SELECT employee_id, name FROM employees WHERE department_id =


50001;

D)
sql
Copy code
CREATE VIEW sales_employees AS

SELECT employee_id, salary FROM employees WHERE department_id


= 50001;


Answer: A) sql CREATE VIEW sales_employees AS SELECT
employee_id, name, salary FROM employees WHERE department_id =
50001;

You might also like