0% found this document useful (0 votes)
9 views41 pages

VND - Openxmlformats Officedocument - Wordprocessingml.document&rendition 1 3

SQL (Structured Query Language) is a standardized programming language for managing relational databases, characterized by its declarative nature, structured syntax, and support for data integrity. It includes various commands for data definition, manipulation, control, and querying, along with support for multiple data types and operators. SQL's advantages include ease of use, high performance, and interoperability across different database management systems.

Uploaded by

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

VND - Openxmlformats Officedocument - Wordprocessingml.document&rendition 1 3

SQL (Structured Query Language) is a standardized programming language for managing relational databases, characterized by its declarative nature, structured syntax, and support for data integrity. It includes various commands for data definition, manipulation, control, and querying, along with support for multiple data types and operators. SQL's advantages include ease of use, high performance, and interoperability across different database management systems.

Uploaded by

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

Characteristics of SQL

SQL (Structured Query Language) is a standardized programming language used for


managing and manipulating relational databases. Its key characteristics include:

1. Declarative Nature: SQL allows users to specify what data they want without
detailing how to retrieve it. The database management system (DBMS) handles the
execution.
2. Structured Query Format: SQL uses a structured syntax with commands like
SELECT, INSERT, UPDATE, DELETE, and CREATE for data manipulation and
definition.
3. Relational Database Support: Designed for relational databases, SQL operates on
tables with rows and columns, supporting relationships via keys (primary, foreign).
4. Portability: SQL is standardized (e.g., ANSI/ISO standards), making it compatible
across various DBMS like MySQL, PostgreSQL, Oracle, and SQL Server.
5. Data Integrity: Supports constraints (e.g., NOT NULL, UNIQUE, FOREIGN KEY)
to ensure data accuracy and consistency.
6. Scalability: Handles small to large datasets efficiently, with optimization for complex
queries.
7. Data Manipulation and Definition: Includes Data Query Language (DQL), Data
Manipulation Language (DML), Data Definition Language (DDL), and Data Control
Language (DCL) for querying, modifying, defining, and controlling access.
8. Non-Procedural: Focuses on the result rather than the process, unlike procedural
languages like C or Java.
9. Client-Server Architecture: SQL is often used in client-server systems, allowing
multiple users to access databases concurrently.
10. Extensibility: Supports stored procedures, triggers, and user-defined functions for
advanced functionality.

Advantages of SQL

1. Ease of Use: Simple, English-like syntax makes it accessible to non-programmers and


developers alike.
2. Versatility: Supports a wide range of operations, from simple data retrieval to
complex joins, aggregations, and subqueries.
3. Standardization: Adheres to ANSI/ISO standards, ensuring portability and
consistency across different database systems.
4. High Performance: Optimized for efficient data retrieval and manipulation,
especially with large datasets, through indexing and query optimization.
5. Data Integrity and Security: Enforces constraints and provides robust access control
via GRANT and REVOKE commands.
6. Scalability: Can handle growing datasets and complex queries, suitable for small
applications to enterprise-level systems.
7. Interoperability: Works with various programming languages (e.g., Python, Java)
and tools through APIs and connectors.
8. Data Analysis: Supports powerful functions for aggregations (e.g., COUNT, SUM,
AVG) and grouping, ideal for analytics and reporting.
9. Community and Support: Widely used, with extensive documentation, community
resources, and support across multiple DBMS platforms.
10. Transaction Control: Ensures data consistency with transaction management
commands like COMMIT and ROLLBACK.

SQL Data Types

SQL data types define the type of data that can be stored in a column of a database table.
Different database management systems (DBMS) like MySQL, PostgreSQL, Oracle, and
SQL Server may have slight variations in data type names and specifications, but the core
categories are standardized. Below are the main categories of SQL data types with common
examples:

1. Numeric Data Types

Used to store numbers, either integers or decimals.

 Exact Numeric:
o INT or INTEGER: Whole numbers (e.g., 42, -10).
o SMALLINT: Smaller range integers (e.g., -32,768 to 32,767 in many DBMS).
o BIGINT: Larger range integers (e.g., -2^63 to 2^63-1).
o DECIMAL or NUMERIC(p, s): Fixed-point numbers with precision p (total digits)
and scale s (decimal places) (e.g., 123.45 for NUMERIC(5,2)).
 Approximate Numeric:
o FLOAT(p): Floating-point numbers with precision p.
o REAL: Single-precision floating-point.
o DOUBLE PRECISION: Double-precision floating-point.

2. Character/String Data Types

Used to store text or character data.

 CHAR(n): Fixed-length string of n characters (padded with spaces if shorter).


 VARCHAR(n) or CHARACTER VARYING(n): Variable-length string with a maximum of n
characters.
 TEXT: Variable-length string with no specific upper limit (DBMS-specific).
 NCHAR(n) and NVARCHAR(n): Fixed or variable-length strings for Unicode characters.

3. Date and Time Data Types

Used to store temporal data.

 DATE: Stores a date (e.g., '2025-09-17').


 TIME: Stores time of day (e.g., '10:37:00').
 TIMESTAMP: Stores date and time (e.g., '2025-09-17 10:37:00').
 INTERVAL: Represents a time duration (e.g., '2 years 3 months').

4. Boolean Data Type

 BOOLEAN: Stores TRUE, FALSE, or NULL (supported in some DBMS like PostgreSQL;
others use integers or other types to simulate).

5. Binary Data Types

Used for non-textual data like images or files.

 BINARY(n): Fixed-length binary string of n bytes.


 VARBINARY(n): Variable-length binary string up to n bytes.
 BLOB: Binary Large Object for large binary data (e.g., images, videos).

