Adds SQL primer.

This commit is contained in:
Tanmay 2022-07-18 00:24:02 +01:00
parent b7d9c8cb7a
commit 555a5629f4
4 changed files with 779 additions and 0 deletions

View File

@ -0,0 +1,213 @@
DROP DATABASE IF EXISTS `jedi_academy`;
CREATE DATABASE `jedi_academy`;
USE `jedi_academy`;
SET
NAMES utf8;
SET
character_set_client = utf8mb4;
-- CREATE TABLES --
CREATE TABLE `students` (
`id` int NOT NULL AUTO_INCREMENT,
`first_name` varchar(255) NOT NULL,
`last_name` varchar(255) NOT NULL,
`email` varchar(255) NOT NULL,
`phone` varchar(255),
`birth_date` date,
`address` varchar(255),
`iq` int,
`batch_id` int,
PRIMARY KEY (`id`)
);
CREATE TABLE `batches` (
`id` int NOT NULL AUTO_INCREMENT,
`name` varchar(255) NOT NULL,
`start_date` date NOT NULL,
`description` varchar(255),
`instructor_id` int,
PRIMARY KEY (`id`)
);
CREATE TABLE `instructors` (
`id` int NOT NULL AUTO_INCREMENT,
`first_name` varchar(255) NOT NULL,
`last_name` varchar(255) NOT NULL,
`email` varchar(255) NOT NULL,
`phone` varchar(255),
PRIMARY KEY (`id`)
);
-- ADD FOREIGN KEYS --
ALTER TABLE
`students`
ADD
FOREIGN KEY (`batch_id`) REFERENCES `batches`(`id`);
ALTER TABLE
`batches`
ADD
FOREIGN KEY (`instructor_id`) REFERENCES `instructors`(`id`);
-- INSERT DATA --
-- Instructors --
INSERT INTO
`instructors` (`first_name`, `last_name`, `email`, `phone`)
VALUES
('Master', 'Yoda', 'y@jedi.com', '123-456-7890'),
(
'Obi-Wan',
'Kenobi',
'o@jedi.com',
'123-456-7890'
),
(
'Sherlock',
'Holmes',
's@sherlock.ed',
'123-456-7890'
),
(
'Rani',
'Laxmi Bai',
'r@rebelli.on',
'123-456-7890'
),
(
'Thor',
'Odinson',
't@thunder.com',
'123-456-7890'
);
-- Batches --
INSERT INTO
`batches` (
`name`,
`start_date`,
`instructor_id`
)
VALUES
(
'Jedi Academy 1',
'2012-01-01',
1
),
(
'Jedi Academy 2',
'2014-01-01',
2
),
(
'Sherlock Academy',
'2017-01-01',
3
),
(
'Independence Academy',
'1857-01-01',
4
),
(
'Love and Thunder Academy',
'2022-01-01',
5
);
-- Students --
INSERT INTO
`students` (
`first_name`,
`last_name`,
`email`,
`phone`,
`birth_date`,
`address`,
`iq`,
`batch_id`
)
VALUES
(
'Anakin',
'Skywalker',
'darth@empire.blr',
'123-456-7890',
'1973-01-01',
'Tatooine',
130,
1
),
(
'Luke',
'Skywalker',
'luke@resistance.com',
'123-456-7890',
'1994-01-01',
'Tatooine',
120,
2
),
(
'Leia',
'Organa',
'leia@resistance.com',
'123-456-7890',
'1994-01-01',
'Alderaan',
130,
2
),
(
'John',
'Watson',
'j@sherlock.ed',
'123-456-7890',
'1657-01-01',
'London',
130,
3
),
(
'Mycroft',
'Holmes',
'm@sherlock.ed',
'123-456-7890',
'1657-01-01',
'London',
150,
3
),
(
'Tantia',
'Tope',
't@rebelli.on',
'123-456-7890',
'1657-01-01',
'Jhansi',
130,
4
),
(
'Jane',
'Foster',
'jane@th.or',
'123-456-7890',
'2022-01-01',
'New Asgard',
160,
5
),
(
'Korg',
'Rock',
'korg@th.or',
'123-456-7890',
'2022-01-01',
'New Asgard',
80,
5
);

