Developer Guides, Cheat Sheets & Tools

SQL course - Part 12: ADMINISTRATION AND SECURITY

Part index Prerequisites Previous Next Full course

πŸ›‘οΈ PART 12 β€” ADMINISTRATION AND SECURITY


54. Security: users, roles, and permissions

🎚️ Level ⏱️ Time 🎯 After this chapter you can…
πŸŸ‘πŸ”΄ Intermediate–Expert 40 min Create logins, users, and roles Β· Grant only the access each account needs Β· Show each user only their own rows Β· Protect sensitive data

[!NOTE] πŸ“Œ In plain words: Security answers three questions: who are you (authentication), what are you allowed to do (authorization), and what did you actually do (auditing).

🌍 Analogy: An office building. Your ID badge proves who you are. The door access list decides which floors you can enter. The entry log records where you went. A database needs all three.

54.1 πŸ”‘ The security hierarchy

πŸŸ₯ MSSQL                              🟦 MySQL
─────────────────────────             ─────────────────────────
LOGIN     (server level)              USER 'name'@'host'
   β”‚                                     β”‚
   β–Ό                                     β–Ό
USER      (database level)            (users are server-wide)
   β”‚                                     β”‚
   β–Ό                                     β–Ό
ROLE      (group of permissions)      ROLE (MySQL 8.0+)
   β”‚                                     β”‚
   β–Ό                                     β–Ό
PERMISSION on objects                 PRIVILEGE on objects

πŸ”€ The key structural difference: MSSQL separates the login (connects to the server) from the user (exists inside one database) β€” so one login can map to users in several databases with different rights. MySQL identifies a user by name plus host ('app'@'10.0.0.%'), which is itself a security control: the same username from a different machine is a different account.

54.2 πŸ‘€ Creating users

-- πŸŸ₯ MSSQL
-- Step 1: a server-level login
CREATE LOGIN app_user WITH PASSWORD = 'Str0ng!Passw0rd#2026';

-- Step 2: a database-level user mapped to it
USE ShopDB;
CREATE USER app_user FOR LOGIN app_user;

-- Windows authentication (preferred on a company Windows network β€” no password to leak; not available on Linux/Docker)
CREATE LOGIN [DOMAIN\SalesTeam] FROM WINDOWS;
CREATE USER [DOMAIN\SalesTeam] FOR LOGIN [DOMAIN\SalesTeam];

-- Maintenance (on a throwaway login, so app_user survives for the rest of this chapter)
CREATE LOGIN old_login WITH PASSWORD = 'Old!Passw0rd#2026';
CREATE USER old_login FOR LOGIN old_login;
ALTER LOGIN old_login WITH PASSWORD = 'NewStr0ng!Passw0rd';
ALTER LOGIN old_login DISABLE;
DROP USER old_login;
DROP LOGIN old_login;
-- 🟦 MySQL
CREATE USER 'app_user'@'localhost'  IDENTIFIED BY 'Str0ng!Passw0rd#2026';
CREATE USER 'app_user'@'10.0.0.%'   IDENTIFIED BY 'Str0ng!Passw0rd#2026';  -- a subnet
CREATE USER 'report_user'@'%'       IDENTIFIED BY 'An0ther!Passw0rd';      -- ⚠️ any host

-- Password policy (a separate account, so app_user survives for the rest of this chapter)
CREATE USER 'policy_user'@'localhost'
    IDENTIFIED BY 'Str0ng!Pass'
    PASSWORD EXPIRE INTERVAL 90 DAY
    FAILED_LOGIN_ATTEMPTS 5 PASSWORD_LOCK_TIME 1;

ALTER USER 'policy_user'@'localhost' IDENTIFIED BY 'NewPassw0rd!';
ALTER USER 'policy_user'@'localhost' ACCOUNT LOCK;
DROP USER 'policy_user'@'localhost';

[!WARNING] ⚠️ 'user'@'%' allows connection from anywhere on the network. Restrict the host wherever you can β€” it turns a leaked password into a much smaller incident.

54.3 🎫 Granting and revoking permissions

-- βœ… MSSQL

-- The other accounts used below (database users WITHOUT LOGIN are fine for practice)
CREATE USER support_user WITHOUT LOGIN;
CREATE USER report_user  WITHOUT LOGIN;
CREATE USER temp_user    WITHOUT LOGIN;

-- Read-only on one table
GRANT SELECT ON customers TO app_user;

-- Read/write
GRANT SELECT, INSERT, UPDATE, DELETE ON orders TO app_user;

-- Column-level: email and phone are NOT granted
GRANT SELECT (customer_id, full_name, city, country) ON customers TO support_user;

-- Execute a procedure without any table rights at all (the procedure from Chapter 37)
GRANT EXECUTE ON usp_get_customer_orders TO app_user;

-- Everything in a schema
GRANT SELECT ON SCHEMA::dbo TO report_user;

-- Take it back
REVOKE INSERT ON orders FROM app_user;

-- DENY beats every GRANT, even ones inherited through a role (MSSQL only)
DENY SELECT ON customers TO temp_user;
-- βœ… MySQL

-- The other account used below
CREATE USER 'support_user'@'localhost' IDENTIFIED BY 'Supp0rt!Passw0rd';

-- Read-only on one table
GRANT SELECT ON ShopDB.customers TO 'app_user'@'localhost';

-- Read/write
GRANT SELECT, INSERT, UPDATE, DELETE ON ShopDB.orders TO 'app_user'@'localhost';

-- Column-level: email and phone are NOT granted
GRANT SELECT (customer_id, full_name, city, country) ON ShopDB.customers TO 'support_user'@'localhost';

-- Execute a procedure without any table rights at all (the procedure from Chapter 37)
GRANT EXECUTE ON PROCEDURE ShopDB.usp_get_customer_orders TO 'app_user'@'localhost';

-- Everything in a database
GRANT SELECT ON ShopDB.* TO 'report_user'@'%';

-- Take it back
REVOKE INSERT ON ShopDB.orders FROM 'app_user'@'localhost';

FLUSH PRIVILEGES;   -- only needed after editing the grant tables directly; harmless after GRANT/REVOKE

[!TIP] πŸ’‘ MSSQL’s three-state model: GRANT, REVOKE, DENY. REVOKE removes a permission you granted. DENY actively blocks it and overrides any grant, including ones inherited from a role. MySQL has only grant and revoke β€” there is no deny.

54.4 πŸ‘₯ Roles β€” how permissions are actually managed

[!NOTE] πŸ“Œ Never grant permissions directly to people. Grant to roles; put people in roles. When someone changes job, you change one membership instead of auditing 40 individual grants.

-- πŸŸ₯ MSSQL
CREATE ROLE sales_readonly;
CREATE ROLE sales_readwrite;
CREATE ROLE reporting;

GRANT SELECT ON SCHEMA::dbo TO sales_readonly;

GRANT SELECT, INSERT, UPDATE ON orders      TO sales_readwrite;
GRANT SELECT, INSERT, UPDATE ON order_items TO sales_readwrite;
GRANT SELECT                  ON products   TO sales_readwrite;

