You signed in with another tab or window.Reload to refresh your session.You signed out in another tab or window.Reload to refresh your session.You switched accounts on another tab or window.Reload to refresh your session.Dismiss alert
This repository contains a collection of SQL files that I have created while learning the basics of SQL. The files in this repository are intended to help me practice and reinforce my understanding of SQL concepts, and may be useful to others who are also learning SQL. 👇
Learning Resources
In addition to the code in this repository, I have found the following resources to be helpful in learning SQL:
If you have any suggestions for additional files or resources that would be helpful for learning SQL, please feel free to open an issue or submit a pull request.
License
The code in this repository is licensed under the MIT License.
Views in SQL
View
A view is a named query stored in the database. It's like a virtual table that doesn't store any data. A view can be reused whenever needed by calling the view name, allowing reusability of frequently used queries.
A view is a virtual table based on the result of a SQL query, presenting data in a more organized and simplified way without storing the data in a physical table.
Example
CREATEVIEWNewTableASSELECT sname, grade, percentageFROM resultWHERE percentage>65ORDER BY sname;SELECT*FROM NewTable;DROPVIEW NewTable;CREATE OR REPLACEVIEWNewTableASSELECT rollno, sname, grade, percentageFROM resultWHERE percentage>50ORDER BY sname;SELECT*FROM result;
Union in SQL
Union
The UNION operator is used to combine the result sets of two or more SELECT statements into a single result set.
Rules
Every SELECT statement within UNION must have the same number of columns.
The columns must also have similar data types.
The columns in every SELECT statement must also be in the same order.
Example
SELECT cityFROM employeeUNION ALLSELECT cityFROM customerORDER BY city;
Group by in SQL
Group By
The GROUP BY clause is used to group rows of a query result set by one or more columns. It's a way to categorize data into groups based on common values in one or more columns.
Example
SELECTMAX(salary)FROM employeeGROUP BY jobORDER BYCOUNT(cno);
Having in SQL
Having
The HAVING clause is used to filter groups of rows based on conditions specified in the GROUP BY clause. It's similar to the WHERE clause, but it's used to filter groups instead of individual rows.
Example
SELECTCOUNT(rollno), gradeFROM resultWHERE percentage>65GROUP BY gradeHAVING COUNT>=3;
Index in SQL
Indexes in MySQL
Indexes are used to find rows with specific column values quickly, improving the speed of data retrieval operations on a database table. It is similar to GROUP BY. Indexes are used to retrieve data from the database more quickly.
Automatic Indexing
Indexing is automatically assigned/created when the following keywords are used:
Primary Key
Foreign Key
Unique
Manual Indexing
We can also create indexing manually using the following syntax:
Regular Index
CREATEINDEXindex_nameON table_name(column_name);
Other Types of Indexes
Full Text Index
Descending Index
Spatial Index
Points to Remember
Index limitations: Index cannot be applied to all columns.
Index data structures: When an index is created, it will create a separate database and data structures to perform faster data retrieval operations.
Performance impact: Insert and update operations become slow when indexing is used. Only data retrieval is faster.
Large database benefits: Indexing is useful with large databases.
1.What is an Index?
An index is a data structure that improves the speed of data retrieval operations on a database table. It is analogous to an index in a book.
2.Types of Indexes in MySQL
Primary Key Index: Automatically created when a primary key is defined. Ensures uniqueness and fast access by the primary key.
Unique Index: Ensures all values in the indexed column are unique.
Regular Index (Non-Unique Index): Speeds up queries on columns that are not unique.
Full-Text Index: Used for full-text searches.
Spatial Index: Used for spatial data types.
3.Creating an Index
You can create an index using theCREATE INDEX statement:
Useful when multiple columns are often queried together.
6.Advantages of Indexes
Speed Up Query Performance: Especially for large tables.
Enforce Uniqueness: Through unique indexes.
Efficient Sorting: As indexes can be used to retrieve sorted data quickly.
7.Disadvantages of Indexes
Disk Space: Indexes require additional storage.
Slower Writes: Inserts, updates, and deletes can be slower because the index must be updated.
8.Viewing Indexes
You can view the indexes on a table with:
SHOW INDEXFROM table_name;
9.Dropping an Index
Indexes can be removed if they are no longer needed:
DROPINDEX index_nameON table_name;
10.Index Selectivity
Selectivity is the measure of how well an index can distinguish between rows. High selectivity means fewer rows are matched by the indexed value, which usually leads to better performance.
11.Index Coverage
An index is "covering" if the query can be satisfied just using the index without accessing the table data. This can happen if theSELECT clause only includes columns that are part of the index.
12.Index Maintenance
Regularly update statistics and consider rebuilding indexes to maintain performance. Use:
ANALYZE TABLE table_name;
for updating statistics.
13.B-Tree Indexes
The most common type of index in MySQL. Good for equality and range queries.
14.Full-Text Indexes
Used for searching text within large datasets. Created with:
CREATE FULLTEXT INDEX index_nameON table_name(column);
15.Spatial Indexes
Used with geographic data types. Created with:
CREATE SPATIAL INDEX index_nameON table_name(column);
16.Performance Monitoring
UseEXPLAIN to understand how MySQL executes a query and whether indexes are being used:
In MySQL, the primary key index is a clustered index, meaning the table data is stored in the order of the primary key. Non-clustered indexes store a separate structure.
18.Temporary Tables and Indexes
Indexes can be used on temporary tables for complex queries:
Force the use of a specific index using index hints:
SELECT*FROM table_name USE INDEX (index_name)WHERE column='value';
20.Best Practices
Index columns used frequently inWHERE,ORDER BY,JOIN, andGROUP BY clauses.
Avoid indexing columns with a low level of selectivity (e.g., boolean columns).
Monitor and adjust indexes as the database evolves and query patterns change.
Joins in SQL
What Are Joins?
In SQL, ajoin is a way to fetch data from two or more tables based on a related column between them. Think of tables as different departments in a company, each with its own set of records. A join helps you pull together relevant information from these departments to form a complete picture.
Types of Joins
INNER JOIN: Combines rows from both tables where there is a match in both tables.
LEFT JOIN (or LEFT OUTER JOIN): Combines all rows from the left table and the matched rows from the right table. If there is no match, the result is NULL on the right side.
RIGHT JOIN (or RIGHT OUTER JOIN): Combines all rows from the right table and the matched rows from the left table. If there is no match, the result is NULL on the left side.
FULL JOIN (or FULL OUTER JOIN): Combines rows when there is a match in one of the tables. It returns NULL for unmatched rows in both tables.
CROSS JOIN: Returns the Cartesian product of the two tables, meaning every row in the first table is combined with every row in the second table.
SELF JOIN: A table is joined with itself.
Let's break down the most essential joins:
1. INNER JOIN
Analogy: Imagine you have two lists of friends from different schools. You want to find friends who are in both lists. An INNER JOIN is like making a new list that includes only those who appear in both original lists.
Analogy: Suppose you have a list of all students and another list of students who have paid their fees. A LEFT JOIN helps you get a list of all students along with their fee status, showing NULL for those who haven’t paid.
Analogy: Similar to LEFT JOIN but reversed. Imagine the fee payment list is complete but some students may not exist in the main student list. A RIGHT JOIN ensures all fee records are shown, even if some students are missing from the main list.
Analogy: This join is like merging two lists where you want to see all entries, including those that don’t match in both lists. Imagine merging two contact lists where some contacts might be unique to each list.
Analogy: Imagine a list of employees where each employee has a manager who is also an employee in the same list. A SELF JOIN helps you relate employees to their managers.
Syntax:
SELECTA.columns,B.columnsFROM table A, table BWHERE condition;
Example:
SELECTA.employee_nameAS Employee,B.employee_nameAS ManagerFROM employees A, employees BWHEREA.manager_id=B.employee_id;
Summary of Key Concepts
INNER JOIN: Fetches matching rows from both tables.
LEFT JOIN: Fetches all rows from the left table and matching rows from the right table.
RIGHT JOIN: Fetches all rows from the right table and matching rows from the left table.
FULL JOIN: Fetches all rows when there is a match in one of the tables.
CROSS JOIN: Fetches the Cartesian product of both tables.
SELF JOIN: A table is joined with itself to create a relation within the same table.
Gauging Your Understanding
To ensure you grasp the prerequisites, please rate your familiarity with the following:
Basic SQL queries (SELECT, FROM, WHERE)
Primary keys and foreign keys in database tables
The concept of relational databases
Basic understanding of NULL values in SQL
SubQuery in SQL
What is a Subquery?
A subquery is a query nested inside another query. It can be placed in various clauses such as SELECT, FROM, WHERE, and HAVING. Think of it as solving a smaller puzzle (the subquery) to find a piece that fits into the larger puzzle (the main query).
Types of Subqueries
Single-Row Subqueries: Returns one row.
Multi-Row Subqueries: Returns multiple rows.
Scalar Subqueries: Returns a single value.
Correlated Subqueries: Subqueries that reference columns from the outer query.
Nested Subqueries: Subqueries within subqueries.
Key Concepts and Examples
1. Single-Row Subqueries
Analogy: Imagine asking for the age of the oldest student in a class. The answer is a single value that can be used to find other students of the same age.
This query finds the name of the employee with the highest salary.
2. Multi-Row Subqueries
Analogy: Suppose you want to know which products belong to the categories that have been recently updated. Here, multiple category IDs can be returned.
This query compares each employee's salary to the average salary.
4. Correlated Subqueries
Analogy: This is like checking each student's score against the class average while calculating the class average excluding the student being checked. It's a subquery that depends on the outer query.