View File

@ -0,0 +1,210 @@
# Queries
## Insert queries
1. Insert a row with all columns
```sql
INSERT INTO students
VALUES (1, 'Tantia', 'Tope', 't@t.com', '1234567890', 1);
```
2. Insert a row with some columns
```sql
INSERT INTO students (first_name, last_name)
VALUES ('Tantia', 'Tope');
```
---
## Select Queries
1. Get all students
```sql
SELECT *
FROM students;
```
2. Get first and last name of all students
```sql
SELECT first_name, last_name
FROM students;
```
3. Get first name of all students with output column name as `Student Name`
```sql
SELECT first_name AS "Student Name"
FROM students;
```
4. Get all unique addresses of all students
```sql
SELECT DISTINCT address FROM students;
```
5. Get all students with ID equal to 1
```sql
SELECT * FROM students WHERE id = 1;
```
6. Get all students with IQ greater than 150
```sql
SELECT * FROM students WHERE iq > 150;
```
7. Get all students with IQ less than 100
```sql
SELECT * FROM students WHERE iq < 100;
```
8. Get all students with IQ greater than 100 and less than150
```sql
SELECT * FROM students
WHERE iq > 100 AND iq < 150;
```
9. Get all students with IQ greater than 100 or less than 150
```sql
SELECT * FROM students
WHERE iq BETWEEN 100 AND 150;
```
10. Get all students with first name `Tantia`
```sql
SELECT * FROM students WHERE first_name = 'Tantia';
```
11. Get all students with first name `Tantia` and last name `Tope`
```sql
SELECT * FROM students
WHERE first_name = 'Tantia' AND last_name = 'Tope';
```
12. Get all students with first name `John` or first name `Mycroft`
```sql
SELECT * FROM students
WHERE first_name = 'John' OR first_name = 'Mycroft';
```
13. Get all students with name `John Watson` or `Mycroft Holmes`
```sql
SELECT * FROM students
WHERE (first_name = 'John' AND last_name = 'Watson')
OR (first_name = 'Mycroft' AND last_name = 'Holmes');
```
14. Get all students without the first name `John`
```sql
SELECT * FROM students WHERE first_name <> 'John';
```
15. Get all students without the first name `John` or last name `Mycroft`
```sql
SELECT * FROM students
WHERE first_name <> 'John' AND last_name <> 'Mycroft';
```
16. Get all students with first name starting with `T`
```sql
SELECT * FROM students WHERE first_name LIKE 'T%';
```
17. Get all students with last name ending with `walker`
```sql
SELECT * FROM students WHERE last_name LIKE '%walker';
```
18. Get all students with first name containing `T`
```sql
SELECT * FROM students WHERE first_name LIKE '%T%';
```
19. Get all students with last name in the format `___walker`
```sql
SELECT * FROM students WHERE last_name LIKE '___walker';
```
20. Get all students in Jhansi and London
```sql
SELECT * FROM students
WHERE address IN ('Jhansi', 'London');
```
21. Get all students which do not have a batch id
```sql
SELECT * FROM students WHERE batch_id IS NULL;
```
22. Get the first 5 students
```sql
SELECT * FROM students LIMIT 5;
```
23. Get the first 5 students sorted by IQ
```sql
SELECT * FROM students ORDER BY iq LIMIT 5;
```
24. Get the first 5 students sorted by IQ in descending order
```sql
SELECT * FROM students ORDER BY iq DESC LIMIT 5;
```
25. Get the first 5 students sorted by IQ in descending order and then by first name
```sql
SELECT * FROM students
ORDER BY iq DESC, first_name LIMIT 5;
```
---
## Update Queries
1. Update a row
```sql
UPDATE students SET first_name = 'Tantia' WHERE id = 1;
```
2. Update a row with a condition
```sql
UPDATE students SET first_name = 'Tantia' WHERE id = 1 AND first_name = 'John';
```
3. Update multiple columns
```sql
UPDATE students SET first_name = 'Tantia', last_name = 'Tope' WHERE id = 1 AND first_name = 'John';
```
## Delete Queries
1. Delete a row with a condition
```sql
DELETE FROM students
WHERE id = 1 AND first_name = 'John';
```
2. Delete a multiple rows
```sql
DELETE FROM students WHERE id IN (1, 2, 3);
```
## Joining Queries
1. Get first name and last name of all students and their batch names
```sql
SELECT students.first_name, students.last_name, batches.name FROM students JOIN batches ON students.batch_id = batches.id;
```
2. Get first name and last name of all students and their instructor names
```sql
SELECT s.first_name, s.last_name, i.first_name, b.name, i.last_name
FROM students s
JOIN batches b ON s.batch_id = b.id
JOIN instructors i ON b.instructor_id = i.id;
```