ALTER ROLE sales_readonly  ADD MEMBER report_user;
ALTER ROLE sales_readwrite ADD MEMBER app_user;

CREATE USER old_user WITHOUT LOGIN;                 -- someone about to change job
ALTER ROLE sales_readwrite ADD MEMBER old_user;
ALTER ROLE sales_readwrite DROP MEMBER old_user;

-- Built-in database roles (practice users without logins)
CREATE USER analyst_user WITHOUT LOGIN;
CREATE USER etl_user     WITHOUT LOGIN;
CREATE USER admin_user   WITHOUT LOGIN;
ALTER ROLE db_datareader ADD MEMBER analyst_user;   -- read everything
ALTER ROLE db_datawriter ADD MEMBER etl_user;       -- write everything
ALTER ROLE db_owner      ADD MEMBER admin_user;     -- ⚠️ everything
-- 🟦 MySQL 8.0+
CREATE ROLE 'sales_readonly', 'sales_readwrite', 'reporting';

GRANT SELECT ON ShopDB.* TO 'sales_readonly';
GRANT SELECT, INSERT, UPDATE ON ShopDB.orders      TO 'sales_readwrite';
GRANT SELECT, INSERT, UPDATE ON ShopDB.order_items TO 'sales_readwrite';

GRANT 'sales_readwrite' TO 'app_user'@'localhost';

-- ⚠️ MySQL roles are NOT active until set as default
SET DEFAULT ROLE ALL TO 'app_user'@'localhost';

REVOKE 'sales_readwrite' FROM 'app_user'@'localhost';

[!WARNING] ⚠️ The MySQL gotcha that wastes hours: you grant a role, the user connects, and they still have no permissions. MySQL roles must be activated β€” either with SET DEFAULT ROLE (once, by an admin) or SET ROLE (per session). Always run SET DEFAULT ROLE ALL after granting.

54.5 πŸ”’ The principle of least privilege

[!NOTE] πŸ“Œ Give every account the minimum permissions it needs to do its job β€” and nothing more.

Account Should have Should NOT have
Web application SELECT/INSERT/UPDATE on business tables, or just EXECUTE on procedures DROP, ALTER, DELETE on audit tables, access to other databases
Reporting/BI SELECT only, ideally on views, ideally on a replica Any write permission at all
ETL/import job Write access to staging tables, EXECUTE on load procedures Access to production tables outside its scope
Developer (on the live server) SELECT on non-sensitive data; nothing else without a change request sa / root. Ever.
DBA Administrative rights, used from a named personal account A shared account nobody can attribute
-- βœ… A realistic least-privilege setup for the ShopDB web app

-- πŸŸ₯ MSSQL
CREATE LOGIN shop_app WITH PASSWORD = 'Str0ng!Passw0rd#2026';
USE ShopDB;
CREATE USER shop_app FOR LOGIN shop_app;

CREATE ROLE app_role;
GRANT SELECT ON dbo.products   TO app_role;
GRANT SELECT ON dbo.categories TO app_role;
GRANT SELECT, INSERT, UPDATE ON dbo.orders      TO app_role;
GRANT SELECT, INSERT          ON dbo.order_items TO app_role;
GRANT SELECT, INSERT          ON dbo.payments    TO app_role;
GRANT SELECT, INSERT, UPDATE  ON dbo.customers   TO app_role;
DENY  DELETE ON dbo.orders   TO app_role;      -- the app soft-deletes only
DENY  SELECT ON dbo.employees TO app_role;     -- salaries are none of its business

ALTER ROLE app_role ADD MEMBER shop_app;

[!TIP] πŸ’‘ The single most valuable security pattern: grant EXECUTE on stored procedures and nothing else. The application cannot run arbitrary SQL, cannot read tables it was not meant to, and cannot be exploited into a DROP TABLE β€” because it has no table permissions at all. It works through ownership chaining: when a procedure and the tables it touches have the same owner, SQL Server checks permission on the procedure only. That is why many large companies require procedure-only access.

54.6 πŸ›‘οΈ Row-Level Security β€” filtering rows per user, automatically

[!NOTE] πŸ“Œ In plain words: Permissions normally work on whole tables and columns. Row-Level Security (RLS) goes one level deeper: each user sees only their own rows of the same table β€” and the filter is applied by the engine, so no query can escape it.

🌍 Analogy: A shared office inbox where the mail is pre-sorted. Everyone opens the same cabinet, but each person physically only finds their own letters. They cannot look at a colleague’s post even by accident, because it is not in the drawer they opened.

The naive approach is a view with a WHERE clause β€” but anyone with table access can simply query the table directly and bypass it. RLS filters direct table queries while the policy is enabled. Administrators who can alter the policy remain trusted.

-- πŸŸ₯ MSSQL: STEP 1 β€” a predicate function that returns a row when access is allowed
CREATE SCHEMA rls;
GO

CREATE OR ALTER FUNCTION rls.fn_orders_by_rep(@employee_id INT)
RETURNS TABLE
WITH SCHEMABINDING                        -- πŸ”‘ required
AS
RETURN
    SELECT 1 AS is_visible
    WHERE @employee_id = TRY_CAST(SESSION_CONTEXT(N'employee_id') AS INT);
    -- Missing or invalid context grants no rows.
GO

-- STEP 2 β€” bind it to the table as a security policy
CREATE SECURITY POLICY rls.orders_filter
ADD FILTER PREDICATE rls.fn_orders_by_rep(employee_id) ON dbo.orders
WITH (STATE = ON);
GO

Now watch the same query return different rows for different reps:

-- πŸŸ₯ MSSQL
SELECT COUNT(*) AS visible FROM orders;                  --  0  (no context = no access)

