SQL II
Review SQL
● SQL
○ DDL
○ DML
○ DCL
○ TCL
○ DQL
○ …
DDL
● CREATE
○ Table
■ CREATE TABLE mytable (
■ id int unsigned NOT NULL auto_increment, username varchar(100) NOT NULL, email varchar(100)
NOT NULL, PRIMARY KEY (id) );
○ View
■ CREATE VIEW MYVIEW AS SELECT C1, C2 C3 FROM TABLE1
● DROP
○ Table
○ View
● ALTER
○ Table
○ View
■ ADD, DROP, MODIFY
● TRUNCATE
DML
● INSERT
○ INSERT INTO mytable ( username, email ) VALUES ( "myuser", "myuser@[Link]" );
● UPDATE
○ UPDATE mytable SET username="myuser" WHERE id=8;
● DELETE
○ DELETE FROM mytable WHERE id=8;
DCL
● GRANT
○ GRANT SELECT, UPDATE, DELETE ON TABLEX TO USER1, USER2
● REVOKE
○ REVOKE SELECT, UPDATE, DELETE ON TABLEX FROM USER1
TCL
● Transactions
○ ACID
● COMMIT
○ COMMIT;
● ROLLBACK
○ ROLLBACK;
● SAVEPOINT
○ SAVEPOINT MYSAVEPOINT
DQL
● SELECT
○ SELECT * FROM mytable;
■ SELECT column1, column2, … FROM table_name;
○ SELECT * FROM mytable WHERE username = "myuser";
■ SELECT column1, column2, … FROM table_name WHERE condition;
○
Relations
● Types of Relations
● 1:1
● 1:N
● N:M
● How to represent relations?
Transactions
[Link]('/transfer', async (req, res) => {
const { fromAccountId, toAccountId, amount } = [Link];
if (!fromAccountId || !toAccountId || !amount || amount <= 0) {
return [Link](400).json({ error: 'Invalid transfer details' });
}
try {
const connection = await [Link](); // Get a connection from the pool
try {
await [Link](); // Start the transaction
// 1. Deduct amount from the 'from' account
const [fromResult] = await [Link](
'UPDATE accounts SET balance = balance - ? WHERE id = ?',
[amount, fromAccountId]
);
if ([Link] === 0) {
throw new Error('Insufficient balance or invalid from account'); // Rollback if insufficient balance
// 2. Add amount to the 'to' account
const [toResult] = await [Link](
'UPDATE accounts SET balance = balance + ? WHERE id = ?',
[amount, toAccountId]
);
i
f ([Link] === 0) {
throw new Error('Invalid to account'); // Rollback if to account is invalid
await [Link](); // Commit the transaction if both operations are successful
[Link]({ message: 'Transfer successful' });
} catch (error) {
await [Link](); // Rollback on any error
[Link]("Transaction Error:", error);
[Link](500).json({ error: 'Transfer failed', details: [Link] }); // Send error details
} finally {
[Link](); // Release the connection back to the pool (important!)
}
} catch (err) {
[Link]("Database Connection Error:", err);
[Link](500).json({ error: 'Database error' });
});
How to develop tables?
● How to model?
● Many approaches
○ Experience A1
○ Entity Relationship Diagram (ER Diagram)
E1 R1 E2
● Entity
A2 A3
● Attributes
● Relationship
Relational Model
● Strengths
● Challenges
Alternatives -> Non Standard Databases -> Not Only SQL -> NoSQL
NoSQL Types
● Key Value Store
○ Dynamo, [Link]
○ S3, …...
● Column-oriented Store
○ Flip -> focus on columns
○ Cassandra, [Link]
○ BigTable, …..
● Document-oriented Store
○ CouchDB, [Link]
○ MongoDB, [Link]
○ …..
● Graph-oriented Store
○ Neo4J, [Link]
○ ….
● …..