SQL My Notes
SQL My Notes
-- last item
SELECT quantity_sold FROM Sales
ORDER by sale_id desc
LIMIT 1;
SELECT quantity_sold FROM Sales
ORDER by sale_id desc
LIMIT 3;
-- sort by price
SELECT sale_id,total_price FROM Sales
ORDER by total_price desc;
-- order by data
SELECT sale_id,sale_date FROM Sales
ORDER by sale_date desc;
-- in
SELECT sale_id,product_id,total_price FROM Sales
where product_id IN(101,102);
-- not between
SELECT sale_id, total_price
FROM Sales
WHERE total_price NOT BETWEEN 50 AND 500;
-- Like
SELECT sale_id,sale_date FROM Sales
WHERE sale_date Like '2024-01-%';
-- group by
SELECT avg(total_price), count(sale_id),sale_date FROM
Sales
group by sale_date;
-- HAVING clause
SELECT product_id, SUM(total_price) AS total_sales
FROM Sales
GROUP BY product_id
HAVING SUM(total_price) > 100;
Output:
+------------------+
| avg(total_price) |
+------------------+
| 726.000000 |
+------------------+
+------------+-------------+
| product_id | total_price |
+------------+-------------+
| 103 | 60.00 |
| 104 | 80.00 |
| 105 | 90.00 |
+------------+-------------+
+------------+
| product_id |
+------------+
| 104 |
| 103 |
+------------+
+---------------+
| quantity_sold |
+---------------+
| 6 |
+---------------+
+---------------+
| quantity_sold |
+---------------+
| 6 |
| 4 |
| 2 |
+---------------+
+---------+-------------+
| sale_id | total_price |
+---------+-------------+
| 1 | 2500.00 |
| 2 | 900.00 |
| 5 | 90.00 |
| 4 | 80.00 |
| 3 | 60.00 |
+---------+-------------+
+---------+------------+
| sale_id | sale_date |
+---------+------------+
| 4 | 2024-01-03 |
| 5 | 2024-01-03 |
| 2 | 2024-01-02 |
| 3 | 2024-01-02 |
| 1 | 2024-01-01 |
+---------+------------+
+---------+---------------+
| sale_id | quantity_sold |
+---------+---------------+
| 1 | 5 |
| 5 | 6 |
+---------+---------------+
+---------+------------+
| sale_id | sale_date |
+---------+------------+
| 1 | 2024-01-01 |
| 4 | 2024-01-03 |
| 5 | 2024-01-03 |
+---------+------------+
+---------+------------+---------------+------------+-------------+
| sale_id | product_id | quantity_sold | sale_date | total_price |
+---------+------------+---------------+------------+-------------+
| 1 | 101 | 5 | 2024-01-01 | 2500.00 |
| 2 | 102 | 3 | 2024-01-02 | 900.00 |
| 3 | 103 | 2 | 2024-01-02 | 60.00 |
| 4 | 104 | 4 | 2024-01-03 | 80.00 |
| 5 | 105 | 6 | 2024-01-03 | 90.00 |
+---------+------------+---------------+------------+-------------+
+---------+------------+-------------+
| sale_id | product_id | total_price |
+---------+------------+-------------+
| 1 | 101 | 2500.00 |
| 2 | 102 | 900.00 |
+---------+------------+-------------+
+---------+---------------+
| sale_id | quantity_sold |
+---------+---------------+
| 1 | 5 |
| 3 | 2 |
+---------+---------------+
+---------+---------------+
| sale_id | quantity_sold |
+---------+---------------+
| 2 | 3 |
| 4 | 4 |
| 5 | 6 |
+---------+---------------+
+---------+-------------+
| sale_id | total_price |
+---------+-------------+
| 3 | 60.00 |
| 4 | 80.00 |
| 5 | 90.00 |
+---------+-------------+
+---------+-------------+
| sale_id | total_price |
+---------+-------------+
| 1 | 2500.00 |
| 2 | 900.00 |
+---------+-------------+
+---------+------------+
| sale_id | sale_date |
+---------+------------+
| 1 | 2024-01-01 |
| 2 | 2024-01-02 |
| 3 | 2024-01-02 |
| 4 | 2024-01-03 |
| 5 | 2024-01-03 |
+---------+------------+
+---------+------------+
| sale_id | sale_date |
+---------+------------+
| 1 | 2024-01-01 |
| 2 | 2024-01-02 |
| 3 | 2024-01-02 |
| 4 | 2024-01-03 |
| 5 | 2024-01-03 |
+---------+------------+
+---------+------------+
| sale_id | sale_date |
+---------+------------+
| 4 | 2024-01-03 |
| 5 | 2024-01-03 |
+---------+------------+
+------------+---------------+------------+-------------+
| product_id | quantity_sold | sale_date | total_price |
+------------+---------------+------------+-------------+
| 101 | 5 | 2024-01-01 | 2500.00 |
| 102 | 3 | 2024-01-02 | 900.00 |
| 104 | 4 | 2024-01-03 | 80.00 |
| 105 | 6 | 2024-01-03 | 90.00 |
+------------+---------------+------------+-------------+
+------------+---------------+------------+-------------+
| product_id | quantity_sold | sale_date | total_price |
+------------+---------------+------------+-------------+
| 101 | 5 | 2024-01-01 | 2500.00 |
+------------+---------------+------------+-------------+
+------------------+----------------+------------+
| avg(total_price) | count(sale_id) | sale_date |
+------------------+----------------+------------+
| 2500.000000 | 1 | 2024-01-01 |
| 480.000000 | 2 | 2024-01-02 |
| 85.000000 | 2 | 2024-01-03 |
+------------------+----------------+------------+
+------------+-------------+
| product_id | total_sales |
+------------+-------------+
| 101 | 2500.00 |
| 102 | 900.00 |
+------------+-------------+
+------------+----------------------------------+
| sale_date | sum_of_total_sales_group_by_data |
+------------+----------------------------------+
| 2024-01-01 | 2500.00 |
| 2024-01-02 | 960.00 |
| 2024-01-03 | 170.00 |
+------------+----------------------------------+
DCL Commands
Data Control Language (DCL) commands in SQL are used to control access to data
within the database. These commands help in enforcing security by defining access
rights and permissions. The main DCL commands are GRANT and REVOKE.
DCL Commands
GRANT Command
Syntax
Example
Granting SELECT and INSERT privileges on the Sales table to user username:
Granting all privileges on the Sales table to user username with the ability to grant
the same privileges to other users:
REVOKE Command
Syntax
REVOKE privilege [, privilege]...
ON object
FROM user [, user]...;
Revoking SELECT and INSERT privileges on the Sales table from user username:
Example Usage
Assume you have a Sales table and a user john_doe. You can grant and revoke
privileges as follows:
GRANT SELECT
ON Sales
TO john_doe;
GRANT INSERT
ON Sales
TO john_doe;
REVOKE SELECT
ON Sales
FROM john_doe;
Summary
Indexing
Indexing is a powerful technique in SQL databases used to improve the speed of
data retrieval operations. An index is a separate data structure that allows the
database to find records more quickly than it could by scanning an entire table.
Here’s a detailed look at indexing in SQL:
Types of Indexes
Creating Indexes
Indexes are created using the CREATE INDEX statement. Here’s the syntax for
creating different types of indexes:
Basic Syntax
CREATE INDEX index_name
ON table_name (column1, column2, ...);
Examples
Managing Indexes
1. Dropping an Index:
Example:
2. Viewing Indexes:
● MySQL:
Index Maintenance
Pros
Cons
1. Primary Keys and Unique Constraints: Always index primary keys and
columns with unique constraints.
2. Foreign Keys: Index foreign keys to speed up JOIN operations.
3. Frequently Queried Columns: Index columns that are frequently used in
WHERE clauses, ORDER BY, and GROUP BY operations.
4. Large Tables: Indexing is especially beneficial for large tables where full table
scans would be inefficient.
Suppose you have a Sales table and you frequently run queries filtering by
product_id and sorting by sale_date. You can create a composite index to
optimize these queries:
CREATE INDEX idx_sales_product_date
ON Sales (product_id, sale_date);
Conclusion
Short Code
Table and Index Creation
CREATE TABLE Sales (
sale_id INT PRIMARY KEY AUTO_INCREMENT,
product_id INT,
quantity_sold INT,
sale_date DATE,
total_price DECIMAL(10, 2)
);
By understanding when and why to rebuild indexes, you can maintain optimal
performance for your SQL databases. Regular maintenance ensures that your
indexes remain efficient and queries execute quickly.
Transaction
Understanding transactions in advance is crucial for managing data integrity and consistency
in a database system. Here’s a comprehensive guide to transactions, including their
properties, commands, and practical considerations:
Transactions Overview
A transaction is a sequence of one or more SQL operations that are executed as a single
unit of work. Transactions are used to ensure data integrity and consistency, particularly in
multi-user environments where multiple operations might be occurring simultaneously.
ACID Properties
1. Atomicity:
○ Definition: Ensures that all operations within a transaction are completed
successfully. If any operation fails, the entire transaction is rolled back, and
the database remains unchanged.
○ Example: In a bank transfer, both the debit from one account and the credit to
another must either both succeed or both fail.
2. Consistency:
○ Definition: Ensures that a transaction brings the database from one valid
state to another, maintaining all predefined rules and constraints.
○ Example: If a transaction violates a constraint (like exceeding a credit limit),
the transaction is rolled back.
3. Isolation:
○ Definition: Ensures that transactions are executed in isolation from one
another. Intermediate states of a transaction are not visible to other
transactions.
○ Example: Two transactions occurring simultaneously should not interfere with
each other’s operations.
4. Durability:
○ Definition: Ensures that once a transaction is committed, its changes are
permanent, even in the event of a system failure.
○ Example: After a bank transfer is committed, the changes to account
balances remain even if the system crashes immediately afterward.
Syntax:
START TRANSACTION;
-- or
BEGIN;
○
2. COMMIT:
○ Purpose: Saves all changes made during the transaction to the database and
ends the transaction.
Syntax:
sql
Copy code
COMMIT;
○
3. ROLLBACK:
○ Purpose: Reverts all changes made during the transaction and ends the
transaction.
Syntax:
sql
Copy code
ROLLBACK;
○
Transaction Isolation Levels
Different isolation levels control the visibility of data changes made by one transaction to
other concurrent transactions. They balance between performance and data consistency:
1. READ UNCOMMITTED:
○ Allows: Reading uncommitted changes made by other transactions.
○ Prevents: Nothing; prone to dirty reads.
○ Use Case: Rarely used, except in specific cases where performance is critical
and dirty reads are acceptable.
2. READ COMMITTED:
○ Allows: Reading only committed changes made by other transactions.
○ Prevents: Dirty reads.
○ Use Case: Commonly used in many applications to balance performance and
consistency.
3. REPEATABLE READ:
○ Allows: Reading the same set of rows multiple times and seeing the same
data each time.
○ Prevents: Dirty reads, non-repeatable reads.
○ Use Case: Ensures repeatable reads in transactions, useful in banking
systems.
4. SERIALIZABLE:
○ Allows: Each transaction to execute in a fully isolated manner.
○ Prevents: Dirty reads, non-repeatable reads, phantom reads.
○ Use Case: Highest level of isolation, used when absolute consistency is
required.
Practical Example
Syntax:
SAVEPOINT savepoint_name;
-- Rollback to the savepoint
ROLLBACK TO SAVEPOINT savepoint_name;
○
3. Error Handling: Proper error handling ensures that transactions are rolled back in
case of errors. Use try-catch constructs or error-handling mechanisms provided by
your database system.
4. Performance: High isolation levels (like SERIALIZABLE) can impact performance
due to locking mechanisms. Choose the appropriate isolation level based on the
application's consistency requirements and performance needs.
Summary
By understanding and correctly implementing transactions, you can ensure your database
operations are reliable, consistent, and maintain data integrity.
Normalization
Normalization is the process of organizing the fields and tables of a relational
database to minimize redundancy and dependency. It involves decomposing a large
table into smaller tables and defining relationships among them to increase the
clarity and efficiency of the data. The goal of normalization is to eliminate redundant
data and ensure data dependencies make sense, thereby improving data integrity.
Normal Forms
Example:
javascript
Copy code
StudentID | Name | Courses
----------|---------|---------------
1 | Alice | Math, Physics
2 | Bob | Math, Chemistry
Normalized to 1NF:
● It is in 1NF.
● All non-key attributes are fully functionally dependent on the entire primary
key (i.e., there are no partial dependencies).
Example:
mathematica
Copy code
OrderID | ProductID | ProductName | Quantity
--------|-----------|-------------|---------
1 | 101 | Apple | 5
1 | 102 | Banana | 3
2 | 101 | Apple | 2
2 | 103 | Orange | 4
Normalized to 2NF:
mathematica
Copy code
Order(OrderID, ProductID, Quantity)
Product(ProductID, ProductName)
Order:
OrderID | ProductID | Quantity
--------|-----------|---------
1 | 101 | 5
1 | 102 | 3
2 | 101 | 2
2 | 103 | 4
Product:
ProductID | ProductName
----------|-------------
101 | Apple
102 | Banana
103 | Orange
● It is in 2NF.
● All non-key attributes are non-transitively dependent on the primary key (i.e.,
no transitive dependencies).
Example:
javascript
Copy code
StudentID | Name | DeptID | DeptName | DeptHead
----------|---------|--------|----------|---------
1 | Alice | 10 | Math | Dr. Smith
2 | Bob | 20 | Physics | Dr. Johnson
3 | Charlie | 10 | Math | Dr. Smith
Normalized to 3NF:
scss
Copy code
Student(StudentID, Name, DeptID)
Department(DeptID, DeptName, DeptHead)
Student:
StudentID | Name | DeptID
----------|---------|--------
1 | Alice | 10
2 | Bob | 20
3 | Charlie | 10
Department:
DeptID | DeptName | DeptHead
-------|----------|-----------
10 | Math | Dr. Smith
20 | Physics | Dr. Johnson
● It is in 3NF.
● Every determinant is a candidate key.
Example:
diff
Copy code
TeacherID | TeacherName | CourseID | CourseName
----------|-------------|----------|-----------
1 | Mr. Smith | 101 | Math
2 | Ms. Johnson | 102 | Physics
1 | Mr. Smith | 103 | Chemistry
Normalized to BCNF:
Teacher(TeacherID, TeacherName)
Course(CourseID, CourseName)
TeacherCourse(TeacherID, CourseID)
Teacher:
TeacherID | TeacherName
----------|-------------
1 | Mr. Smith
2 | Ms. Johnson
Course:
CourseID | CourseName
---------|------------
101 | Math
102 | Physics
103 | Chemistry
TeacherCourse:
TeacherID | CourseID
----------|----------
1 | 101
2 | 102
1 | 103
● It is in BCNF.
● It has no multi-valued dependencies.
Example:
javascript
Copy code
StudentID | Course | Hobby
----------|----------|--------
1 | Math | Reading
1 | Math | Swimming
2 | Physics | Reading
2 | Chemistry| Swimming
Normalized to 4NF:
scss
Copy code
StudentCourse(StudentID, Course)
StudentHobby(StudentID, Hobby)
StudentCourse:
StudentID | Course
----------|-------
1 | Math
2 | Physics
2 | Chemistry
StudentHobby:
StudentID | Hobby
----------|-------
1 | Reading
1 | Swimming
2 | Reading
2 | Swimming
● It is in 4NF.
● It has no join dependencies.
Example:
css
Copy code
Project | Task | Resource
----------|------------|---------
A | Design | Alice
A | Design | Bob
A | Testing | Alice
B | Design | Charlie
B | Testing | Bob
Normalized to 5NF:
less
Copy code
ProjectTask(Project, Task)
TaskResource(Task, Resource)
ProjectResource(Project, Resource)
ProjectTask:
Project | Task
----------|-----
A | Design
A | Testing
B | Design
B | Testing
TaskResource:
Task | Resource
----------|---------
Design | Alice
Design | Bob
Testing | Alice
Testing | Bob
ProjectResource:
Project | Resource
----------|---------
A | Alice
A | Bob
B | Charlie
B | Bob
Benefits of Normalization
Drawbacks of Normalization