Skip to content

Latest commit

 

History

History
1119 lines (783 loc) · 44.7 KB

README.md

File metadata and controls

1119 lines (783 loc) · 44.7 KB

SQL

Table of Contents




Data Query Language

  • It is used to extract the data from the relations. e.g.; SELECT
  • A generic query to retrieve from a relational database is:
  • Part of the query represented by statement 1 is compulsory
SELECT [DISTINCT] Attribute_List FROM R1,R2….RM
[WHERE condition]
[GROUP BY (Attributes)[HAVING condition]]
[ORDER BY(Attributes)[DESC]];

SQL Queries

COUNT Queries

Count no of employees working in dept 'IT'

SELECT Conut(*) FROM Employees WHERE dept_name='IT';

FIND Queries

Find details of employees whose salary is in between 10000 50000

SELECT * FROM Employees WHERE salary BETWEEN 10000 AND 50000;

LIKE Queries (REGEX)

Find Names of employees starting with a

SELECT first_name FROM Employees WHERE first_name LIKE 'A%';
/* Here % means null or any number of characters */

Find details of employees whose first_name end in 'A' and has 6 letters

SELECT first_name FROM Employees WHERE first_name LIKE '_____A';
/* Here _ means exactly one characters */

UPDATE Queries

Increase income of all employees by 5%

UPDATE Employees SET income = income + (income * 5/100);

Query an alphabetically ordered list of all names in OCCUPATIONS, immediately followed by the first letter of each profession as a parenthetical (i.e.: enclosed in parentheses) For example: AnActorName(A), ADoctorName(D), AProfessorName(P), and ASingerName(S). Eg Ariel(A) Samantha(D)

select CONCAT(Name,"(",LEFT(Occupation,1),")") from Occupations order by name;

Query the number of ocurrences of each occupation in OCCUPATIONS. Sort the occurrences in ascending order, and output them in the following format: There are total 2 doctors

select CONCAT("There are total ", Count(Occupation), " ", LOWER(occupation), "s.") from Occupations Group by Occupation order by  Count(Occupation)

UPDATE multiple rows with different values in one query

UPDATE table SET Col1 = CASE id 
                WHEN 1 THEN 1 
                WHEN 2 THEN 2 
                WHEN 4 THEN 10 
                ELSE Col1 
              END, 
        Col2 = CASE id 
                WHEN 3 THEN 3 
                WHEN 4 THEN 12 
                ELSE Col2 
              END
    WHERE id IN (1, 2, 3, 4);

Examples on a Table

show tables;
SELECT * FROM Sales GROUP BY SalesPerson;
SELECT AVG(no_page) FROM book_mast;
SELECT MAX(Yearly_Income) AS `Maximum Income`
FROM customerdetails;
select name from employee where salary>2000 and months<10 order by employee_id;

Above SQL Query will group the Customers by their Education, and finds the highest Income in each group

SELECT  Education, MAX(Yearly_Income) FROM customerdetails GROUP BY Education;

Store MySQL query results in another Table

CREATE TABLE a SELECT SalesPerson,AVG(TotalSale) as b FROM Sales GROUP BY SalesPerson;
select * from a
select MAX(b) from a;

Leetcode Problems

Second highest salary from the Employee table

Create table If Not Exists Employee (Id int, Salary int)
Truncate table Employee
insert into Employee (Id, Salary) values ('1', '100')
insert into Employee (Id, Salary) values ('2', '200')
insert into Employee (Id, Salary) values ('3', '300')

Employee table:
+----+--------+
| id | salary |
+----+--------+
| 1  | 100    |
| 2  | 200    |
| 3  | 300    |
+----+--------+

Given the above Employee table, the query should return 200 as the second highest salary. If there is no second highest salary, then the query should return null.

+---------------------+   
| SecondHighestSalary |   
+---------------------+   
| 200                 |   
+---------------------+   
/* To get the Higest Salary */
SELECT MAX(Salary) AS HighestSalary FROM Employee;
/* Sort salary in descend order and then utilize the OFFSET clause to get second highest and LIMIT clause to get one result */
SELECT Salary AS SecondHighestSalary FROM Employee ORDER BY Salary DESC LIMIT 1 OFFSET 1
/* To Handle one or no records use IFNULL, To Handle Duplicates use  DISTINCT*/
SELECT IFNULL((SELECT DISTINCT Salary FROM Employee ORDER BY Salary DESC LIMIT 1 OFFSET 1), NULL) AS SecondHighestSalary;

