Skip to content

SQL Basics

1. SQL Data Types

MySQL provides various data types categorised into:

Numeric Data Types

Data TypeDescription
INTInteger value (4 bytes)
TINYINTSmall integer (1 byte)
SMALLINTSmall integer (2 bytes)
MEDIUMINTMedium integer (3 bytes)
BIGINTLarge integer (8 bytes)
DECIMAL/NUMERICFixed-point number
FLOATFloating-point number (4 bytes)
DOUBLEFloating-point number (8 bytes)

String Data Types

Data TypeDescription
CHAR(n)Fixed-length string
VARCHAR(n)Variable-length string
TEXTLarge text field
BLOBBinary large object

Date and Time Data Types

Data TypeDescription
DATEStores date (YYYY-MM-DD)
DATETIMEStores date and time (YYYY-MM-DD HH:MM:SS)
TIMESTAMPStores UNIX timestamp
TIMEStores time (HH:MM:SS)
YEARStores year (YYYY)

2. SQL Command Categories

CategoryFull FormPurposeKeywords
DDLData Definition LanguageDefines database schemaCREATE, ALTER, DROP, TRUNCATE
DMLData Manipulation LanguageModifies dataINSERT, UPDATE, DELETE
DQLData Query LanguageRetrieves dataSELECT
TCLTransaction Control LanguageControls transactionsCOMMIT, ROLLBACK, SAVEPOINT
DCLData Control LanguageManages permissionsGRANT, REVOKE

3. Common SQL Commands

DDL Commands

  • Create Database

    CREATE DATABASE mydb;
  • Create Table

    CREATE TABLE users (
    id INT AUTO_INCREMENT PRIMARY KEY,
    name VARCHAR(100),
    email VARCHAR(100) UNIQUE,
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
    );
  • Alter Table

    ALTER TABLE users ADD COLUMN phone VARCHAR(15);
  • Drop Table

    DROP TABLE users;

DML Commands

  • Insert Data

    INSERT INTO users (name, email) VALUES ('John Doe', 'john@example.com');
  • Update Data

    UPDATE users SET name = 'Jane Doe' WHERE id = 1;
  • Delete Data

    DELETE FROM users WHERE id = 1;

DQL Commands

  • Select All Data

    SELECT * FROM users;
  • Select Specific Columns

    SELECT name, email FROM users;
  • Select with Condition (WHERE)

    SELECT * FROM users WHERE email = 'john@example.com';

4. PHP & MySQL Connection Methods

4.1 MySQLi (Object-Oriented)

$mysqli = new mysqli("localhost", "username", "password", "mydb");
if ($mysqli->connect_error) {
die("Connection failed: " . $mysqli->connect_error);
}
echo "Connected successfully!";

4.2 MySQLi (Procedural)

$conn = mysqli_connect("localhost", "username", "password", "mydb");
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
echo "Connected successfully!";

4.3 PDO (Object-Oriented)

try {
$pdo = new PDO("mysql:host=localhost;dbname=mydb", "username", "password");
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
echo "Connected successfully!";
} catch (PDOException $e) {
die("Connection failed: " . $e->getMessage());
}

5. Prepared Statements (Prevent SQL Injection)

5.1 MySQLi - OOP

$stmt = $mysqli->prepare("INSERT INTO users (name, email) VALUES (?, ?)");
$stmt->bind_param("ss", $name, $email);
$name = "Alice";
$email = "alice@example.com";
$stmt->execute();
$stmt->close();

5.2 MySQLi - Procedural

$sql = "INSERT INTO users (name, email) VALUES (?, ?)";
$stmt = mysqli_prepare($conn, $sql);
mysqli_stmt_bind_param($stmt, "ss", $name, $email);
mysqli_stmt_execute($stmt);
mysqli_stmt_close($stmt);

5.3 PDO

$stmt = $pdo->prepare("INSERT INTO users (name, email) VALUES (?, ?)");
$stmt->execute(["Bob", "bob@example.com"]);

6. Fetching Data

6.1 MySQLi - OOP

$result = $mysqli->query("SELECT * FROM users");
while ($row = $result->fetch_assoc()) {
echo "Name: " . $row['name'] . "<br>";
}

6.2 MySQLi - Procedural

$sql = "SELECT * FROM users";
$result = mysqli_query($conn, $sql);
while ($row = mysqli_fetch_assoc($result)) {
echo "Name: " . $row['name'] . "<br>";
}

6.3 PDO

$stmt = $pdo->query("SELECT * FROM users");
while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
echo "Name: " . $row['name'] . "<br>";
}

7. Transactions (ACID Compliance)

7.1 MySQLi - OOP

$mysqli->autocommit(FALSE);
$mysqli->begin_transaction();
try {
$mysqli->query("UPDATE users SET name='Charlie' WHERE id=2");
$mysqli->commit();
} catch (Exception $e) {
$mysqli->rollback();
echo "Transaction failed: " . $e->getMessage();
}

7.2 PDO

$pdo->beginTransaction();
try {
$pdo->exec("UPDATE users SET name='Charlie' WHERE id=2");
$pdo->commit();
} catch (Exception $e) {
$pdo->rollback();
echo "Transaction failed: " . $e->getMessage();
}

8. Error Handling

8.1 MySQLi - OOP

if (!$mysqli->query("INVALID SQL QUERY")) {
echo "Error: " . $mysqli->error;
}

8.2 PDO

try {
$pdo->exec("INVALID SQL QUERY");
} catch (PDOException $e) {
echo "Error: " . $e->getMessage();
}

9. Security Best Practices

  • ✅ Use Prepared Statements to prevent SQL Injection.
  • ✅ Use password_hash() before storing passwords.
  • ✅ Grant least privileges to MySQL users.
  • ✅ Keep MySQL updated for security patches.
  • ✅ Regularly back up your database:
    Terminal window
    mysqldump -u root -p mydb > backup.sql

10. Commonly Used SQL Keywords

KeywordDescription
SELECTRetrieves data from one or more tables.
FROMSpecifies the table from which to retrieve data.
WHEREFilters records based on a condition.
AND/ORCombines multiple conditions in a WHERE clause.
ORDER BYSorts the result set in ascending or descending order.
GROUP BYGroups records that have the same values in specified columns.
HAVINGFilters the result set after applying GROUP BY.
INSERT INTOAdds new records to a table.
UPDATEModifies existing records in a table.
DELETERemoves records from a table.
JOINCombines rows from two or more tables based on a related column.
LEFT JOIN/RIGHT JOINRetrieves records from one table even if there is no match in the other table.
INNER JOINReturns only the rows where there is a match in both tables.
DISTINCTRemoves duplicate values from the result set.
LIMITSpecifies the number of records to return.
LIKESearches for a specified pattern in a column.
INSpecifies multiple values for a column.
BETWEENFilters records within a specific range.
NULLChecks if a column contains a NULL value.
ASRenames a column or table for easier reference.
EXISTSChecks if a subquery returns any results.
UNIONCombines the result sets of two or more SELECT queries.
CASEAdds conditional logic in queries.

Conclusion

  • ✅ Use PDO for better flexibility and database compatibility.
  • ✅ Use MySQLi for MySQL-specific applications.
  • ✅ Always use prepared statements for security.
  • ✅ Use transactions for critical operations to ensure data integrity.