Skip to content

Commit 0038072

Browse files
feat(curriculum): add sql and bash review page (freeCodeCamp#61739)
Co-authored-by: Ilenia M <[email protected]>
1 parent 76faee3 commit 0038072

File tree

1 file changed

+228
-3
lines changed

1 file changed

+228
-3
lines changed

curriculum/challenges/english/blocks/review-bash-and-sql/6724e46581a1742244e45b59.md

Lines changed: 228 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -7,8 +7,233 @@ dashedName: review-bash-and-sql
77

88
# --description--
99

10-
Description placeholder
10+
## Database Normalization
1111

12-
# --assignment--
12+
This is the process of organizing a relational database to reduce data redundancy and improve integrity.
13+
14+
Its benefits include:
15+
16+
- Minimizing duplicated data, which saves storage and reduces inconsistencies.
17+
- Enforcing data integrity through the use of primary and foreign keys.
18+
- Making databases easier to maintain and understand.
19+
20+
### Normal Forms
21+
22+
- **1NF (First Normal Form)**
23+
- Each cell contains a single (atomic) value.
24+
- Each record is unique (enforced by a primary key).
25+
- Order of rows/columns is irrelevant.
26+
- Example: Move multiple phone numbers from a `students` table into a separate `student_phones` table.
27+
28+
- **2NF (Second Normal Form)**
29+
- Meets 1NF requirements.
30+
- No **partial dependencies**: every non-key attribute must depend on the entire composite primary key.
31+
- Example: Split `orders` table into `order_header` and `order_items` to avoid attributes depending on only part of the key.
32+
33+
- **3NF (Third Normal Form)**
34+
- Meets 2NF requirements.
35+
- No **transitive dependencies**: non-key attributes cannot depend on other non-key attributes.
36+
- Example: Move `city_postal_code` to a `cities` table instead of storing it with every order.
37+
38+
- **BCNF (Boyce-Codd Normal Form)**
39+
- Meets 3NF requirements.
40+
- Every determinant (left-hand side of a functional dependency) must be a superkey.
41+
42+
**Tip**: Aim for 3NF in most designs for a good balance of integrity and performance.
43+
44+
## Key SQL Concepts
45+
46+
- SQL is a Structured Query Language for communicating with relational databases.
47+
- **Basic commands**`SELECT`, `INSERT`, `UPDATE`, `DELETE`, `CREATE TABLE`, `ALTER TABLE`, etc.
48+
- `Joins` → Combines data from multiple tables (`INNER JOIN`, `LEFT JOIN`, `RIGHT JOIN`, `FULL JOIN`).
49+
50+
## Running SQL Commands in Bash
51+
52+
You can run SQL commands directly from the command line using the `psql` command-line client for PostgreSQL or similar tools for other databases.
53+
54+
For example, to run a SQL file in PostgreSQL:
55+
56+
```bash
57+
psql -U username -d database_name -c "SELECT * FROM students;"
58+
```
59+
60+
You can also execute MySQL commands directly:
61+
62+
```bash
63+
mysql -u username -p database_name -e "SELECT * FROM students;"
64+
```
65+
66+
### Run SQL from a File
67+
68+
```bash
69+
# PostgreSQL
70+
psql -U username -d database_name -f script.sql
71+
72+
# MySQL
73+
mysql -u username -p database_name < script.sql
74+
```
75+
76+
### Embed SQL in a Bash Script
77+
78+
```bash
79+
#!/bin/bash
80+
DB_USER="school_admin"
81+
DB_NAME="school"
82+
83+
# Insert student data
84+
psql -U "$DB_USER" -d "$DB_NAME" -c \
85+
"INSERT INTO students (name, age, major) VALUES ('Alice', 20, 'CS');"
86+
```
87+
88+
### Use of Variables in SQL
89+
90+
```bash
91+
#!/bin/bash
92+
DB_USER="school_admin"
93+
DB_NAME="school"
94+
STUDENT_NAME="Bob"
95+
AGE=21
96+
97+
psql -U "$DB_USER" -d "$DB_NAME" -c \
98+
"INSERT INTO students (name, age) VALUES ('$STUDENT_NAME', $AGE);"
99+
```
100+
101+
**Tip**: Sanitize variables to avoid SQL injection.
102+
103+
## Retrieving and Using SQL Query Results in Bash
104+
105+
When you run SQL queries via `psql`, you can **capture** and **process** the returned values in your Bash scripts.
106+
107+
### Capturing a Single Value
108+
109+
```bash
110+
#!/bin/bash
111+
DB_USER="school_admin"
112+
DB_NAME="school"
113+
114+
# Get total student count
115+
STUDENT_COUNT=$(psql -U "$DB_USER" -d "$DB_NAME" -t -A -c \
116+
"SELECT COUNT(*) FROM students;")
117+
118+
echo "Total students: $STUDENT_COUNT"
119+
```
120+
121+
Output → 42
122+
123+
### Retrieving Multiple Columns
13124

14-
Review the Bash and SQL topics and concepts.
125+
```bash
126+
#!/bin/bash
127+
DB_USER="school_admin"
128+
DB_NAME="school"
129+
130+
# Get top 3 students' names and ages
131+
RESULTS=$(psql -U "$DB_USER" -d "$DB_NAME" -t -A -F"," -c \
132+
"SELECT name, age FROM students LIMIT 3;")
133+
134+
echo "Top 3 students:"
135+
echo "$RESULTS"
136+
```
137+
138+
Output
139+
140+
```bash
141+
Alice,20
142+
Bob,21
143+
Charlie,22
144+
```
145+
146+
### Looping Through Query Results
147+
148+
```bash
149+
#!/bin/bash
150+
DB_USER="school_admin"
151+
DB_NAME="school"
152+
153+
# Get student names and majors
154+
psql -U "$DB_USER" -d "$DB_NAME" -t -A -F"," -c \
155+
"SELECT name, major FROM students;" | while IFS="," read -r name major
156+
do
157+
echo "Student: $name | Major: $major"
158+
done
159+
```
160+
161+
Shape of Output
162+
163+
```bash
164+
Student: Alice | Major: CS
165+
Student: Bob | Major: Math
166+
Student: Carol | Major: Physics
167+
```
168+
169+
## SQL Injection
170+
171+
It is a web security vulnerability where attackers insert malicious SQL code into input fields to manipulate the database.
172+
173+
This can lead to risky actions like:
174+
175+
- Bypassing authentication.
176+
- Stealing sensitive data.
177+
- Modifying or deleting records.
178+
179+
An example of an SQL injection attack:
180+
181+
```sql
182+
SELECT * FROM users WHERE username = ' " " OR "1"="1" -- ' AND password = 'anything';
183+
```
184+
185+
This query would return all users because the condition `OR "1"="1"` is always true, allowing attackers to bypass login checks.
186+
187+
### Preventing SQL Injection
188+
189+
1. **Use Prepared Statements**: These separate SQL code from data, preventing injection. Here's an example (Node.js with pg):
190+
191+
```sql
192+
client.query('SELECT * FROM users WHERE username = $1 AND password = $2', [username, password]);
193+
```
194+
195+
2. **Input Validation**: Sanitize and validate all user inputs to ensure they conform to expected formats.
196+
197+
3. **Least Privilege**: Use database accounts with the minimum permissions necessary for the application.
198+
199+
**Note**: Never grant admin rights to application accounts.
200+
201+
## N+1 Problem
202+
203+
The N+1 problem occurs when an application makes one query to retrieve a list of items (N) and then makes an additional query for each item to retrieve related data, resulting in N+1 queries.
204+
205+
**Why It’s Bad**
206+
207+
- Each query adds network and processing overhead.
208+
- Multiple small queries are slower than one optimized query.
209+
210+
### Example of N+1 Pattern
211+
212+
```sql
213+
-- 1: Get list of orders
214+
SELECT * FROM orders LIMIT 50;
215+
216+
-- N: For each order, get customer
217+
SELECT * FROM customers WHERE customer_id = ...;
218+
```
219+
220+
**Solution**: Use `JOINs` or other set-based operations.
221+
222+
```sql
223+
SELECT
224+
orders.order_id,
225+
orders.product,
226+
orders.quantity,
227+
customers.customer_id,
228+
customers.name,
229+
customers.email,
230+
customers.address
231+
FROM orders
232+
JOIN customers
233+
ON orders.customer_id = customers.customer_id
234+
WHERE orders.order_id IN (SELECT order_id FROM orders LIMIT 50);
235+
```
236+
237+
Always look for opportunities to combine related data into a single query.
238+
239+
# --assignment--

0 commit comments

Comments
 (0)