Employees Earning More Than Their Managers

Employee table:
+----+-------+--------+-----------+
| Id | Name  | Salary | ManagerId |
+----+-------+--------+-----------+
| 1  | Joe   | 70000  | 3         |
| 2  | Henry | 80000  | 4         |
| 3  | Sam   | 60000  | NULL      |
| 4  | Max   | 90000  | NULL      |
+----+-------+--------+-----------+

Write a solution to find the employees who earn more than their managers. Return the result table in any order.

Output: 
+----------+
| Employee |
+----------+
| Joe      |
+----------+
SELECT a.Name AS 'Employee'
FROM Employee AS a,Employee AS b
WHERE a.ManagerId = b.Id AND a.Salary > b.Salary;
/* Using JOIN */
SELECT a.Name AS 'Employee' FROM Employee AS a
JOIN Employee as b
ON a.ManagerId = b.id
WHERE a.Salary > b.Salary;

Customers Who Never Order

/* Customers */
+----+-------+
| Id | Name  |
+----+-------+
| 1  | Joe   |
| 2  | Henry |
| 3  | Sam   |
| 4  | Max   |
+----+-------+

/* Orders */
+----+------------+
| Id | CustomerId |
+----+------------+
| 1  | 3          |
| 2  | 1          |
+----+------------+

Write a solution to find all customers who never order anything. Return the result table in any order.

Output: 
+-----------+
| Customers |
+-----------+
| Henry     |
| Max       |
+-----------+
SELECT * FROM Customers WHERE Id NOT IN (SELECT CustomerId FROM Orders); 

SELECT Name As 'Customers' FROM Customers WHERE Id NOT IN (SELECT CustomerId FROM Orders);


Concepts

Indexes

https://user3141592.medium.com/single-vs-composite-indexes-in-relational-databases-58d0eb045cbe

An index, or more specifically, an index on a column is an additional data structure of the table’s records sorted (typically via b-tree) only on that column. Each record in the index also includes a pointer to the original record in the table, such that finding records in the index is equivalent to finding records in the original table.

For example, suppose we had the following users table.

ID | first_name | last_name    | Class      | Position |  ssn | 
---------------------------------------------------------------
 1 | Teemo      | Shroomer     | Specialist | Top      | 2345 |
 2 | Cecil      | Heimerdinger | Specialist | Mid      | 5461 |
 3 | Annie      | Hastur       | Mage       | Mid      | 8784 |

If we create an index on users.first_name, CREATE INDEX first_name_index ON users (first_name) USING BTREE;

it would create a sorting of the users by their first_name with a pointer to their primary key, something like this: Annie -> 3 Cecil -> 2 Teemo -> 1

Then a query like

SELECT * FROM users WHERE first_name = 'Teemo';

would take only O(log_2(n)) // reads since the database can perform a binary search on this index, since it is sorted by first_name

O(n) to O(log base 2 (n))

Disadvantages of index

  1. Additional storage space to store indexes
  2. Indexes also need to be updated when state-changing queries like CREATE UPDATE and DELETE are made As such, adding unnecessary indexes can actually degrade performance overall

Composite Indexes

In SQL databases, a composite index, also known as a compound index or multi-column index, is an index that involves more than one column in the index key. Unlike a single-column index that indexes only one column of a table, a composite index includes multiple columns.
This type of index is beneficial when queries involve conditions or sorting based on multiple columns.

Interview question:
If i have an composite index on A-B-C-D, while fetching A-B will the composite index work, what about B-C-D?
When you have a composite index on multiple columns (A-B-C-D), the effectiveness of the index in supporting queries depends on how the columns are used in the query conditions.

  • Queries that involve the leftmost columns of the composite index can efficiently use the index.
    This includes queries on A, A-B, A-B-C, or A-B-C-D.

  • Equality and range queries on the indexed columns can effectively use the composite index.
    A query with conditions like A = value or A = value AND B > value2 can utilize the composite index.

  • Queries involving sorting or grouping on the leftmost columns of the index can benefit from the index.
    A query with ORDER BY A or GROUP BY A may leverage the composite index.

However, queries that involve columns beyond the leftmost part of the index may not fully benefit from the composite index

  • If you have a query condition on B-C-D but not on A, the composite index (A-B-C-D) may not be as effective for that specific query. However, it could still be beneficial if the query involves a range condition or sorting on B.
    The decision on whether to use the composite index or perform a full table scan depends on the database's query optimizer. Modern database engines use sophisticated optimization strategies to determine the most efficient execution plan for a given query.