6. Other Data Types

 CLOB: Character Large Object for large text data.


 JSON or JSONB: Stores JSON data (supported in modern DBMS like PostgreSQL, MySQL).
 XML: Stores XML data (supported in some DBMS like Oracle, SQL Server).
 ARRAY: Stores arrays (supported in PostgreSQL, not standard in all DBMS).
 UUID: Stores universally unique identifiers (e.g., '123e4567-e89b-12d3-a456-
426614174000').

Note: Specific data types and their sizes may vary by DBMS. For example, MySQL uses
TINYINT for small integers, while PostgreSQL uses SERIAL for auto-incrementing integers.

SQL Literals

Literals are fixed values explicitly written in SQL queries to represent data. They are used in
statements like SELECT, INSERT, or WHERE clauses. SQL supports several types of
literals, corresponding to data types:

1. Numeric Literals

Represent numbers, either exact or approximate.

 Integer: Whole numbers, e.g., 42, -10, 0.


 Decimal/Floating-Point: Numbers with decimals, e.g., 3.14, -0.001, 1.23e-4 (scientific
notation).
 Example: SELECT 100 AS number; or INSERT INTO prices (cost) VALUES (19.99);.

2. String Literals

Represent text or character data, enclosed in single quotes (').

 Example: 'Hello, World!', 'John Doe'.


 To include a single quote in the string, escape it with another single quote: 'It''s a test'.
 Some DBMS (e.g., MySQL) also support double quotes (") for strings, but single quotes are
standard.
 Example: SELECT 'Alice' AS name; or WHERE username = 'bob123';.

3. Boolean Literals

Represent true or false values (in DBMS that support BOOLEAN).

 Values: TRUE, FALSE, NULL.


 Example: SELECT TRUE AS is_active; or WHERE condition = FALSE;.
 In DBMS without BOOLEAN, integers (1 for true, 0 for false) or other conventions may be
used.

4. Date and Time Literals

Represent temporal values, often enclosed in single quotes and formatted according to the
DBMS.

 Date: '2025-09-17' (format: YYYY-MM-DD).


 Time: '10:37:00' (format: HH:MM:SS).
 Timestamp: '2025-09-17 10:37:00'.
 Example: INSERT INTO events (event_date) VALUES ('2025-09-17');.
 Some DBMS require specific prefixes, e.g., Oracle uses TO_DATE('2025-09-17', 'YYYY-
MM-DD').

5. Binary Literals

Represent binary data, often using hexadecimal notation or specific keywords.

 Example: 0x48656C6C6F (hex for 'Hello' in some DBMS like MySQL).


 Example: SELECT X'414243'; (hex for 'ABC' in SQL Server).

6. NULL Literal

Represents an unknown or missing value.

 Example: INSERT INTO employees (phone) VALUES (NULL);.


 NULL is not equal to zero, an empty string, or any other value.

7. Other Literals

 JSON: In DBMS supporting JSON, literals are written as JSON strings, e.g., '{"name":
"John", "age": 30}'.
 Interval: Represents time durations, e.g., INTERVAL '1 day' (PostgreSQL-specific).
 Example: SELECT '{"key": "value"}'::JSON AS json_data; (PostgreSQL).

Types of SQL commands.


SQL (Structured Query Language) commands are categorized based on their functionality in
managing and manipulating relational databases. These commands are grouped into four
main types, with an additional category for transaction control. Below is a concise overview
of the types of SQL commands, their purposes, and examples:

1. Data Definition Language (DDL)

DDL commands define and modify the structure of database objects like tables, schemas, and
indexes.

 Purpose: Create, alter, or delete database structures.


 Characteristics: Changes are often permanent and may auto-commit in some DBMS.
 Examples:
o CREATE: Creates a new table or database object.
 CREATE TABLE employees (id INT, name VARCHAR(50));
o ALTER: Modifies an existing object.
 ALTER TABLE employees ADD email VARCHAR(100);
o DROP: Deletes an object.
 DROP TABLE employees;
o TRUNCATE: Removes all rows from a table without deleting its structure.
 TRUNCATE TABLE employees;
o RENAME: Renames a database object (DBMS-specific).
 RENAME TABLE employees TO staff;

2. Data Manipulation Language (DML)

DML commands manage the data within tables, allowing insertion, updating, deletion, and
retrieval.

 Purpose: Manipulate data stored in the database.


 Examples:
o SELECT: Retrieves data from one or more tables.
 SELECT name, salary FROM employees WHERE dept = 'IT';
o INSERT: Adds new rows to a table.
 INSERT INTO employees (id, name) VALUES (1, 'Alice');
o UPDATE: Modifies existing data in a table.
 UPDATE employees SET salary = salary + 5000 WHERE id = 1;
o DELETE: Removes rows from a table.
 DELETE FROM employees WHERE id = 1;

3. Data Control Language (DCL)

DCL commands manage access permissions and security levels for database objects.

 Purpose: Define user roles, permissions, and access controls.


 Examples:
o GRANT: Assigns privileges to users.
 GRANT SELECT, INSERT ON employees TO user1;
o REVOKE: Removes privileges from users.
 REVOKE DELETE ON employees FROM user1;

4. Data Query Language (DQL)

DQL commands are used to query and retrieve data from the database. Technically, DQL is a
subset of DML, but it’s often listed separately due to its focus on data retrieval.

 Purpose: Fetch data based on specific conditions.


 Example:
o SELECT: Retrieves data (the primary DQL command).
 SELECT * FROM employees WHERE salary > 50000;

5. Transaction Control Language (TCL)

TCL commands manage transactions to ensure data integrity and consistency.

 Purpose: Control the execution of DML commands within a transaction.


 Examples:
o COMMIT: Saves all changes made in the current transaction.
 COMMIT;
o ROLLBACK: Undoes changes made in the current transaction.
 ROLLBACK;
o SAVEPOINT: Sets a point within a transaction to roll back to.
 SAVEPOINT savepoint1;
o SET TRANSACTION: Configures transaction properties (e.g., read-only).
 SET TRANSACTION READ ONLY;

Notes

 DBMS Variations: Some commands (e.g., RENAME, TRUNCATE) may have


DBMS-specific syntax or limitations (e.g., MySQL, PostgreSQL, Oracle).
 Case Sensitivity: SQL commands are generally case-insensitive, but data values (e.g.,
in strings) may be case-sensitive depending on the DBMS.
 Comprehensive Use: Most SQL operations combine these command types. For
example, DDL creates a table, DML populates it, DCL secures it, and TCL ensures
transactional integrity.

SQL operators and their procedure.

SQL operators are special symbols or keywords used to perform operations on data within
SQL queries, such as comparisons, arithmetic, logical operations, and more. They are integral
to constructing queries for filtering, calculating, and combining data in relational databases.
Below is a concise overview of the main types of SQL operators, their purposes, and how
they are used (their "procedure").

Types of SQL Operators

1. Arithmetic Operators

Used to perform mathematical operations on numeric data.

 Operators:
o +: Addition (e.g., 5 + 3 = 8)
o -: Subtraction (e.g., 5 - 3 = 2)
o *: Multiplication (e.g., 5 * 3 = 15)
o /: Division (e.g., 6 / 2 = 3)
o %: Modulus (remainder of division, e.g., 7 % 2 = 1)
 Procedure:
o Used in SELECT, WHERE, or other clauses to compute values.
o Operands are typically numeric columns, literals, or expressions.
o Example: SELECT salary * 1.1 AS new_salary FROM employees;
 Increases salary by 10% and returns the result as new_salary.
o Example: SELECT id, quantity % 10 AS remainder FROM inventory;
 Returns the remainder of quantity divided by 10.

2. Comparison Operators

Used to compare values, typically in WHERE or HAVING clauses, to filter data.

 Operators:
o =: Equal to
o != or <>: Not equal to
o <: Less than
o >: Greater than
o <=: Less than or equal to
o >=: Greater than or equal to
 Procedure:
o Compare columns, literals, or expressions to filter rows.
o Often used in WHERE to define conditions.
o Example: SELECT name FROM employees WHERE salary > 50000;
 Retrieves names of employees with a salary greater than 50,000.
o Example: SELECT product FROM items WHERE price != 0;
 Returns products with non-zero prices.

3. Logical Operators

Combine multiple conditions to form complex queries.

 Operators:
o AND: True if all conditions are true.
o OR: True if at least one condition is true.
o NOT: Negates a condition.
 Procedure:
o Used in WHERE or HAVING to combine conditions.
o Example: SELECT name FROM employees WHERE dept = 'IT' AND salary >
60000;
 Retrieves names of employees in the IT department with a salary above
60,000.
o Example: SELECT name FROM employees WHERE dept = 'HR' OR dept = 'Sales';
 Retrieves names of employees in either HR or Sales.
o Example: SELECT name FROM employees WHERE NOT dept = 'IT';
 Retrieves names of employees not in the IT department.

4. Concatenation Operator

Combines strings or text values.

 Operator:
o || (standard SQL, used in PostgreSQL) or + (in SQL Server).
o Some DBMS (e.g., MySQL) use CONCAT() function instead.
 Procedure:
o Combines string literals, columns, or expressions into a single string.
o Example: SELECT first_name || ' ' || last_name AS full_name FROM employees;
 Concatenates first_name and last_name with a space (PostgreSQL).
o Example (MySQL): SELECT CONCAT(first_name, ' ', last_name) AS full_name
FROM employees;
 Same result using MySQL’s CONCAT() function.

5. Bitwise Operators

Perform bit-level operations on integer or binary data.

 Operators:
o &: Bitwise AND
o |: Bitwise OR
o ^: Bitwise XOR
o ~: Bitwise NOT (DBMS-specific)
 Procedure:
o Used for low-level operations on binary data (less common in typical SQL queries).
o Example: SELECT 5 & 3 AS result; (Result: 1, as 5 = 0101 and 3 = 0011, so 0101 &
0011 = 0001).
o Supported in DBMS like PostgreSQL, MySQL, and SQL Server.

6. Set Operators

Combine or compare results from multiple SELECT queries.

 Operators:
o UNION: Combines rows from two queries, removing duplicates.
o UNION ALL: Combines rows, keeping duplicates.
o INTERSECT: Returns rows common to both queries.
o EXCEPT (or MINUS in Oracle): Returns rows in the first query not in the second.
 Procedure:
o Used between two SELECT statements with compatible column types and counts.
o Example: SELECT name FROM employees WHERE dept = 'IT' UNION SELECT
name FROM contractors WHERE dept = 'IT';
 Combines unique names from employees and contractors in the IT
department.
o Example: SELECT id FROM orders INTERSECT SELECT id FROM returns;
 Returns IDs present in both orders and returns (supported in PostgreSQL,
SQL Server).

7. Special Operators

Handle specific conditions or patterns.

 Operators:
o LIKE: Matches patterns in strings (uses % for zero or more characters, _ for a single
character).
 Example: SELECT name FROM employees WHERE name LIKE 'A%';
 Retrieves names starting with 'A'.
o IN: Checks if a value is in a list.
 Example: SELECT name FROM employees WHERE dept IN ('IT', 'HR');
 Retrieves names of employees in IT or HR.
o BETWEEN: Checks if a value is within a range (inclusive).
 Example: SELECT name FROM employees WHERE salary BETWEEN
40000 AND 60000;
 Retrieves names of employees with salaries between 40,000 and
60,000.
o IS NULL / IS NOT NULL: Checks for NULL values.
 Example: SELECT name FROM employees WHERE phone IS NULL;
 Retrieves names of employees with no phone number.
o EXISTS: Tests for the existence of rows in a subquery.
 Example: SELECT name FROM departments WHERE EXISTS (SELECT 1
FROM employees WHERE dept_id = departments.id);
 Retrieves departments with at least one employee.

Procedure for Using SQL Operators

1. Identify the Context: Determine where the operator is needed (e.g., SELECT for
calculations, WHERE for filtering, or between SELECT statements for set operations).
2. Choose the Operator: Select the appropriate operator based on the operation (e.g., + for
arithmetic, AND for logical conditions, LIKE for pattern matching).
3. Construct the Query:
o Ensure operands (columns, literals, or expressions) are compatible with the operator
(e.g., numeric for arithmetic, strings for LIKE).
o Place the operator in the correct clause (e.g., WHERE for comparisons, SELECT for
arithmetic or concatenation).
4. Test and Validate: Run the query and verify the results, ensuring the operator behaves as
expected (e.g., check for case sensitivity in LIKE or NULL handling).
5. DBMS-Specific Considerations: Check for DBMS-specific syntax (e.g., || vs. CONCAT(),
or EXCEPT vs. MINUS in Oracle).

Notes

 Operator Precedence: SQL follows a precedence order (e.g., arithmetic before comparison,
AND before OR). Use parentheses to enforce specific evaluation order, e.g., WHERE (salary
> 50000 AND dept = 'IT') OR dept = 'HR'.
 DBMS Variations: Some operators (e.g., EXISTS, INTERSECT, EXCEPT) may not be
supported in all DBMS (e.g., MySQL lacks INTERSECT and EXCEPT).
 NULL Handling: Operators involving NULL often yield NULL (e.g., 5 + NULL = NULL).
Use IS NULL instead of = NULL for comparisons.

Tables, views and indexes


n SQL, tables, views, and indexes are fundamental database objects used to store, organize,
and optimize data in relational databases. Below is a concise explanation of each, their
characteristics, and their roles, along with how they are created and used.

1. Tables

Definition

A table is the primary structure for storing data in a relational database, organized in rows
and columns, where each column has a specific data type, and each row represents a record.

Characteristics

 Structure: Consists of columns (attributes) with defined data types (e.g., INT, VARCHAR)
and rows (data entries).
 Primary Storage: Directly stores the actual data.
 Constraints: Supports constraints like PRIMARY KEY, FOREIGN KEY, NOT NULL,
UNIQUE, and CHECK to ensure data integrity.
 Persistence: Data persists until explicitly modified or deleted.

Creation and Usage

 Creation (DDL):

sql

CREATE TABLE employees (


id INT PRIMARY KEY,
name VARCHAR(50) NOT NULL,
salary DECIMAL(10,2),
dept_id INT,
FOREIGN KEY (dept_id) REFERENCES departments(id)
);

o Creates a table employees with columns id, name, salary, and dept_id.
 Usage (DML):
o Insert: INSERT INTO employees (id, name, salary, dept_id) VALUES (1, 'Alice',
60000, 10);
o Query: SELECT name, salary FROM employees WHERE dept_id = 10;
o Update: UPDATE employees SET salary = 65000 WHERE id = 1;
o Delete: DELETE FROM employees WHERE id = 1;

Advantages

 Stores raw data.


 Supports relationships via keys.
 Flexible for all types of data operations (CRUD: Create, Read, Update, Delete).

2. Views

Definition

A view is a virtual table derived from a query on one or more tables or other views. It does
not store data physically but provides a dynamic, query-based representation of data.

Characteristics

 Virtual: Does not store data; it’s a saved SELECT query executed when accessed.
 Dynamic: Reflects changes in the underlying tables automatically.
 Security: Can restrict access to specific columns or rows (e.g., hide sensitive data).
 Simplification: Simplifies complex queries by encapsulating them.
 Updatable: Some views (e.g., simple views based on one table) can be updated, depending
on the DBMS.

Creation and Usage

 Creation (DDL):

sql

CREATE VIEW it_employees AS


SELECT id, name, salary
FROM employees
WHERE dept_id = 10;

o Creates a view showing only employees in department 10.


 Usage (DQL/DML):
o Query: SELECT * FROM it_employees WHERE salary > 50000;
 Treats the view like a table for querying.
o Update (if updatable): UPDATE it_employees SET salary = 70000 WHERE id = 1;
 Updates the underlying employees table (if allowed by the DBMS).
 Modification/Drop:
o Alter: CREATE OR REPLACE VIEW it_employees AS ... (updates the view
definition).
o Drop: DROP VIEW it_employees;

Advantages

 Simplifies complex queries.


 Enhances security by limiting data exposure.
 Provides a reusable, abstracted view of data.

Limitations

 No physical storage, so performance depends on the underlying query.


 Complex views (e.g., with joins or aggregations) may not be updatable.
 DBMS-specific restrictions on view functionality.

3. Indexes

Definition

An index is a database structure that improves the speed of data retrieval operations on a table
at the cost of additional storage and maintenance overhead.

Characteristics

 Performance Optimization: Speeds up SELECT queries and WHERE clause filtering by


creating a sorted data structure (e.g., B-tree or hash).
 Storage: Physically stored, separate from the table, but references table data.
 Types:
o Clustered: Determines the physical order of data in the table (one per table).
o Non-clustered: Separate structure with pointers to table data (multiple allowed).
o Unique: Ensures no duplicate values (e.g., on PRIMARY KEY or UNIQUE
columns).
o Composite: Indexes multiple columns together.
 Trade-off: Faster reads but slower writes (INSERT, UPDATE, DELETE) due to index
maintenance.

Creation and Usage

 Creation (DDL):

sql

CREATE INDEX idx_employee_name ON employees(name);

o Creates a non-clustered index on the name column of the employees table.


o Unique index: CREATE UNIQUE INDEX idx_employee_id ON employees(id);
 Usage:
o Automatically used by the DBMS query optimizer for queries like:

sql

SELECT * FROM employees WHERE name = 'Alice';

 The index speeds up the search for name = 'Alice'.


 Modification/Drop:
o Drop: DROP INDEX idx_employee_name;
o Alter (DBMS-specific): Some systems allow rebuilding or reorganizing indexes (e.g.,
ALTER INDEX idx_employee_name REBUILD; in SQL Server).

Advantages

 Significantly improves query performance for large datasets.


 Supports faster searches, joins, and sorting.
 Essential for frequently queried columns (e.g., primary keys, foreign keys).

Limitations

 Increases storage requirements.


 Slows down write operations (INSERT, UPDATE, DELETE).
 Requires maintenance (e.g., rebuilding fragmented indexes).

Comparison
Feature Table View Index

Virtual representation of
Purpose Stores actual data Optimizes data retrieval
data

Storage Physical Virtual (no data storage) Physical (separate structure)

Creation CREATE TABLE CREATE VIEW CREATE INDEX

Direct (CRUD Query-only (or limited


Data Access Indirect (enhances queries)
operations) DML)

Depends on query
Performance Standard access Improves read performance
complexity

Auto-maintained, may need


Maintenance Constraints, triggers Updates with base table
rebuild

Procedures for Use

1. Tables:
o Define the schema with appropriate data types and constraints.
o Use DDL to create (CREATE TABLE) and modify (ALTER TABLE, DROP
TABLE).
o Use DML for data operations (INSERT, SELECT, UPDATE, DELETE).
2. Views:
o Create with a SELECT query to encapsulate logic or restrict data.
o Query like a table; update if simple and allowed by the DBMS.
o Modify or drop as needed (CREATE OR REPLACE VIEW, DROP VIEW).
3. Indexes:
o Identify frequently queried columns (e.g., in WHERE, JOIN, or ORDER BY).
o Create indexes on those columns, balancing read vs. write performance.
o Monitor and maintain indexes (e.g., rebuild fragmented indexes in large databases).

Notes

 DBMS Variations: Syntax and features vary slightly across DBMS (e.g., MySQL uses
InnoDB for clustered indexes, PostgreSQL supports materialized views for physical storage).
 Performance Tuning: Indexes should be created strategically; too many can degrade write
performance.
 Security with Views: Use views to hide sensitive columns (e.g., salary) while exposing non-
sensitive data (e.g., name).
 Materialized Views: Some DBMS (e.g., PostgreSQL, Oracle) support materialized views,
which store data physically and need periodic refreshing.

Queries and sub queries.

In SQL, queries and subqueries are essential for retrieving and manipulating data from
relational databases. A query is a request for data or action, typically using the SELECT
statement, while a subquery is a query nested within another query to provide intermediate
results. Below is a concise explanation of queries and subqueries, their characteristics, types,
and how they are used.

1. Queries

Definition

A query is an SQL statement, primarily using SELECT, that retrieves data from one or more
tables or views based on specified conditions. Queries can also include other DML
commands (INSERT, UPDATE, DELETE) or combine with DDL/DCL/TCL for broader
database operations.

Characteristics

 Purpose: Retrieve, insert, update, or delete data.


 Structure: Typically includes clauses like SELECT, FROM, WHERE, GROUP BY,
HAVING, ORDER BY, and JOIN.
 Output: Returns a result set (rows and columns) for SELECT queries or modifies data for
other DML operations.
 Scope: Operates on tables, views, or derived results from other queries.

Types of Queries

1. Simple Query:
o Retrieves data from a single table.
o Example:
sql

SELECT name, salary FROM employees WHERE salary > 50000;

 Returns names and salaries of employees earning more than 50,000.


2. Join Query:
o Combines data from multiple tables using JOIN.
o Example:

sql

SELECT e.name, d.dept_name


FROM employees e
JOIN departments d ON e.dept_id = d.id;

 Joins employees and departments to show employee names and their


department names.
3. Aggregate Query:
o Uses aggregate functions (COUNT, SUM, AVG, MIN, MAX) with GROUP BY.
o Example:

sql

SELECT dept_id, AVG(salary) AS avg_salary


FROM employees
GROUP BY dept_id
HAVING AVG(salary) > 60000;

 Returns the average salary per department where the average exceeds 60,000.
4. Set Query:
o Combines results from multiple SELECT statements using UNION, INTERSECT, or
EXCEPT.
o Example:

sql

SELECT name FROM employees WHERE dept_id = 10


UNION
SELECT name FROM contractors WHERE dept_id = 10;
 Combines unique names from employees and contractors in department 10.

Procedure for Queries

1. Identify the data needed (columns, tables).


2. Construct the query using appropriate clauses (SELECT, FROM, WHERE, etc.).
3. Add conditions (WHERE), joins, or aggregations as needed.
4. Test the query to ensure correct results.
5. Optimize using indexes or query restructuring if performance is slow.

2. Subqueries

Definition

A subquery (or inner query) is a query nested within another query (outer query), enclosed in
parentheses. It executes first, and its result is used by the outer query to produce the final
output.

Characteristics

 Nested Structure: Executes within a larger query, typically in WHERE, SELECT, FROM, or
HAVING clauses.
 Single or Multi-Row: Returns a single value, single row, single column, or multiple
rows/columns, depending on its use.
 Execution: The subquery runs first, and its result is passed to the outer query.
 Correlation:
o Non-correlated Subquery: Independent of the outer query, runs once.
o Correlated Subquery: Depends on the outer query, runs for each row of the outer
query.
 Purpose: Filters data, computes intermediate results, or checks conditions.

Types of Subqueries

1. Single-Row Subquery:
o Returns one row and one column, used with operators like =, >, <.
o Example:

sql
SELECT name
FROM employees
WHERE salary = (SELECT MAX(salary) FROM employees);

 Returns the name of the employee with the highest salary.


2. Multi-Row Subquery:
o Returns multiple rows, used with operators like IN, ANY, ALL.
o Example:

sql

SELECT name
FROM employees
WHERE dept_id IN (SELECT id FROM departments WHERE location = 'New York');

 Returns names of employees in departments located in New York.


3. Correlated Subquery:
o References columns from the outer query, executed repeatedly for each row.
o Example:

sql

SELECT name
FROM employees e
WHERE EXISTS (SELECT 1 FROM departments d WHERE d.id = e.dept_id AND d.budget
> 100000);

 Returns names of employees in departments with a budget over 100,000.


4. Subquery in SELECT or FROM:
o Used to compute values or act as a derived table.
o Example (in SELECT):

sql

SELECT name, (SELECT AVG(salary) FROM employees) AS avg_salary


FROM employees;

 Returns each employee’s name and the average salary across all employees.
o Example (in FROM):
sql

SELECT dept_id, avg_salary


FROM (SELECT dept_id, AVG(salary) AS avg_salary FROM employees GROUP BY
dept_id) AS dept_stats
WHERE avg_salary > 60000;

 Treats the subquery as a derived table to filter departments by average salary.

Procedure for Subqueries

1. Identify the need for a subquery (e.g., to filter based on a condition from another table or
compute an intermediate result).
2. Write the subquery to return the required data (single value, single column, or multiple rows).
3. Embed the subquery in parentheses within the outer query’s WHERE, SELECT, or FROM
clause.
4. Use appropriate operators (=, IN, EXISTS, etc.) based on the subquery’s output.
5. Test the query to ensure correctness and optimize (e.g., consider joins as alternatives for
better performance).

Key Differences Between Queries and Subqueries

Feature Query Subquery

Definition Independent SQL statement Nested query within another query

Execution Executes standalone Executes first, feeds outer query

Scope Produces final result or action Provides intermediate result

Location Standalone or outer query Inside WHERE, SELECT, FROM, etc.

Output Full result set or data change Single value, row, or column(s)

Advantages of Subqueries

 Break complex problems into manageable parts.


 Enable dynamic filtering based on computed results.
 Useful for checking existence (EXISTS) or comparing against aggregates (MAX, AVG).
Limitations of Subqueries

 Performance: Correlated subqueries can be slow as they execute for each row of the outer
query.
 Complexity: Nested subqueries can make queries harder to read and maintain.
 Alternatives: Joins or Common Table Expressions (CTEs) may be more efficient in some
cases.

Notes

 DBMS Variations: Most DBMS (e.g., MySQL, PostgreSQL, SQL Server) support
subqueries, but features like EXISTS or ALL may vary in implementation.
 Optimization: Subqueries can sometimes be replaced with JOIN for better performance,
especially for non-correlated subqueries.
 CTEs as Alternatives: Common Table Expressions (WITH clause) can simplify complex
subqueries:

sql

WITH dept_stats AS (
SELECT dept_id, AVG(salary) AS avg_salary
FROM employees
GROUP BY dept_id
)
SELECT dept_id, avg_salary
FROM dept_stats
WHERE avg_salary > 60000;

o Achieves the same result as a subquery in FROM but is more readable.

Aggregate functions:

Aggregate Functions in SQL

Aggregate functions in SQL perform calculations on a set of values (typically a column) and
return a single summarized result. They are commonly used with the GROUP BY clause to
compute summaries for groups of rows or with the entire result set in a query. These
functions are essential for data analysis, reporting, and summarizing large datasets.
Characteristics of Aggregate Functions

 Input: Operate on a set of values (e.g., a column or expression).


 Output: Return a single value (e.g., sum, average, count).
 Usage: Often used in SELECT or HAVING clauses.
 NULL Handling: Most aggregate functions ignore NULL values, except for
COUNT(*) which counts all rows.
 Grouping: When used with GROUP BY, they compute results for each group;
without GROUP BY, they aggregate the entire result set.

Common Aggregate Functions

Below is a list of the most commonly used SQL aggregate functions, their purposes, and
examples:

1. COUNT
o Purpose: Counts the number of rows or non-NULL values in a column.
o Syntax: COUNT(*) (counts all rows) or COUNT(column_name) (counts non-
NULL values in the column).
o Example:

sql

SELECT COUNT(*) AS total_employees


FROM employees;

 Returns the total number of rows in the employees table.


o Example with Condition:

sql

SELECT dept_id, COUNT(*) AS emp_count


FROM employees
GROUP BY dept_id;

 Counts employees per department.


2. SUM
o Purpose: Calculates the total sum of numeric values in a column.
o Syntax: SUM(column_name)
o Example:

sql

SELECT SUM(salary) AS total_salary


FROM employees
WHERE dept_id = 10;

 Returns the total salary of employees in department 10.


o Note: Ignores NULL values; works on numeric data types (INT, DECIMAL,
etc.).
3. AVG
o Purpose: Computes the average (arithmetic mean) of numeric values in a
column.
o Syntax: AVG(column_name)
o Example:

sql

SELECT dept_id, AVG(salary) AS avg_salary


FROM employees
GROUP BY dept_id
HAVING AVG(salary) > 60000;

 Returns the average salary per department where the average exceeds
60,000.
o Note: Ignores NULL values.
4. MIN
o Purpose: Finds the smallest value in a column (works on numeric, string, or
date/time data).
o Syntax: MIN(column_name)
o Example:

sql
SELECT MIN(salary) AS lowest_salary
FROM employees;

 Returns the lowest salary in the employees table.


o Example with Strings:

sql

SELECT MIN(name) AS first_name


FROM employees;

 Returns the alphabetically first name.


5. MAX
o Purpose: Finds the largest value in a column (works on numeric, string, or
date/time data).
o Syntax: MAX(column_name)
o Example:

sql

SELECT MAX(hire_date) AS latest_hire


FROM employees;

 Returns the most recent hire date.


o Example with Grouping:

sql

SELECT dept_id, MAX(salary) AS highest_salary


FROM employees
GROUP BY dept_id;

 Returns the highest salary in each department.

Less Common Aggregate Functions (DBMS-Specific)

Some DBMS offer additional aggregate functions:

 STDDEV (Standard Deviation): Measures data dispersion (e.g., PostgreSQL, Oracle).


o Example: SELECT STDDEV(salary) FROM employees;
 VARIANCE: Calculates the variance of values (e.g., PostgreSQL, SQL Server).
o Example: SELECT VARIANCE(salary) FROM employees;
 STRING_AGG or GROUP_CONCAT (String Aggregation): Concatenates values
into a single string (e.g., PostgreSQL: STRING_AGG, MySQL: GROUP_CONCAT).
o Example (PostgreSQL):

sql

SELECT dept_id, STRING_AGG(name, ', ') AS employee_names


FROM employees
GROUP BY dept_id;

 Concatenates employee names per department, separated by commas.

Procedure for Using Aggregate Functions

1. Identify the Aggregation Need: Determine what summary is required (e.g., count,
sum, average).
2. Select the Function: Choose the appropriate function (COUNT, SUM, etc.).
3. Specify the Scope:
o Use in SELECT for the result set or HAVING to filter groups.
o Combine with GROUP BY to aggregate by categories (e.g., by department).
4. Handle NULLs: Ensure the function’s NULL handling aligns with the requirement
(most ignore NULL except COUNT(*)).
5. Test and Optimize:
o Verify the output matches expectations.
o Use indexes on columns involved in GROUP BY or WHERE for better
performance.

Key Points

 GROUP BY Clause:
o Required when aggregating by groups; non-aggregated columns in SELECT
must appear in GROUP BY.
o Example:
sql

SELECT dept_id, COUNT(*) AS emp_count, AVG(salary) AS avg_salary


FROM employees
GROUP BY dept_id;

 HAVING Clause:
o Filters groups after aggregation (unlike WHERE, which filters rows before).
o Example:

sql

SELECT dept_id, SUM(salary) AS total_salary


FROM employees
GROUP BY dept_id
HAVING SUM(salary) > 100000;

 NULL Handling: Aggregate functions (except COUNT(*)) skip NULL values,


which may affect results.
o Example: SUM(salary) ignores rows where salary is NULL.
 Subqueries with Aggregates:
o Aggregate functions are often used in subqueries to compute values for
comparisons.
o Example:

sql

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

 Returns employees with above-average salaries.


 DBMS Variations:
o Most aggregate functions (COUNT, SUM, AVG, MIN, MAX) are standard
across DBMS (MySQL, PostgreSQL, SQL Server, Oracle).
o Functions like STRING_AGG or GROUP_CONCAT are DBMS-specific.
o Some DBMS require explicit handling of empty result sets (e.g.,
COALESCE(AVG(salary), 0)).
Notes

 Performance: Aggregations on large datasets can be slow; indexes on GROUP BY or


WHERE columns can help.
 Distinct Option: Most functions support DISTINCT to aggregate unique values.
o Example: COUNT(DISTINCT dept_id) counts unique department IDs.
 Alternatives: Window functions (e.g., ROW_NUMBER(), RANK()) can provide
more flexible aggregations without collapsing rows.

Insert, update and delete operations, Joins,

Unions, Intersection, Minus, Cursors, Triggers, Procedures in


SQL/PL SQL

Below is a comprehensive overview of INSERT, UPDATE, DELETE operations, Joins,


Unions, Intersection, Minus, Cursors, Triggers, and Procedures in SQL and PL/SQL,
focusing on their purpose, syntax, and usage. Each section includes examples and procedures
for clarity, tailored to standard SQL with notes on PL/SQL where applicable.

1. INSERT, UPDATE, and DELETE Operations

These are Data Manipulation Language (DML) operations used to modify data in tables.

a. INSERT

 Purpose: Adds new rows to a table.


 Syntax:

sql

INSERT INTO table_name (column1, column2, ...) VALUES (value1, value2, ...);

o Alternative (insert from a query):

sql
INSERT INTO table_name (column1, column2, ...) SELECT column1, column2, ... FROM
another_table WHERE condition;

 Procedure:

1. Specify the table and columns to insert data into.


2. Provide values for the columns (or a SELECT query).
3. Ensure values match the column data types and constraints (e.g., NOT NULL,
FOREIGN KEY).
4. Execute and verify the insertion.
 Example:

sql

INSERT INTO employees (id, name, salary, dept_id) VALUES (1, 'Alice', 60000, 10);

o Inserts a single row into the employees table.


 Example (from query):

sql

INSERT INTO archived_employees (id, name, salary)


SELECT id, name, salary FROM employees WHERE hire_date < '2020-01-01';

o Copies employees hired before 2020 into archived_employees.

b. UPDATE

 Purpose: Modifies existing rows in a table.


 Syntax:

sql

UPDATE table_name SET column1 = value1, column2 = value2, ... WHERE condition;

 Procedure:
1. Identify the table and columns to update.
2. Set new values using expressions or literals.
3. Use a WHERE clause to target specific rows (omit for all rows, but use cautiously).
4. Verify the changes.
 Example:

sql

UPDATE employees SET salary = salary * 1.1 WHERE dept_id = 10;

o Increases salaries by 10% for employees in department 10.


 Example with Subquery:

sql

UPDATE employees
SET salary = (SELECT AVG(salary) FROM employees WHERE dept_id = employees.dept_id)
WHERE dept_id = 20;

o Sets each employee’s salary in department 20 to the department’s average salary.

c. DELETE

 Purpose: Removes rows from a table.


 Syntax:

sql

DELETE FROM table_name WHERE condition;

 Procedure:
1. Specify the table to delete from.
2. Use a WHERE clause to target specific rows (omit to delete all rows, but use
cautiously).
3. Verify the deletion.
 Example:

sql

DELETE FROM employees WHERE hire_date < '2015-01-01';

o Deletes employees hired before 2015.


 Example with Subquery:

sql
DELETE FROM employees WHERE dept_id IN (SELECT id FROM departments WHERE location =
'Chicago');

o Deletes employees in departments located in Chicago.

Notes

 Transaction Control: Use COMMIT to save changes or ROLLBACK to undo (especially in


PL/SQL).
 Constraints: Ensure operations comply with table constraints (e.g., foreign keys may prevent
deletion).
 Performance: Large UPDATE or DELETE operations may benefit from indexes on WHERE
clause columns.

2. Joins

 Purpose: Combine rows from two or more tables based on a related column, typically used in
SELECT queries to retrieve related data.
 Types:
1. INNER JOIN: Returns rows where there is a match in both tables.
2. LEFT (OUTER) JOIN: Returns all rows from the left table, with matching rows
from the right table (or NULL if no match).
3. RIGHT (OUTER) JOIN: Returns all rows from the right table, with matching rows
from the left table (or NULL if no match).
4. FULL (OUTER) JOIN: Returns all rows from both tables, with NULL for non-
matching rows.
5. CROSS JOIN: Returns the Cartesian product of both tables (all possible
combinations).
 Syntax:

sql

SELECT columns
FROM table1
[JOIN_TYPE] JOIN table2
ON table1.column = table2.column;
 Procedure:
1. Identify the tables and the column(s) to join on (e.g., primary key and foreign key).
2. Choose the appropriate join type based on the desired result.
3. Specify conditions in the ON clause.
4. Add WHERE, GROUP BY, or other clauses as needed.
 Example (INNER JOIN):

sql

SELECT e.name, d.dept_name


FROM employees e
INNER JOIN departments d ON e.dept_id = d.id;

o Returns employee names and their department names for matching rows.
 Example (LEFT JOIN):

sql

SELECT e.name, d.dept_name


FROM employees e
LEFT JOIN departments d ON e.dept_id = d.id;

o Returns all employees, with department names or NULL if no department match.


 Example (CROSS JOIN):

sql

SELECT e.name, r.role_name


FROM employees e
CROSS JOIN roles r;

o Returns all combinations of employee names and roles (no ON clause needed).

Notes

 Performance: Joins on large tables benefit from indexes on join columns.


 DBMS Support: All major DBMS (MySQL, PostgreSQL, SQL Server, Oracle) support these
joins, though syntax may vary slightly (e.g., Oracle’s older (+) syntax for outer joins).
3. Unions, Intersection, Minus

These are set operators that combine or compare results from multiple SELECT queries.

a. UNION

 Purpose: Combines rows from two or more SELECT queries, removing duplicates.
 Syntax:

sql

SELECT column1, column2 FROM table1


UNION
SELECT column1, column2 FROM table2;

 Procedure:
1. Ensure both SELECT queries return the same number and type of columns.
2. Combine results using UNION.
3. Use UNION ALL to include duplicates (faster, as it skips duplicate removal).
 Example:

sql

SELECT name FROM employees WHERE dept_id = 10


UNION
SELECT name FROM contractors WHERE dept_id = 10;

o Returns unique names from employees and contractors in department 10.

b. INTERSECT

 Purpose: Returns rows common to both SELECT queries.


 Syntax:

sql

SELECT column1, column2 FROM table1


INTERSECT
SELECT column1, column2 FROM table2;

 Procedure:
1. Ensure column compatibility (number and type).
2. Use INTERSECT to find common rows.
 Example:

sql

SELECT id FROM orders


INTERSECT
SELECT id FROM returns;

o Returns IDs present in both orders and returns.


 Note: Not supported in MySQL; use subqueries or joins as alternatives.

c. MINUS (or EXCEPT)

 Purpose: Returns rows from the first SELECT query that are not in the second query.
 Syntax:

sql

SELECT column1, column2 FROM table1


MINUS
SELECT column1, column2 FROM table2;

 Procedure:
1. Ensure column compatibility.
2. Use MINUS (Oracle) or EXCEPT (PostgreSQL, SQL Server) to exclude rows.
 Example:

sql

SELECT id FROM employees


MINUS
SELECT id FROM archived_employees;

o Returns employee IDs not in the archived_employees table.


 Note: MySQL does not support MINUS/EXCEPT; use NOT IN or LEFT JOIN with NULL
checks.
Notes

 Column Compatibility: All set operators require the same number of columns with
compatible data types.
 Performance: UNION ALL is faster than UNION because it doesn’t remove duplicates.
 DBMS Support: INTERSECT and MINUS/EXCEPT are not universally supported (e.g.,
MySQL lacks them).

4. Cursors (PL/SQL)

 Purpose: Allow row-by-row processing of query results in PL/SQL, useful for complex logic
or iterative operations.
 Types:
o Implicit Cursor: Automatically managed by PL/SQL for DML operations.
o Explicit Cursor: User-defined for manual control over query results.
 Syntax (Explicit Cursor):

sql

DECLARE
CURSOR cursor_name IS SELECT column1, column2 FROM table_name WHERE condition;
variable1 datatype;
variable2 datatype;
BEGIN
OPEN cursor_name;
LOOP
FETCH cursor_name INTO variable1, variable2;
EXIT WHEN cursor_name%NOTFOUND;
-- Process data
END LOOP;
CLOSE cursor_name;
END;

 Procedure:

1. Declare a cursor with a SELECT query.


2. Open the cursor to execute the query.
3. Fetch rows one by one into variables.
4. Process each row (e.g., update, insert, or custom logic).
5. Close the cursor.
 Example:

sql

DECLARE
CURSOR emp_cursor IS SELECT id, salary FROM employees WHERE dept_id = 10;
v_id employees.id%TYPE;
v_salary employees.salary%TYPE;
BEGIN
OPEN emp_cursor;
LOOP
FETCH emp_cursor INTO v_id, v_salary;
EXIT WHEN emp_cursor%NOTFOUND;
UPDATE employees SET salary = v_salary * 1.1 WHERE id = v_id;
END LOOP;
CLOSE emp_cursor;
END;

o Increases salaries by 10% for employees in department 10.

Notes

 Performance: Cursors are slower than set-based operations (e.g., UPDATE with WHERE);
use only when row-by-row processing is necessary.
 Attributes: Cursor attributes like %FOUND, %NOTFOUND, %ISOPEN, and
%ROWCOUNT provide status information.

5. Triggers (PL/SQL)

 Purpose: Automatically execute a block of code in response to specific DML events


(INSERT, UPDATE, DELETE) on a table.
 Types:
o Row-Level Trigger: Executes for each affected row.
o Statement-Level Trigger: Executes once per DML statement.
o BEFORE: Runs before the event.
o AFTER: Runs after the event.
 Syntax:

sql

CREATE OR REPLACE TRIGGER trigger_name


[BEFORE | AFTER] [INSERT | UPDATE | DELETE] ON table_name
[FOR EACH ROW]
DECLARE
-- Declarations
BEGIN
-- Trigger logic
END;

 Procedure:

1. Define the trigger event (e.g., AFTER INSERT).


2. Specify the table and whether it’s row-level (FOR EACH ROW) or statement-level.
3. Write logic to handle the event (use :NEW and :OLD for row-level triggers to access
new/old values).
4. Test the trigger with DML operations.
 Example:

sql

CREATE OR REPLACE TRIGGER log_salary_update


AFTER UPDATE OF salary ON employees
FOR EACH ROW
BEGIN
INSERT INTO salary_log (emp_id, old_salary, new_salary, change_date)
VALUES (:OLD.id, :OLD.salary, :NEW.salary, SYSDATE);
END;

o Logs salary changes into a salary_log table after an UPDATE on employees.salary.

Notes

 Use Cases: Auditing, enforcing business rules, or maintaining derived data.


 Limitations: Triggers can’t directly call COMMIT or ROLLBACK and may cause
performance overhead if complex.

6. Procedures (PL/SQL)

 Purpose: Encapsulate reusable blocks of PL/SQL code to perform specific tasks, such as data
manipulation or business logic.
 Syntax:

sql

CREATE OR REPLACE PROCEDURE procedure_name (parameter1 IN datatype, parameter2 OUT


datatype, ...)
AS
BEGIN
-- Logic
EXCEPTION
-- Error handling
END;

 Procedure:
1. Define the procedure with optional input (IN), output (OUT), or input/output (IN
OUT) parameters.
2. Write the logic in the BEGIN block.
3. Include error handling in the EXCEPTION block.
4. Call the procedure using EXEC or CALL.
 Example:

sql

CREATE OR REPLACE PROCEDURE raise_salary (p_dept_id IN NUMBER, p_percentage IN


NUMBER)
AS
BEGIN
UPDATE employees
SET salary = salary * (1 + p_percentage / 100)
WHERE dept_id = p_dept_id;
COMMIT;
EXCEPTION
WHEN OTHERS THEN
ROLLBACK;
RAISE_APPLICATION_ERROR(-20001, 'Error updating salaries: ' || SQLERRM);
END;

o Increases salaries in the specified department by the given percentage.


 Calling the Procedure:

sql

EXEC raise_salary(10, 5);

o Raises salaries in department 10 by 5%.

Notes

 Advantages: Reusability, modularity, and centralized logic.


 Parameters: Use IN for input, OUT for output, or IN OUT for both.
 DBMS Support: Procedures are primarily a PL/SQL (Oracle) feature but are supported in
similar forms in SQL Server (stored procedures) and PostgreSQL (functions).

Summary Table

Feature Purpose Key Clause/Keyword Example Use Case

INSERT Add new rows INSERT INTO ... VALUES Add a new employee

UPDATE Modify existing rows UPDATE ... SET ... WHERE Increase salaries

Remove inactive
DELETE Remove rows DELETE FROM ... WHERE
employees

Combine data from INNER/LEFT/RIGHT/FULL List employees with


Joins
multiple tables JOIN department names

Combine query results, Merge employee and


UNION UNION
no duplicates contractor names
Feature Purpose Key Clause/Keyword Example Use Case

Common rows from Find IDs in both orders


INTERSECT INTERSECT
queries and returns

Rows in one query but Find non-archived


MINUS/EXCEPT MINUS/EXCEPT
not another employees

Row-by-row processing Process salaries


Cursors CURSOR ... OPEN/FETCH
(PL/SQL) individually

Auto-execute on DML
Triggers CREATE TRIGGER Log salary changes
events (PL/SQL)

Reusable logic blocks Apply salary raises by


Procedures CREATE PROCEDURE
(PL/SQL) department

 .

You might also like