View File

@ -0,0 +1,191 @@
# Queries
## Insert queries
1. Insert a row with your name and all the other fields
```sql
```
1. Insert a row with just mandatory fields
```sql
```
---
## Select Queries
1. Get all students
```sql
```
2. Get first and last name of all students
```sql
```
3. Get first name of all students with output column name as `Student Name`
```sql
```
4. Get all unique addresses of all students
```sql
```
5. Get all students with ID equal to 1
```sql
```
6. Get all students with IQ greater than 150
```sql
```
7. Get all students with IQ less than 100
```sql
```
8. Get all students with IQ greater than 100 and less than150
```sql
```
9. Get all students with IQ greater than 100 or less than 150
```sql
```
10. Get all students with first name `Tantia`
```sql
```
11. Get all students with first name `Tantia` and last name `Tope`
```sql
```
12. Get all students with first name `John` or first name `Mycroft`
```sql
```
13. Get all students with name `John Watson` or `Mycroft Holmes`
```sql
```
14. Get all students without the first name `John`
```sql
```
15. Get all students without the first name `John` or last name `Mycroft`
```sql
```
16. Get all students with first name starting with `T`
```sql
```
17. Get all students with last name ending with `walker`
```sql
```
18. Get all students with first name containing `T`
```sql
```
19. Get all students with last name in the format `___walker`
```sql
```
20. Get all students in Jhansi and London
```sql
```
21. Get all students which do not have a batch id
```sql
```
22. Get the first 5 students
```sql
```
23. Get the first 5 students sorted by IQ
```sql
```
24. Get the first 5 students sorted by IQ in descending order
```sql
```
25. Get the first 5 students sorted by IQ in descending order and then by first name
```sql
```
---
## Update Queries
1. Update a row
```sql
```
2. Update a row with a condition
```sql
```
3. Update multiple columns
```sql
```
## Delete Queries
1. Delete a row with a condition
```sql
```
2. Delete a multiple rows
```sql
```
## Joining Queries
1. Get first name and last name of all students and their batch names
```sql
```
2. Get first name and last name of all students and their instructor names
```sql
```

View File