Soft delete vs Hard delete

Soft deletes: marking data as deleted
Hard deletes: performing a DELETE on a table

Soft delete - implemented by adding a Boolean column 'deleted' in the DB and a timestamp of when it was “deleted”

RAW Datatype:

  • RAW datatype can store unstructured data in a column.
  • Stores variable-length binary data that can be queried and inserted but not manipulated. Maximum length is 32767 bytes.

INSTR Function:

  • Searches the string for a substring and returns the numeric value of the specified character's first occurrence.

HAVING Clause:

  • Similar to WHERE clause but is used for groups rather than rows.

Control Flow in SQL (CASE Statement)

  • A control flow function that allows writing if-else or if-then-else logic in a SQL query. Validates various conditions and shows the output when the first condition is true, stopping the traversal. If no condition is true, it executes the else block, showing a null value if the else block is not found.

Routines and Triggers:

  • Routines: Group of multiple commands that can be called whenever required (also known as subroutines).
  • Triggers: Special type of stored procedure containing SQL statements fired automatically whenever any database event occurs, residing in the system catalog.

SQL Joins

  • JOIN is same as INNER JOIN
  • We can also use LEFT OUTER JOIN instead of LEFT JOIN, both are same.
  • RIGHT JOIN is also known as RIGHT OUTER JOIN

Cross Join

  • CROSS JOIN is used to generate a paired combination of each row of the first table with each row of the second table. This join type is also known as cartesian join
  • The Cartesian Product is a multiplication operation in the set theory that generates all ordered pairs of the given sets. Suppose that, A is a set and elements are {a,b} and B is a set and elements are {1,2,3}. The Cartesian Product of these two A and B is denoted AxB and the result will be like the following.
  • Unlike the INNER JOIN, LEFT JOIN and FULL OUTER JOIN, the CROSS JOIN does not require a joining condition.
  • The SQL queries which contain the CROSS JOIN keyword can be very costly. We try to say that these queries have a high potential to consume more resources and can cause performance issues.
  • CROSS JOIN are implemented with Nested Loops,
  • When WHERE condition is used, this type of JOIN behaves as an INNER JOIN, and when the WHERE condition is not present, it behaves like a CARTESIAN product
  • syntax
SELECT ColumnName_1, 
       ColumnName_2, 
       ColumnName_N
FROM [Table_1]
     CROSS JOIN [Table_2]

SELECT ColumnName_1, 
       ColumnName_2, 
       ColumnName_N
FROM [Table_1],[Table_2]
  • What is a Natural Join and in which situations is a natural join used
-- create a table
CREATE TABLE orders (
  id INTEGER PRIMARY KEY,
  name TEXT,
  customer_id INTEGER
);
CREATE TABLE customers (
  customer_id INTEGER PRIMARY KEY,
  name TEXT
);

-- insert some values
INSERT INTO orders VALUES (1, 'one', 5);
INSERT INTO orders VALUES (2, 'two', 10);
INSERT INTO orders VALUES (3, 'three', 15);
INSERT INTO orders VALUES (4, 'four', 50);
INSERT INTO orders VALUES (5, 'five', 60);
INSERT INTO orders VALUES (6, 'six', 100);
INSERT INTO customers VALUES (5, 'mayur');
INSERT INTO customers VALUES (10, 'pooja');
INSERT INTO customers VALUES (15, 'bhai');
INSERT INTO customers VALUES (20, 'jay');
INSERT INTO customers VALUES (25, 'sumeet');

-- fetch some values
SELECT * FROM orders left join customers on orders.customer_id = customers.customer_id;
SELECT * FROM orders right join customers on orders.customer_id = customers.customer_id;
SELECT * FROM orders inner join customers on orders.customer_id = customers.customer_id;
SELECT * FROM orders full outer join customers on orders.customer_id = customers.customer_id;
SELECT * FROM orders left join customers on orders.customer_id = customers.customer_id where customers.customer_id is null;
SELECT * FROM orders right join customers on orders.customer_id = customers.customer_id where orders.customer_id is null;
SELECT * FROM orders full outer join customers on orders.customer_id = customers.customer_id where customers.customer_id is null or orders.customer_id is null;



SQL vs NoSQL Implementation differences

