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
-`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
13
124
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.
0 commit comments