@ -0,0 +1,165 @@
# SQL Primer
## Agenda
* CRUD with SQL
* JOIN
## CRUD with SQL
### Create rows
**Keyword**: `INSERT`
**Syntax**: `INSERT INTO table_name (column1, column2, ...) VALUES (value1, value2, ...)`
#### Examples
1. Insert a row with all columns
```sql
INSERT INTO students VALUES (1, 'Tantia', 'Tope', 't@t.com', '1234567890', 1);
```
2. Insert a row with some columns
```sql
INSERT INTO students (first_name, last_name) VALUES ('Tantia', 'Tope');
```
### Read rows
**Keyword**: `SELECT`
**Syntax**: `SELECT column1, column2, ... FROM table_name WHERE condition ORDER BY column1, column2, ... ASC/DESC LIMIT #`
#### Examples
1. Get all rows
```sql
SELECT * FROM students;
```
2. Get certain fields from all rows
```sql
SELECT first_name, last_name FROM students;
```
3. Filter rows by condition
```sql
SELECT * FROM students WHERE first_name = 'Tantia';
```
4. Order rows by column
```sql
SELECT * FROM students ORDER BY first_name ASC;
```
5. Limit number of rows
```sql
SELECT * FROM students LIMIT 10;
```
#### Common operators for WHERE clause
| Operator | Description | Example |
| -------- | --------------------- | --------------------------------------------------------------------------- |
| = | Equal | `SELECT * FROM students WHERE first_name = 'Tantia'` |
| != or <> | Not equal | `SELECT * FROM students WHERE first_name != 'Tantia'` |
| NOT | NOT | `SELECT * FROM students WHERE NOT first_name = 'John'` |
| > | Greater than | `SELECT * FROM students WHERE iq > 150` |
| < | Less than | `SELECT * FROM students WHERE age < 100` |
| >= | Greater than or equal | `SELECT * FROM students WHERE age >= 18` |
| <= | Less than or equal | `SELECT * FROM students WHERE age <= 18` |
| AND | AND | `SELECT * FROM students WHERE first_name = 'Tantia' AND last_name = 'Tope'` |
| OR | OR | `SELECT * FROM students WHERE first_name = 'John' OR last_name = 'Mycroft'` |
| IN | IN | `SELECT * FROM students WHERE first_name IN ('John', 'Mycroft')` |
| BETWEEN | BETWEEN | `SELECT * FROM students WHERE iq BETWEEN 100 AND 150` |
| LIKE | LIKE | `SELECT * FROM students WHERE first_name LIKE '%T%'` |
| REGEXP | REGEXP | `SELECT * FROM students WHERE first_name REGEXP '^[A-Z]{1}'` |
| NULL | NULL | `SELECT * FROM students WHERE first_name IS NULL` |
| NOT NULL | NOT NULL | `SELECT * FROM students WHERE first_name IS NOT NULL` |
#### String matching wildcards
With `LIKE` you can use the following two wildcard characters in the pattern:
* `%` matches any number of characters, even zero characters.
* `_` matches exactly one character.
```sql
SELECT * FROM students WHERE first_name LIKE 'T%';
```
```sql
SELECT * FROM students WHERE first_name LIKE 'T_';
```
### Update rows
**Keyword**: `UPDATE`
**Syntax**: `UPDATE table_name SET column1 = value1, column2 = value2, ... WHERE condition`
##### Examples
1. Update a row
```sql
UPDATE students SET first_name = 'Tantia' WHERE id = 1;
```
2. Update a row with a condition
```sql
UPDATE students SET first_name = 'Tantia' WHERE id = 1 AND first_name = 'John';
```
3. Update multiple columns
```sql
UPDATE students SET first_name = 'Tantia', last_name = 'Tope' WHERE id = 1 AND first_name = 'John';
```
### Delete rows
**Keyword**: `DELETE`
**Syntax**: `DELETE FROM table_name WHERE condition`
##### Examples
1. Delete a row with a condition
```sql
DELETE FROM students WHERE id = 1 AND first_name = 'John';
```
2. Delete a multiple rows
```sql
DELETE FROM students WHERE id IN (1, 2, 3);
```
## Join
Join is the widely-used clause in the SQL Server essentially to combine and retrieve data from two or more tables. In a real-world relational database, data is structured in many tables and which is why, there is a constant need to join these multiple tables based on logical relationships between them.
### Inner join
Inner Join clause in SQL Server creates a new table (not physical) by combining rows that have matching values in two or more tables. This join is based on a logical relationship (or a common field) between the tables and is used to retrieve data that appears in both tables.
![Inner Join](https://i.stack.imgur.com/kZcvR.gif)
Assume, we have two tables, Table A and Table B, that we would like to join using SQL Inner Join. The result of this join will be a new result set that returns matching rows in both these tables. The intersection part in black below shows the data retrieved using Inner Join.
![Inner Join](https://www.sqlshack.com/wp-content/uploads/2019/06/venn-diagram-representation-of-sql-inner-join-.png)
**Keyword**: `INNER JOIN` or simply `JOIN`
**Syntax**: `SELECT column1, column2, ... FROM table_name1 JOIN table_name2 ON condition`
For example, we want to get the batch names of all the students along with their names.
| id | first_name | last_name | batch_name |
| --- | ---------- | --------- | ---------- |
| 1 | John | Watson | Sherlock |
| 2 | Mycroft | Holmes | Sherlock |
This can be achieved by using the following SQL query:
```sql
SELECT s.first_name, s.last_name, b.batch_name FROM students s JOIN batches ON s.batch_id = b.id;
```