GroupBy

  • In short - groupBy in mongo returns array of objects, group by in SQL returns first matching row
  • In MongoDB, when you group by a field (e.g., customerId), you usually use the $group aggregation stage.
    This allows you to define how to aggregate the grouped data. For instance, you can collect all loans for a customer into an array or apply other aggregation functions
  • This query returns all loans associated with each customerId, aggregated into an array
db.loans.aggregate([
  {
    $group: {
      _id: "$customerId",
      loans: { $push: "$loanDetails" } // Collect all loans in an array
    }
  }
]);
  • In SQL, GROUP BY is often used in conjunction with aggregate functions like SUM, COUNT, MAX, or MIN. However, if you don't use these explicitly and instead select columns not included in the GROUP BY, SQL usually picks the first row encountered for non-aggregated columns, which depends on the query's execution plan and is not guaranteed to be consistent unless explicitly defined.
  • This would not work in strict SQL modes since loanDetails isn't part of the GROUP BY. If it does work, the database typically picks the loanDetails from the first row encountered for each customerId.
SELECT customerId, loanDetails
FROM loans
GROUP BY customerId;
  • To mimic MongoDB's behavior in SQL (e.g., getting all loans per customer), you'd use GROUP_CONCAT (MySQL) or a similar function This aggregates all loans for a customerId into a single string, separated by commas (or another delimiter).
SELECT customerId, GROUP_CONCAT(loanDetails) AS loans
FROM loans
GROUP BY customerId;



SQL Language Components

TCL (Transaction Control Language)

Transaction Control Language commands manages transactions within a database.
It includes commands such as COMMIT, ROLLBACK, and SAVEPOINT to control the outcome of transactions by either making changes permanent (COMMIT), undoing changes (ROLLBACK), or establishing points within a transaction for potential rollbacks (SAVEPOINT).
TCL commands ensure the consistency and integrity of data within a database during transactional processing.

TCL stands for Transaction Control Commands used for managing the changes made by DML commands like INSERT, DELETE, and UPDATE. The TCL commands are automatically committed in the database; that's why we cannot use them directly while creating tables or dropping them

  • COMMIT Statement:
    Ends the current transaction and makes all changes performed in the transaction permanent.

  • ROLLBACK Statement:
    Backs out or cancels the current transaction changes and restores changed data to its previous state.

  • SAVEPOINT:
    Establishes a point within a transaction to which you can later roll back.

DML (Data Manipulation Language)

  • DML (Data Manipulation Language) commands are responsible for manipulating the data stored in the database.
  • Primarily used to interact with and manage the data stored in database tables.
  • They include operations such as SELECT, INSERT, UPDATE, and DELETE.
  • Transaction Control - Typically used within transactions that can be committed or rolled back.

Note : A DML statement is not executed in the case of table deletion.
DML statements are used to access and manipulate data in an existing table.

DDL (Data Definition Language)

  • DDL (Data Definition Language) commands are used to define, manage, and control the structure of the database. They involve operations that impact the schema and structure of the database.
  • Employed to define and manage the structure of the database, including tables, indexes, constraints, etc.
  • They include operations such as CREATE, ALTER, DROP
  • Transaction Control - Often implicitly commits the transaction and may not be rolled back in some database systems.

DELETE vs DROP vs TRUNCATE

DELETE:

  • DML COMMAND
  • Deletes rows from the table one by one
  • Can use WHERE clause with DELETE to delete a single row
  • Slower than TRUNCATE
  • ROLLBACK is possible with DELETE

DROP:

  • DDL COMMAND
  • Deletes the entire structure or schema (Irrevocably removes the entire table and its associated structure)
  • Cannot use WHERE clause with DROP
  • Slower than DELETE & TRUNCATE
  • ROLLBACK IS NOT POSSIBLE WITH DROP
  • Frees up storage space immediately, Usually used cautiously, as it leads to permanent data loss

TRUNCATE:

  • DDL COMMAND
  • Deletes rows at one go
  • Cannot use WHERE clause with Truncate
  • Faster than both DELETE & DROP (because it doesn't log individual row deletions)
  • Transaction-specific and can be rolled back
  • Truncate statement removes all data from the table and frees the table's space
  • DELETE statement removes all data but does not free the table's space

Summary

  • Use DELETE when you need to selectively remove specific rows from a table.
  • Use DROP when you want to permanently remove a table or other database object.
  • Use TRUNCATE when you want to remove all rows from a table without deleting the table itself, and speed is crucial, especially for large datasets.
  • Always exercise caution, especially with DROP, as it permanently removes data and structures, and the action cannot be undone. Always make sure to have backups before performing irreversible operations.