EXEC sp_set_session_context @key = N'employee_id', @value = 3;
SELECT COUNT(*) AS visible FROM orders;                  -- 10  (Priya Raman's orders)

EXEC sp_set_session_context @key = N'employee_id', @value = 4;
SELECT COUNT(*) AS visible FROM orders;                  --  7  (Tom Becker's orders)

Expected output with this fail-closed predicate on fresh ShopDB:

session context rows visible in orders
(none set) 0
employee_id = 3 10
employee_id = 4 7

[!NOTE] πŸ“Œ The important part: the query never changed. SELECT COUNT(*) FROM orders is the same text every time. The engine silently adds your filter condition to every query touching that table β€” SELECT, and with a block predicate, INSERT/UPDATE/DELETE too.

Predicate type What it does
FILTER PREDICATE Silently hides rows from reads (no error, they simply are not there)
BLOCK PREDICATE Raises an error if a write would create or modify a row the user should not own

[!IMPORTANT] 🎯 When to use RLS: one application shared by many client companies (multi-tenant β€” each company sees only its own rows), sales teams where reps must not see each other’s deals, hospital records restricted by ward, any regulated data where β€œthe app filters it” is not a good enough answer for an auditor.

[!WARNING] ⚠️ Three cautions:

  1. The predicate runs on every query against that table β€” keep it trivially cheap and make sure the column it filters on is indexed, or you will slow down the entire application.
  2. sp_set_session_context must be set by trusted code, normally right after the connection is opened. If the application can be tricked into setting someone else’s ID, RLS has bought you nothing. This demo denies access when no ID is set. A database user who can choose their own session context can impersonate another rep; this pattern assumes authenticated, trusted application code owns the connection.
  3. RLS applies to everyone, including db_owner and sysadmin members. If administrators must see all rows, build that rule into the predicate function yourself β€” and always test with a real, low-privilege user before you trust it.
-- πŸŸ₯ MSSQL: inspect and disable
SELECT name, is_enabled FROM sys.security_policies;
ALTER SECURITY POLICY rls.orders_filter WITH (STATE = OFF);
DROP SECURITY POLICY rls.orders_filter;

πŸ”€ MySQL has no built-in row-level security. The standard substitute is a view that runs with its creator’s rights: create the view with WITH CHECK OPTION and SQL SECURITY DEFINER, grant users access to the view only, and revoke all access to the base table. It is weaker than RLS β€” it depends on you never granting table access β€” but it is the closest equivalent.

54.7 πŸ” Encryption

Protection πŸŸ₯ MSSQL 🟦 MySQL
In transit Force TLS (encryption of the network connection) REQUIRE SSL on the user
At rest (whole DB) Transparent Data Encryption (TDE) InnoDB tablespace encryption
Column level Always Encrypted, ENCRYPTBYKEY AES_ENCRYPT() / AES_DECRYPT()
Passwords Never encrypt β€” hash with bcrypt/Argon2 in the app Same
Data masking Dynamic Data Masking Views with masking expressions
-- 🟦 MySQL: require an encrypted connection
ALTER USER 'app_user'@'10.0.0.%' REQUIRE SSL;     -- the remote account from 54.2
-- πŸŸ₯ MSSQL: dynamic data masking β€” support sees only part of the value
ALTER TABLE customers
    ALTER COLUMN email ADD MASKED WITH (FUNCTION = 'email()');
ALTER TABLE customers
    ALTER COLUMN phone ADD MASKED WITH (FUNCTION = 'partial(0,"XXX-XXX-",4)');

CREATE USER senior_support WITHOUT LOGIN;   -- (a practice user)
GRANT UNMASK TO senior_support;             -- specific people can see the real values

[!WARNING] ⚠️ Never, ever encrypt passwords β€” hash them. Encryption is reversible; that is the whole problem. Store a salted hash β€” a one-way scramble with random extra data mixed in, made with bcrypt, scrypt, or Argon2 β€” computed in the application, never in SQL. MD5() and SHA1() are broken for this purpose and must not be used for passwords.

[!WARNING] ⚠️ Dynamic Data Masking is a display convenience, not a security boundary. A determined user with SELECT rights can work out masked values by guessing with WHERE clauses such as WHERE email LIKE 'a%'. Use real permissions for real secrets.

54.8 πŸ•΅οΈ Auditing

-- πŸŸ₯ MSSQL: who has what permission?
SELECT
    dp.name AS principal_name,
    dp.type_desc,
    p.permission_name,
    p.state_desc,
    OBJECT_NAME(p.major_id) AS object_name
FROM sys.database_permissions p
JOIN sys.database_principals dp ON dp.principal_id = p.grantee_principal_id
WHERE dp.name NOT IN ('public','dbo')
ORDER BY dp.name, object_name;

-- Role membership
SELECT r.name AS role_name, m.name AS member_name
FROM sys.database_role_members rm
JOIN sys.database_principals r ON r.principal_id = rm.role_principal_id
JOIN sys.database_principals m ON m.principal_id = rm.member_principal_id;
-- 🟦 MySQL
SHOW GRANTS FOR 'app_user'@'localhost';
SELECT * FROM mysql.user;
SELECT * FROM information_schema.user_privileges;
SELECT * FROM information_schema.schema_privileges WHERE table_schema = 'ShopDB';

54.9 βœ… The security checklist

β˜‘οΈ Item
☐ No application uses sa or root
☐ Every account follows least privilege
☐ Permissions granted to roles, never to individuals
☐ Strong password policy, rotation, and lockout enabled
☐ Connections encrypted with TLS
☐ Sensitive data encrypted at rest
☐ Passwords hashed in the app, never stored or encrypted in the DB
☐ All queries parameterized (Chapter 55)
☐ Default and sample accounts removed
☐ Database server not reachable from the public internet
☐ Auditing enabled for privileged actions
☐ Backups encrypted, and restore tested
☐ Permissions reviewed on a schedule, and whenever someone leaves

54.10 πŸ§ͺ Try it yourself

  1. Create a read-only reporting user and verify it cannot insert.
  2. Create a role granting access to products and categories only; add a user and test the boundary.
  3. Grant column-level SELECT that excludes email, then try to select it.
  4. List every permission currently granted in ShopDB.
  5. In MySQL, grant a role, connect as that user without SET DEFAULT ROLE, and observe the failure.

🧭 In practice β€” security: users, roles, and permissions

How to use it. Create a login (server level) and a user (database level), put users into roles, and grant permissions to the role rather than to people. Grant only what is needed. Expected result: each application and person can do their job and nothing more, and revoking access is one membership change.

When to use it. On every system with more than one user, and on every application β€” from the first day, because retrofitting least privilege onto a system where everything runs as the administrator is a project, not a task.

Where to use it. Production above all. Scenario: a reporting tool connects with an account that has SELECT on three views and nothing else. A compromised reporting credential then cannot read salaries, cannot write, and cannot drop anything β€” the blast radius is bounded by design rather than by luck.

When not to use it. Never let an application connect as sa, root, or a db_owner. Never share one login between services; when something is abused you need to know which one. Do not grant permissions directly to individuals β€” it becomes unauditable within months and nobody dares revoke anything.

Best practices. Grant to roles, assign roles to users, and review membership on a schedule. Use separate accounts per environment and per service. Keep credentials out of source control and out of connection strings in plain files β€” use a secret store or your platform’s managed identity. Consider column-level permissions or masked views for personal data, so that β€œread access to customers” does not automatically mean β€œread every phone number”.


55. SQL injection and how to stop it

🎚️ Level ⏱️ Time 🎯 After this chapter you can…
🟒🟑 Beginner–Intermediate 20 min Explain how SQL injection works Β· Stop it with parameters Β· Write safe dynamic SQL Β· Recognize β€œdefences” that do not work

[!NOTE] πŸ“Œ In plain words: SQL injection is when user input is treated as SQL code instead of data. It is the oldest, most common, and most damaging database vulnerability β€” and it is completely preventable.

🌍 Analogy: A form letter with a blank: β€œDear _____, your order has shipped.” If someone writes their name as β€œBob. PS: Also send everyone a refund.” and you photocopy the letter without thinking, you have just executed their instruction. Parameterization is the equivalent of putting the name in a separate field on the envelope that can never be read as part of the letter.

55.1 πŸ’€ How the attack works

// ❌ VULNERABLE application code (any language)
query = "SELECT * FROM customers WHERE email = '" + userInput + "'";

Normal input: amara.silva@example.com

SELECT * FROM customers WHERE email = 'amara.silva@example.com';   -- βœ… fine

Malicious input: ' OR '1'='1

SELECT * FROM customers WHERE email = '' OR '1'='1';
-- πŸ’€ Returns EVERY customer. The login check just passed for everyone.

Worse input: '; DROP TABLE customers; --

SELECT * FROM customers WHERE email = ''; DROP TABLE customers; --';
-- πŸ’€ The table is gone. The -- comments out the rest of the statement.

Data theft with UNION:

-- Input: ' UNION SELECT employee_id, first_name, last_name, title, department,
--          CAST(salary AS CHAR), '', '' FROM employees --
-- πŸ’€ Salaries returned through the customer search box.

[!WARNING] ⚠️ Injection is not only about SELECT. Attackers use it to read any table, modify data, escalate privileges, read files from the server, and in some configurations execute operating system commands. Every major data breach list is full of injection.

55.2 βœ… The one real fix: parameterized queries

[!NOTE] πŸ“Œ Parameters keep code and data in separate channels. The database receives the SQL structure and the values independently, so a value can never become a command β€” no matter what it contains.

// βœ… C# / .NET β€” SQL Server
using var cmd = new SqlCommand(
    "SELECT * FROM customers WHERE email = @email AND country = @country", conn);
cmd.Parameters.AddWithValue("@email", userInput);      // ← always just a value
cmd.Parameters.AddWithValue("@country", country);
# βœ… Python β€” MySQL
cursor.execute(
    "SELECT * FROM customers WHERE email = %s AND country = %s",
    (user_input, country)                               # ← a tuple of values
)

# βœ… Python β€” SQL Server (pyodbc)
cursor.execute(
    "SELECT * FROM customers WHERE email = ? AND country = ?",
    (user_input, country)
)
// βœ… Java β€” JDBC (works for both engines)
PreparedStatement ps = conn.prepareStatement(
    "SELECT * FROM customers WHERE email = ? AND country = ?");
ps.setString(1, userInput);
ps.setString(2, country);
// βœ… PHP β€” PDO
$stmt = $pdo->prepare("SELECT * FROM customers WHERE email = :email");
$stmt->execute(['email' => $userInput]);
// βœ… Node.js β€” mysql2
connection.execute(
    'SELECT * FROM customers WHERE email = ? AND country = ?',
    [userInput, country]
);

[!TIP] πŸ’‘ Now ' OR '1'='1 is simply searched for as a literal email address. No customer has that email, so zero rows come back. The attack does not fail loudly β€” it becomes meaningless, which is exactly what you want.

55.3 🧯 Safe dynamic SQL, when you genuinely need it

Sometimes the structure must be dynamic (a sortable column, a variable table name). Parameters can only stand in for values, not for column or table names β€” so you must check names against an allow-list (a fixed list of permitted names).

-- πŸŸ₯ MSSQL: sp_executesql parameterizes VALUES; QUOTENAME protects IDENTIFIERS
CREATE OR ALTER PROCEDURE usp_search_customers
    @country   NVARCHAR(60)  = NULL,
    @city      NVARCHAR(60)  = NULL,
    @sort_col  SYSNAME       = 'full_name'
AS
BEGIN
    SET NOCOUNT ON;

    -- βœ… ALLOW-LIST the column name. Never paste it in raw.
    IF @sort_col NOT IN ('full_name','city','country','signup_date')
        SET @sort_col = 'full_name';

    DECLARE @sql NVARCHAR(MAX) = N'
        SELECT customer_id, full_name, city, country, signup_date
        FROM customers
        WHERE 1 = 1
          AND (@p_country IS NULL OR country = @p_country)
          AND (@p_city    IS NULL OR city    = @p_city)
        ORDER BY ' + QUOTENAME(@sort_col) + N';';

    -- βœ… Values passed as real parameters, never concatenated
    EXEC sp_executesql @sql,
         N'@p_country NVARCHAR(60), @p_city NVARCHAR(60)',
         @p_country = @country, @p_city = @city;
END;
GO
-- 🟦 MySQL: PREPARE / EXECUTE with USING
DELIMITER $$
CREATE PROCEDURE usp_search_customers(IN p_country VARCHAR(60), IN p_sort VARCHAR(30))
BEGIN
    DECLARE v_sort VARCHAR(30);

    -- βœ… ALLOW-LIST
    SET v_sort = CASE p_sort
        WHEN 'city'        THEN 'city'
        WHEN 'country'     THEN 'country'
        WHEN 'signup_date' THEN 'signup_date'
        ELSE 'full_name'
    END;

    SET @sql = CONCAT(
        'SELECT customer_id, full_name, city, country FROM customers ',
        'WHERE (? IS NULL OR country = ?) ORDER BY ', v_sort);

    SET @c = p_country;
    PREPARE stmt FROM @sql;
    EXECUTE stmt USING @c, @c;      -- βœ… values bound, not concatenated
    DEALLOCATE PREPARE stmt;
END$$
DELIMITER ;

[!TIP] πŸ’‘ The rule: parameterize values, allow-list names. There is no third option. If you find yourself gluing a user-supplied string into SQL, stop and build the allow-list.

55.4 🚫 Defences that do NOT work

❌ β€œDefence” Why it fails
Escaping quotes yourself Misses look-alike Unicode quotes, attacks saved now and triggered later (second-order injection), and numbers (WHERE id = 1 OR 1=1 needs no quotes at all)
Blocking words like DROP Easily dodged: DrOp, DR/**/OP, encoded text, building the word letter by letter
Hiding error messages Blind injection pulls data out by asking yes/no questions and timing the answers, without any error
Client-side validation The attacker does not use your form; they send HTTP directly
Stored procedures alone A procedure that concatenates strings internally is just as vulnerable
-- ❌ πŸŸ₯ MSSQL: a stored procedure is NOT automatically safe
CREATE PROCEDURE usp_bad_search @email NVARCHAR(150)
AS
BEGIN
    EXEC('SELECT * FROM customers WHERE email = ''' + @email + '''');  -- πŸ’€ injectable
END;

55.5 πŸ›‘οΈ Defence in depth

Even with parameterization everywhere, layer your defences:

  1. βœ… Parameterize every query. Non-negotiable.
  2. βœ… Least privilege. If the app account cannot DROP, an injection cannot drop.
  3. βœ… Validate input by type and range (an ID should be an integer; reject anything else early).
  4. βœ… Generic error messages to users; detailed ones to your logs only.
  5. βœ… A web application firewall as an extra net, never as the primary control.
  6. βœ… Code review and automated code scanners flagging text glued into SQL.
  7. βœ… Penetration testing before release.
  8. βœ… Monitor for unusual query patterns and error spikes.

πŸ”Ž The rest of the application-side story is Chapter 65 β€” why parameters are also a performance feature, connection pooling, timeouts, and safe retries.

55.6 πŸ§ͺ Try it yourself

[!WARNING] ⚠️ On your own local ShopDB only. Never test injection against a system you do not own.

  1. Build a tiny script that concatenates user input into a query. Break it with ' OR '1'='1.
  2. Rewrite it with parameters and confirm the same input now returns nothing.
  3. Write a safe dynamic-sort procedure with a whitelist, then try to inject through the sort parameter.
  4. Create a least-privilege user with no DELETE rights and confirm an injected DELETE fails even if the injection succeeds syntactically.

🧭 In practice β€” SQL injection

How to use it. Parameterise every value. Build the query with placeholders and pass user input as parameters; never concatenate it into the SQL string. Use sp_executesql with parameters for dynamic SQL in SQL Server, and prepared statements in MySQL. Expected result: input is always treated as data, never as code, whatever it contains.

When to use it. Every single time a value reaches SQL from outside the database β€” a web form, an API payload, a query string, an uploaded file, another service. There is no exception where concatenation is acceptable.

Where to use it. Every application boundary. Scenario: a search box builds WHERE name = '<input>' by concatenation. Someone types ' OR 1=1 -- and receives the whole table; a more creative input drops it. Parameterising makes that input a harmless search for a literal string containing a quote.

When not to use it. There is no situation where string concatenation of user input is acceptable. The common excuses all fail: input validation and escaping are incomplete defences that get bypassed; stored procedures are not automatically safe if they concatenate internally; and an ORM is not a guarantee if you use its raw-SQL escape hatch. When an identifier (a table or column name) must be dynamic, validate it against an allow-list β€” identifiers cannot be parameterised.

Best practices. Parameterise first, then add defence in depth: least-privilege accounts so an injection cannot drop tables, error messages that do not leak schema details, and logging that does not record the payload verbatim. Parameterisation also helps performance, because the engine can reuse one cached plan instead of compiling a new one for every distinct concatenated string.


56. Backup, restore, and disaster recovery

🎚️ Level ⏱️ Time 🎯 After this chapter you can…
πŸŸ‘πŸ”΄ Intermediate–Expert 40 min Choose how much data you can afford to lose Β· Take full, differential, and log backups Β· Restore to an exact moment Β· Test that backups really work

[!NOTE] πŸ“Œ In plain words: Everything else in this guide is about making the database useful. This chapter is about making sure it still exists tomorrow. It is the most important day-to-day topic there is.

🌍 Analogy: Backing up the photos on your phone. You only discover whether you did it properly on the day the phone is lost β€” and by then it is too late to start.

[!WARNING] ⚠️ The rule that matters more than any other in this guide: a backup you have never restored is not a backup. It is a hope.

56.1 🎯 RPO and RTO β€” decide these first

Term Question it answers Example
RPO (Recovery Point Objective) How much data can we afford to lose? β€œAt most 15 minutes of transactions”
RTO (Recovery Time Objective) How long can we be down? β€œBack online within 1 hour”

[!TIP] πŸ’‘ These are business decisions, not technical ones. An RPO of 15 minutes means transaction log backups every 15 minutes. An RPO of zero means a second server updated at the very same instant (synchronous replication) and a much larger budget. Ask the business, then design the backup strategy to meet the number β€” not the other way round.

56.2 πŸŸ₯ MSSQL backup

Recovery models β€” choose deliberately:

Model Log backups Point-in-time restore Use for
SIMPLE ❌ Not possible ❌ No Dev, test, data warehouses reloadable from source
FULL βœ… Required βœ… Yes Production. Almost always this one.
BULK_LOGGED βœ… Yes ⚠️ Limited during bulk ops Temporarily, during a large bulk load
ALTER DATABASE ShopDB SET RECOVERY FULL;
-- FULL backup: everything
BACKUP DATABASE ShopDB
TO DISK = 'D:\Backups\ShopDB_Full_20260909.bak'
WITH COMPRESSION, CHECKSUM, INIT,
     NAME = 'ShopDB Full Backup';

-- DIFFERENTIAL: only what changed since the last FULL (small and fast)
BACKUP DATABASE ShopDB
TO DISK = 'D:\Backups\ShopDB_Diff_20260909_1200.bak'
WITH DIFFERENTIAL, COMPRESSION, CHECKSUM;

-- TRANSACTION LOG: every committed transaction since the last log backup
BACKUP LOG ShopDB
TO DISK = 'D:\Backups\ShopDB_Log_20260909_1215.trn'
WITH COMPRESSION, CHECKSUM;

[!TIP] πŸ’‘ WITH CHECKSUM verifies pages as they are backed up, catching corruption at backup time rather than at 3 a.m. during a restore. WITH COMPRESSION can reduce I/O, at a CPU cost; the ratio depends on the data. It is edition-dependent (SQL Server 2022 Express cannot create compressed backups), so omit COMPRESSION where unsupported. Check the edition feature matrix.

A typical schedule for a live system:

Sunday 01:00   FULL backup
Mon–Sat 01:00  DIFFERENTIAL backup
Every 15 min   TRANSACTION LOG backup

β†’ Worst-case data loss (RPO): 15 minutes
β†’ Restore path: last FULL + last DIFF + all LOGs since that DIFF

Restoring:

-- Restore the chain in order. NORECOVERY = "more files are coming, do not open the database yet".
USE master;          -- πŸ”‘ you cannot restore the database your session is using
RESTORE DATABASE ShopDB
FROM DISK = 'D:\Backups\ShopDB_Full_20260909.bak'
WITH NORECOVERY, REPLACE;

RESTORE DATABASE ShopDB
FROM DISK = 'D:\Backups\ShopDB_Diff_20260909_1200.bak'
WITH NORECOVERY;

RESTORE LOG ShopDB
FROM DISK = 'D:\Backups\ShopDB_Log_20260909_1215.trn'
WITH RECOVERY;                       -- πŸ”‘ the LAST file uses RECOVERY
-- ⭐ Point-in-time restore: recover to the moment BEFORE the bad UPDATE.
--    An alternative to the chain above: the same FULL and DIFF, then the log only up to STOPAT.
USE master;
RESTORE DATABASE ShopDB
FROM DISK = 'D:\Backups\ShopDB_Full_20260909.bak'
WITH NORECOVERY, REPLACE;

RESTORE DATABASE ShopDB
FROM DISK = 'D:\Backups\ShopDB_Diff_20260909_1200.bak'
WITH NORECOVERY;

RESTORE LOG ShopDB
FROM DISK = 'D:\Backups\ShopDB_Log_20260909_1215.trn'
WITH STOPAT = '2026-09-09 12:07:00', RECOVERY;

[!TIP] πŸ’‘ STOPAT is the feature that saves you from a bad DELETE. Someone deletes 400,000 rows at 12:07. You restore to a copy of the database as it was at 12:06:59, then copy the missing rows back into the live database. Practise this before you need it.

-- Verify a backup file is readable and complete
RESTORE VERIFYONLY FROM DISK = 'D:\Backups\ShopDB_Full_20260909.bak';
RESTORE HEADERONLY FROM DISK = 'D:\Backups\ShopDB_Full_20260909.bak';

-- Backup history
SELECT database_name, backup_start_date, backup_finish_date, type, backup_size
FROM msdb.dbo.backupset
WHERE database_name = 'ShopDB'
ORDER BY backup_start_date DESC;

56.3 🟦 MySQL backup

Logical backup β€” mysqldump writes out the SQL statements that rebuild your data (portable, human-readable, slower):

# One database, consistent, with the binary-log position recorded
mysqldump -u root -p \
  --single-transaction \
  --routines --triggers --events \
  --source-data=2 \
  ShopDB > ShopDB_20260909.sql

# All databases
mysqldump -u root -p --all-databases --single-transaction > all_20260909.sql

# Compressed
mysqldump -u root -p --single-transaction --routines --triggers --events --source-data=2 ShopDB | gzip > ShopDB_20260909.sql.gz

[!TIP] πŸ’‘ --single-transaction is essential for InnoDB. It takes the dump inside a consistent snapshot without locking the tables, so your application keeps running. Without it, mysqldump locks tables and your site stalls for the duration.

# Restore
mysql -u root -p ShopDB < ShopDB_20260909.sql
gunzip < ShopDB_20260909.sql.gz | mysql -u root -p ShopDB

Physical backup β€” Percona XtraBackup copies the raw data files (fast, does not block users, for large databases):

xtrabackup --backup --target-dir=/backups/full --user=root --password=***
xtrabackup --prepare --target-dir=/backups/full
xtrabackup --copy-back --target-dir=/backups/full

Point-in-time recovery using the binary log:

-- Enable binary logging (in my.cnf)
-- log_bin = /var/log/mysql/mysql-bin.log
-- binlog_format = ROW
-- binlog_expire_logs_seconds = 1209600      (14 days; the old expire_logs_days was removed in MySQL 8.4)

SHOW BINARY LOGS;
SHOW BINLOG EVENTS LIMIT 20;       -- the first log; add IN 'mysql-bin.000042' for a specific file from the list
# 1. Restore the last full dump
mysql -u root -p ShopDB < ShopDB_20260909.sql

# 2. TEMPLATE: replace this file/position with the coordinates recorded in the dump.
# Include every subsequent required binlog in order; stop at the chosen recovery event.
mysqlbinlog --start-position=RECORDED_POSITION \
            --stop-datetime="2026-09-09 12:06:59" \
            /var/log/mysql/mysql-bin.000042 | mysql -u root -p

[!WARNING] ⚠️ Without log_bin enabled, point-in-time recovery is impossible. Your only option is restoring last night’s dump and losing everything since. Check that binary logging is on with SHOW VARIABLES LIKE 'log_bin'; β€” it is the MySQL equivalent of the transaction log. It has been on by default since MySQL 8.0, but it is often switched off to save disk space.

Recovery preconditions: use the exact file and position recorded by --source-data=2, not an assumed backup start time. Archive the complete required log chain and test replay into an isolated restore instance. See MySQL point-in-time recovery. Physical --copy-back also requires a stopped server, an appropriate empty data directory, compatible tooling and restored ownership; the three XtraBackup commands above are an outline, not a complete restore runbook.

56.4 🌐 High availability

Technology πŸŸ₯ MSSQL 🟦 MySQL Protects against
Replication Transactional/merge replication Asynchronous / semi-synchronous replication Spreading read and report traffic across servers
Sync replicas Always On Availability Groups Group Replication / InnoDB Cluster Server failure with zero data loss
Clustering Failover Cluster Instances InnoDB Cluster + MySQL Router Hardware failure
Log shipping Log shipping Delayed replica A standby copy kept a little behind the live server
Cloud managed Azure SQL, Amazon RDS Amazon RDS, Aurora, Google Cloud SQL Most of the above, run for you

[!TIP] πŸ’‘ A replica is not a backup. Replication faithfully copies your mistakes: DROP TABLE customers replicates in milliseconds. A delayed replica (MySQL SOURCE_DELAY = 3600) gives you a one-hour window to catch a disaster before it reaches the copy β€” a genuinely useful safety net alongside real backups.

56.5 🚨 The disaster recovery plan

[!NOTE] πŸ“Œ A backup strategy is not a DR (disaster recovery) plan. A DR plan is a written document that a tired person can follow at 3 a.m.

β˜‘οΈ Element
☐ RPO and RTO agreed with the business, in writing
☐ Backups automated and monitored (alert on failure AND on silence)
☐ Backups stored off the database server
☐ Backups stored off-site (3-2-1 rule: 3 copies, 2 media types, 1 off-site)
☐ Backups encrypted
☐ Restores tested on a schedule β€” monthly at minimum
☐ Restore duration measured and known to meet the RTO
☐ Step-by-step instructions (a runbook) written, with commands ready to paste
☐ Contact list and escalation path documented
☐ Someone other than the author has successfully followed the runbook

[!WARNING] ⚠️ The three ways backup strategies fail in the real world:

  1. The backup job silently stopped weeks ago. Nobody monitored it. Alert on the absence of a successful backup, not just on errors.
  2. The backups were on the same server that died. Or the same shared storage system (SAN). Or the same datacentre.
  3. Nobody ever tried a restore. The files were corrupt, or incomplete, or the restore took 14 hours against a 1-hour RTO.

56.6 πŸ§ͺ Try it yourself

  1. Take a full backup of ShopDB and restore it as ShopDB_Restored. Time it.
  2. In MSSQL, set FULL recovery, take a full backup, delete some rows, take a log backup, and restore to a point in time just before the delete.
  3. In MySQL, take a mysqldump with --single-transaction, drop a table, and restore.
  4. Write a one-page restore runbook for ShopDB, then hand it to someone else and watch them follow it.

🧭 In practice β€” backup, restore, and disaster recovery

How to use it. Take full backups on a schedule, differential backups between them, and β€” in SQL Server’s full recovery model β€” transaction log backups frequently enough to bound your possible data loss. Restore by applying full, then differential, then logs in order. Expected result: a documented, rehearsed path from β€œthe server is gone” to β€œwe are running again”.

When to use it. Before anything else in production, and before every schema change or bulk correction you make by hand.

Where to use it. Production and any system holding data you cannot recreate. Scenario: someone runs an UPDATE without a WHERE at 14:05. With log backups and point-in-time restore you recover the database to 14:04. Without them, you restore last night’s full backup and lose the whole day.

When not to use it. An untested backup is not a backup β€” it is an assumption. Do not store backups only on the same server or the same disk as the database; a hardware failure or ransomware takes both. Do not leave a SQL Server database in the full recovery model without taking log backups: the log grows until the disk fills and the database stops accepting writes, which is a self-inflicted outage that happens constantly.

Best practices. Decide your RPO (how much data you can afford to lose) and RTO (how long you can afford to be down) explicitly β€” they determine the backup schedule, not the other way round. Then rehearse a restore, on a schedule, onto different hardware. The restore is the thing you actually need; the backup is only the means. Keep at least one copy off-site and one offline.


57. Monitoring and maintenance

🎚️ Level ⏱️ Time 🎯 After this chapter you can…
πŸ”΄ Expert 30 min Know what to watch on a live database Β· Find what the server is waiting on Β· Schedule routine care jobs Β· Explore your database with catalog queries

[!NOTE] πŸ“Œ In plain words: A database is not β€œdone” when it goes live. It needs watching, tuning, and routine care β€” like a car needs servicing.

🌍 Analogy: The dashboard of that car. Warning lights (monitoring) tell you something is wrong before the engine fails, and the service schedule (maintenance) stops most of those lights coming on at all.

57.1 πŸ“Š What to monitor

Category Metric Alert when
Availability Can we connect? Any failure
Space Free disk, data/log file growth Under 20% free
Performance Slow queries, wait statistics, CPU, memory cache hit rate Well above your normal levels, for more than a few minutes
Blocking Longest blocking chain, deadlock count Blocking over 30 s; deadlocks rising
Backups Last successful backup time No success in the expected window
Replication Replica lag Lag over your RPO
Errors Serious errors in the error log (severity 17 or higher) Immediately
Corruption Consistency check results Any error at all

57.2 πŸ” Essential monitoring queries

-- πŸŸ₯ MSSQL: what is running right now
SELECT
    r.session_id, r.status, r.command, r.wait_type, r.blocking_session_id,
    r.cpu_time, r.total_elapsed_time, r.reads, r.writes,
    SUBSTRING(t.text, (r.statement_start_offset/2)+1, 2000) AS query_text
FROM sys.dm_exec_requests r
CROSS APPLY sys.dm_exec_sql_text(r.sql_handle) t
WHERE r.session_id <> @@SPID
ORDER BY r.total_elapsed_time DESC;

-- Where is the server spending its wait time? (the #1 health check)
SELECT TOP 15
    wait_type,
    wait_time_ms / 1000.0 AS wait_seconds,
    waiting_tasks_count,
    wait_time_ms / NULLIF(waiting_tasks_count,0) AS avg_ms_per_wait
FROM sys.dm_os_wait_stats
WHERE wait_type NOT IN ('CLR_SEMAPHORE','SLEEP_TASK','BROKER_TASK_STOP',
    'XE_TIMER_EVENT','LAZYWRITER_SLEEP','SQLTRACE_BUFFER_FLUSH','WAITFOR',
    'REQUEST_FOR_DEADLOCK_SEARCH','CHECKPOINT_QUEUE','DIRTY_PAGE_POLL',
    'HADR_FILESTREAM_IOMGR_IOCOMPLETION','SP_SERVER_DIAGNOSTICS_SLEEP')
ORDER BY wait_time_ms DESC;

-- Database and file sizes
SELECT
    DB_NAME(database_id) AS db_name,
    name AS file_name, type_desc,
    CAST(size AS BIGINT) * 8 / 1024 AS size_mb,
    CASE WHEN max_size = -1 THEN 'Unlimited'
         ELSE CAST(CAST(max_size AS BIGINT) * 8 / 1024 AS VARCHAR(20)) END AS max_mb   -- BIGINT: a 2 TB log limit overflows INT
FROM sys.master_files ORDER BY db_name, type_desc;

Common MSSQL wait types and what they mean:

Wait type Meaning Usually means
PAGEIOLATCH_* Waiting to read a page from disk Slow storage or not enough memory
CXPACKET/CXCONSUMER Parts of a query running on several CPU cores wait for each other Often harmless; check the MAXDOP setting (max CPU cores per query)
LCK_M_* Waiting for a lock Blocking β€” find the session at the front of the queue
WRITELOG Waiting to write the transaction log Slow log disk; move the log to faster storage
SOS_SCHEDULER_YIELD CPU pressure Not enough CPU, or bad plans burning it
RESOURCE_SEMAPHORE Waiting for memory to be reserved for the query Bad estimates asking for too much memory
-- 🟦 MySQL: essential health checks
SELECT * FROM performance_schema.processlist;
SHOW ENGINE INNODB STATUS;
SHOW GLOBAL STATUS LIKE 'Threads_connected';
SHOW GLOBAL STATUS LIKE 'Slow_queries';
SHOW GLOBAL STATUS LIKE 'Innodb_buffer_pool_read%';

-- Buffer pool hit ratio (how often the data was already in memory) β€” should be well above 99%
SELECT
    ROUND(100 * (1 - (
        (SELECT VARIABLE_VALUE FROM performance_schema.global_status
         WHERE VARIABLE_NAME = 'Innodb_buffer_pool_reads') /
        (SELECT VARIABLE_VALUE FROM performance_schema.global_status
         WHERE VARIABLE_NAME = 'Innodb_buffer_pool_read_requests')
    )), 2) AS buffer_pool_hit_pct;

-- The sys schema is a goldmine
SELECT * FROM sys.statements_with_runtimes_in_95th_percentile LIMIT 10;
SELECT * FROM sys.statements_with_full_table_scans LIMIT 10;
SELECT * FROM sys.schema_unused_indexes;
SELECT * FROM sys.io_global_by_file_by_bytes LIMIT 10;
SELECT * FROM sys.host_summary;

-- Table sizes
SELECT
    table_name,
    ROUND((data_length + index_length) / 1024 / 1024, 2) AS total_mb,
    ROUND(data_length / 1024 / 1024, 2)  AS data_mb,
    ROUND(index_length / 1024 / 1024, 2) AS index_mb,
    table_rows
FROM information_schema.tables
WHERE table_schema = 'ShopDB'
ORDER BY (data_length + index_length) DESC;

57.3 🧰 Routine maintenance tasks

Task Frequency πŸŸ₯ MSSQL 🟦 MySQL
Full backup Daily/weekly BACKUP DATABASE mysqldump / XtraBackup
Log backup Every 5–30 min BACKUP LOG Binary log retention
Consistency check Weekly DBCC CHECKDB CHECK TABLE
Update statistics Weekly, or after bulk loads UPDATE STATISTICS ANALYZE TABLE
Index maintenance Weekly/monthly ALTER INDEX REORGANIZE/REBUILD OPTIMIZE TABLE
Purge old data Monthly Partition switch or batched delete DROP PARTITION
Review slow queries Weekly Query Store / DMVs Slow query log / sys schema
Review permissions Quarterly, and whenever someone leaves Catalog views SHOW GRANTS
Test a restore Monthly Restore to a test server Restore to a test server
-- πŸŸ₯ MSSQL: the corruption check you must not skip
DBCC CHECKDB('ShopDB') WITH NO_INFOMSGS, ALL_ERRORMSGS;

[!WARNING] ⚠️ DBCC CHECKDB is the single most important maintenance task in SQL Server. Storage corruption is silent β€” it sits in a rarely-read page for months, then surfaces during a restore, at which point every backup you hold may already contain it. Run it weekly, and alert on any error.

57.4 ⏰ Scheduling jobs

-- πŸŸ₯ MSSQL: SQL Server Agent
EXEC msdb.dbo.sp_add_job @job_name = N'ShopDB Nightly Maintenance';

EXEC msdb.dbo.sp_add_jobstep
    @job_name = N'ShopDB Nightly Maintenance',
    @step_name = N'Update Statistics',
    @subsystem = N'TSQL',
    @database_name = N'ShopDB',
    @command = N'EXEC sp_updatestats;';

EXEC msdb.dbo.sp_add_schedule
    @schedule_name = N'Nightly 2am',
    @freq_type = 4, @freq_interval = 1,
    @active_start_time = 20000;

EXEC msdb.dbo.sp_attach_schedule
    @job_name = N'ShopDB Nightly Maintenance', @schedule_name = N'Nightly 2am';

EXEC msdb.dbo.sp_add_jobserver @job_name = N'ShopDB Nightly Maintenance';
-- 🟦 MySQL: the Event Scheduler
SET GLOBAL event_scheduler = ON;

CREATE EVENT ev_nightly_analyze
ON SCHEDULE EVERY 1 DAY STARTS '2026-09-10 02:00:00'
DO
    ANALYZE TABLE ShopDB.orders, ShopDB.order_items, ShopDB.products;

CREATE EVENT ev_purge_old_logs
ON SCHEDULE EVERY 1 DAY STARTS '2026-09-10 03:00:00'
DO
    DELETE FROM ShopDB.audit_log WHERE logged_at < UTC_TIMESTAMP() - INTERVAL 90 DAY LIMIT 50000;   -- audit_log: see 65.5

SHOW EVENTS FROM ShopDB;

[!TIP] πŸ’‘ On Linux, many teams prefer cron (Linux’s built-in task scheduler) over the MySQL Event Scheduler β€” it is easier to monitor, log, and alert on, and it survives a database restart cleanly.

57.5 πŸ—‚οΈ The system catalogs β€” knowing your own database

The system catalog is a set of built-in views that describe the database itself β€” its tables, columns, indexes, and keys. You query it with ordinary SELECT statements.

-- 🟦 MySQL: TABLE_SCHEMA is the database name.
-- πŸŸ₯ SQL Server: use TABLE_CATALOG = 'ShopDB' AND TABLE_SCHEMA = 'dbo'
-- in each WHERE clause below instead; schema and database are separate concepts.
SELECT table_name, table_type FROM information_schema.tables WHERE table_schema = 'ShopDB';

SELECT table_name, column_name, data_type, is_nullable, column_default
FROM information_schema.columns
WHERE table_schema = 'ShopDB' AND table_name = 'orders'
ORDER BY ordinal_position;

SELECT table_name, constraint_name, constraint_type
FROM information_schema.table_constraints WHERE table_schema = 'ShopDB';

Finding every foreign key relationship β€” this one is not portable, because MySQL adds non-standard columns to key_column_usage that SQL Server does not have:

-- βœ… MySQL only: referenced_* columns are a MySQL extension
SELECT
    kcu.table_name             AS child_table,
    kcu.column_name            AS child_column,
    kcu.referenced_table_name  AS parent_table,
    kcu.referenced_column_name AS parent_column
FROM information_schema.key_column_usage kcu
WHERE kcu.table_schema = 'ShopDB' AND kcu.referenced_table_name IS NOT NULL;
-- βœ… MSSQL: use the sys.* catalog views instead
SELECT
    OBJECT_NAME(fk.parent_object_id)                             AS child_table,
    COL_NAME(fkc.parent_object_id,     fkc.parent_column_id)     AS child_column,
    OBJECT_NAME(fk.referenced_object_id)                         AS parent_table,
    COL_NAME(fkc.referenced_object_id, fkc.referenced_column_id) AS parent_column,
    fk.name                                                      AS constraint_name
FROM sys.foreign_keys fk
JOIN sys.foreign_key_columns fkc ON fkc.constraint_object_id = fk.object_id
ORDER BY child_table, child_column;

Result on ShopDB (8 foreign keys):

child_table child_column parent_table parent_column
employees manager_id employees employee_id
order_items order_id orders order_id
order_items product_id products product_id
orders customer_id customers customer_id
orders employee_id employees employee_id
payments order_id orders order_id
products category_id categories category_id
products supplier_id suppliers supplier_id

[!CAUTION] πŸ› Common mistake: assuming INFORMATION_SCHEMA is fully portable because it is β€œthe ANSI standard”. The core columns are, but every vendor extends it. referenced_table_name exists only in MySQL β€” in SQL Server the same query fails with β€œInvalid column name β€˜referenced_table_nameβ€™β€œ. For foreign keys specifically, use INFORMATION_SCHEMA.REFERENTIAL_CONSTRAINTS for portable code, or the native catalog views for anything detailed.

-- πŸŸ₯ MSSQL: the richer sys.* catalog views
SELECT * FROM sys.tables;
SELECT * FROM sys.columns WHERE object_id = OBJECT_ID('orders');
SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('orders');
SELECT * FROM sys.foreign_keys;

-- Find a column anywhere in the database
SELECT OBJECT_NAME(object_id) AS table_name, name AS column_name
FROM sys.columns WHERE name LIKE '%email%';
-- 🟦 MySQL: SHOW commands
SHOW TABLES;
SHOW CREATE TABLE orders;
SHOW COLUMNS FROM orders;
SHOW INDEX FROM orders;
SHOW TABLE STATUS FROM ShopDB;
SHOW VARIABLES LIKE 'innodb%';

[!TIP] πŸ’‘ Learn to query the catalog. β€œWhich tables have a column called customer_id?”, β€œWhich tables have no primary key?”, β€œWhich foreign keys have no index?” β€” all answerable in one query, and all far faster than clicking through a graphical tool.

-- βœ… Genuinely useful: find tables with no primary key
-- 🟦 MySQL
SELECT t.table_name
FROM information_schema.tables t
LEFT JOIN information_schema.table_constraints tc
       ON tc.table_schema = t.table_schema
      AND tc.table_name = t.table_name
      AND tc.constraint_type = 'PRIMARY KEY'
WHERE t.table_schema = 'ShopDB'
  AND t.table_type = 'BASE TABLE'
  AND tc.constraint_name IS NULL;

57.6 πŸ§ͺ Try it yourself

  1. Find the top 5 wait types on your server and look up what each one means.
  2. List every table in ShopDB with its size, largest first.
  3. Find any table without a primary key.
  4. Find every foreign key column that has no index (a genuine performance audit).
  5. Schedule a nightly statistics update job in your engine.

🧭 In practice β€” monitoring and maintenance

How to use it. Watch a small number of things continuously: slow queries, blocking and deadlocks, index fragmentation, free disk and log space, backup success, and error logs. Use dynamic management views (SQL Server) or performance_schema and the slow query log (MySQL). Expected result: you hear about a problem from your monitoring rather than from a user.

When to use it. From the day a system goes live. Maintenance that is not scheduled does not happen, and the first time anyone looks at index fragmentation is usually during an incident.

Where to use it. Production operations. Scenario: a weekly job reports the ten slowest queries and any index above 30% fragmentation. Acting on that list for an hour a week prevents most of the emergencies that would otherwise arrive at 2 a.m.

When not to use it. Do not rebuild every index every night out of habit β€” it is expensive, it generates enormous log volume, and on many workloads it achieves nothing. Reorganise moderately fragmented indexes and rebuild only badly fragmented ones. Do not alert on everything either; an alert that fires daily is an alert everyone has already learned to ignore.

Best practices. Automate the boring parts β€” backup verification, statistics updates, index maintenance, log-space checks β€” and alert on outcomes (a backup did not run, a query exceeded its budget) rather than on raw counters. Keep a short runbook for the failures you have actually had. On SQL Server, the community-standard maintenance scripts are a far better starting point than hand-rolled jobs.


Part index Prerequisites Previous Next Full course