Auditing Databases: Tracking Activity and Ensuring Compliance

UPI Study › Courses › Database Programming › Free lessons › Lesson 12.7 Free with a free account

Auditing Databases: Tracking Activity and Ensuring Compliance

Database Programming · Chapter 12: Database Security and AuditingSection 12.7 · lesson 76 of 7611 min · free with a free account

← Encrypting Database Data: Methods and Applications

A free account plays all of Chapter 1 and 3 more lessons of Database Programming. Create a free account →

Earn 3 college credits for Database ProgrammingRecommended for credit by NCCRS · Computer Science 381 · self-paced · one payment, lifetime access

In this lesson

Record who changed what with triggers, server audits and history tables.

  • List the fields an audit trail needs to answer accountability questions
  • Build a trigger that records old and new values and explain its limits
  • Compare MySQL Enterprise Audit, SQL Server Audit, change tracking and temporal tables
  • Relate audit logging and retention to GDPR, HIPAA, PCI DSS and SOX

Free study notes

Get this lesson's notes by email

The key points and 4 practice questions with answers, in your inbox. One email, free.

One email. Unsubscribe in one click.

Transcript

Everything said in the video, section by section (1,277 words). Read along, or search it.

Opening Scenario

Who Changed a Customer's Points

Maya Rao owns fictional Lantern Books. A customer's points have changed, and she asks Amina Diallo, the database administrator, who did it. The current row answers only what is stored now. How can the team preserve evidence of the action, including its identity and outcome? We will build a small change-history demonstration, then identify the questions that require a protected server audit instead.

Audit Trail Basics

Who, What, When, Where and Outcome

An audit trail is a protected record of activity. An audit log is the file or table holding that evidence. Record who acted, what action was attempted, and which object was involved. Also capture when, where the request originated, and whether it succeeded. An error log records problems. A replication or recovery log records changes for another purpose; neither automatically supplies a complete accountability trail. Choose the events and fields from the questions you need to answer. Logging everything can increase overhead, expose secrets, and overwhelm reviewers.

Sandbox Setup

A Customer Subset and an Audit Table

Our disposable customer subset keeps Dara's sixty points and Ben's eighty-five. An audit table will hold the customer identifier, before and after values, actor label, and timestamp. Run this setup. The current timestamp will be generated by the database; we will not invent a clock value for the display. SQLite has no server login identity. This local demonstration uses an explicitly illustrative actor label, so it cannot establish who authenticated.

Audit Trigger

An After-Update Trigger on Points

A trigger runs automatically in response to a database action. This after-update trigger inserts history when the points value actually changes. Old refers to the earlier row; new refers to the replacement. The is-not comparison is null-safe in SQLite, unlike a plain inequality comparison. Run the trigger definition. It installs the behavior, without changing a customer's points yet. Demo actor is a teaching label, not verified identity. Production evidence must obtain identity from a trusted connection or application mechanism.

Worked Example

One Update, One History Row

Now update Dara's points to one hundred ten. The application issues only the customer update; the trigger supplies the history insertion. Run it, then query the audit table. Both actions execute through the actual SQLite shell. The row records customer four, sixty before, one hundred ten after, and our illustrative actor label. A generated timestamp is stored too. That gives useful change history. For stronger accountability, it still needs restricted modification rights and a trusted identity source.

Trigger Limits

Reads Leave No Trace in the Table

A read raises a different question. Does querying Dara's row add evidence to an update-only trigger table? Run this select, followed by the history count. The first result reads customer data, without changing it. Dara still has one hundred ten points, and the audit count remains one. An update trigger cannot record a plain read. MySQL and SQL Server truncate also bypass their delete triggers. MySQL foreign-key cascade actions have additional trigger gaps, and powerful users may disable or remove the mechanism.

Quick Check

An Update That Changes Nothing

A separate request assigns Dara's points to their existing value. The audit table already contains one committed entry. What count will this script return? Pause, and decide. Only the preexisting audit entry remains: one. The update event occurs, but equal points make the trigger skip its insertion. Run it to confirm the entry remains alone. Adding an entry assumes every update changes a value; removing all entries forgets the committed history.

Transactions

Rolled-Back Changes Lose Their History

A trigger's history write participates in the transaction. This attempt changes the points and then rolls the transaction back. Run the script. Both the customer change and its history insertion are undone together. The result is one hundred ten points and one committed audit row. This table does not preserve an independent record of that rolled-back attempt. For attempted actions, failures, and reads, choose an audit facility designed to capture those events, rather than assuming a row-history trigger sees everything.

Server Audit Tools

MySQL Enterprise Audit and SQL Server Audit

MySQL Enterprise Audit, which comes only with the paid MySQL Enterprise Edition, uses its audit-log plugin with filtering rules. Confirm the edition, output configuration, encryption, and events selected for the deployment. The general query log records client connections and received statements. It is broad and sensitive; direct client updates still appear when binary logging uses row format. Row changes applied on a replica are different: they are not received SQL statements. Do not confuse that limitation with ordinary client query logging. SQL Server Audit separates the destination from event selection. A server audit names its target; server and database specifications choose the actions recorded. Enable the audit and specification, then inspect captured events. Reading the audit file through its system function verifies that the intended event actually arrived.

Recording Identity

Per-Row and Per-Statement Triggers

For MySQL row triggers, old and new are available per row. User identifies the connected account; current user inside a trigger identifies its definer. SQL Server triggers run per statement. Join inserted and deleted rowsets by the key, so an update affecting several customers records every affected row. Original login identifies the initial SQL Server login. A pooled application login still identifies the application account, so end-user attribution needs additional trusted context. Protect audit configuration as well as stored records. An administrator able to change the rules can create a gap, before anyone reviews the file.

Row History

Change Tracking and Temporal Tables

Change tracking identifies changed keys and operations for synchronization. It does not keep the old values, and consumers must respect its retention window. System-versioned temporal tables retain previous row versions with validity periods. An as-of query can reconstruct retained historical state, without automatically identifying the actor. SQL Server provides both features. MySQL needs other designs, such as triggers or replication-based capture, for similar requirements. Combine tools by question: activity auditing establishes actions and identities, while row history establishes earlier values. Neither label guarantees every needed field.

Compliance

GDPR, HIPAA, PCI DSS and SOX

Compliance means showing that applicable obligations are met. For GDPR, risk-appropriate security includes confidentiality, integrity, availability, and resilience. Document personal data breaches. Notify the authority without undue delay, where feasible within seventy-two hours, unless the breach is unlikely to risk people's rights and freedoms. HIPAA security rules apply to regulated entities handling electronic protected health information. They require mechanisms that record and examine system activity. PCI DSS requires audit logging for in-scope systems. Version 4.0.1 keeps at least twelve months, with the latest three immediately available. SOX internal-control assessment concerns covered financial reporting. Access controls, change approvals, and reliable evidence support that assessment.

Retention

How Long Audit Evidence Stays Available

Retention defines how long evidence remains available. HIPAA's six-year rule concerns required security documentation; the SEC's seven-year rule concerns covered auditors' records. Neither automatically means every database log has that same lifetime. Translate applicable obligations into an approved retention policy for each record category. Restrict readers and writers, separate review duties, and send protected copies elsewhere. Review events and alert on unusual activity; an unread trail detects nothing. Rotate files deliberately, with capacity monitoring and recoverable archives. SQL Server audit failure policies include continue, fail operation, and shutdown, with different evidence and availability consequences.

Final Check

A Multirow Update Adds Two Entries

A fresh update adds five points to both customers. Predict the history count queried before the rollback. There is already one committed audit row. Pause, and decide. Three recorded changes. The earlier committed entry remains, and this statement changes both Dara and Ben, adding two temporary entries. Run it to confirm the count. The final rollback removes the new changes, leaving the original committed history intact. Two forgets the existing entry. One overlooks that a row trigger runs for each qualifying changed row, even in a multirow statement.

Key Takeaways

Trusted Evidence, Not Just Old Values

Maya's question needs trusted activity evidence as well as old and new values. A trigger alone supplies only part of that answer. Choose audit events and history tools by the questions they can actually answer. Protect and review records, and retain them under a policy that reflects the applicable obligations. That completes Database Programming. Carry the same discipline into your own systems: define the data, test the queries, protect access, and preserve evidence.

About Database Programming at UPI Study

Database Programming (Computer Science 381) is a self-paced online course of 76 video lessons in 12 chapters, from database applications, SQL setup, schema planning and normalization to keys and constraints, data types, filtering and sorting, joins, subqueries, views, indexes, ROLLUP and PIVOT, regular expressions and database security. It carries a NCCRS credit recommendation for 3 semester credits.

Every lesson transcript is free on pages like this one, and the videos are free with a free UPI Study account. Enrolling adds a practice quiz after each lesson, the graded work and final exam that earn the credit, lifetime access, and an official transcript on completion. UPI Study has helped over 130,000 students with college credits. ACE and NCCRS have over 2,100 cooperating colleges that will consider accepting credits; the final decision is with the universities.

Compare: Database Fundamentals vs Database Programming

Why take it here

Why students take Database Programming with UPI Study

Write the SQL behind every appDatabase Programming teaches SQL in MySQL and SQL Server side by side: designing and normalizing tables, keys and constraints, data types, inserting, updating and deleting rows, filtering, grouping, joins, subqueries, views, indexes, transactions, and protecting data from SQL injection. It suits computer science and information technology degrees.
Credit at a fraction of the priceThe same 3 credits can cost $750 or more at a US college. Here it is one payment, self-paced, with lifetime access.
Finish your degree soonerTransfer credits reduce the courses you still owe, so you can graduate earlier or lighten a heavy semester.
Strengthen an applicationA completed college-level course on an official transcript shows admissions and scholarship committees you can do the work.
Study on your own scheduleNo start dates, no deadlines. Watch the lessons, practice, and take the final when you are ready.
130,000+students helped with college creditsACE and NCCRS have over 2,100 cooperating colleges that will consider accepting credits; the final decision is with the universities.

Where the credit goes

Universities that work with NCCRS

Database Programming carries a NCCRS credit recommendation. These universities work with NCCRS; some are UPI Study's signed partners. ACE and NCCRS have over 2,100 cooperating colleges that will consider accepting credits; the final decision is with the universities.

Find my college → Not listed? Ask Athena in the corner of this page, or book a 15-minute call.

FAQ

Questions students ask us

About Auditing Databases: Tracking Activity and Ensuring Compliance

How do you create an audit trigger in SQL?
Create an AFTER UPDATE trigger that copies the old and new values into a history table. In SQLite: CREATE TRIGGER trg_points AFTER UPDATE OF points ON customers WHEN OLD.points IS NOT NEW.points BEGIN INSERT INTO points_audit (customer_id, old_points, new_points) VALUES (OLD.customer_id, OLD.points, NEW.points); END; The WHEN clause skips updates that leave the value unchanged, and IS NOT compares NULL safely. Record the actor from a trusted identity source.
What can't an audit trigger record?
An update trigger records only the changes it fires on, so it misses plain SELECT reads, attempts that fail or roll back, and TRUNCATE, which bypasses delete triggers in MySQL and SQL Server. Its history insert belongs to the same transaction, so a rollback removes it too, and powerful users can disable or drop the trigger. For reads, failures and login identity, use a server facility such as SQL Server Audit or, on MySQL Enterprise Edition, MySQL Enterprise Audit.
What is the difference between change tracking and temporal tables in SQL Server?
Change tracking records which rows changed and the type of operation, mainly for synchronization, but it does not keep the old values. System-versioned temporal tables keep previous row versions with validity periods, so a FOR SYSTEM_TIME AS OF query can show the data at an earlier time. Neither feature by itself records who made the change, so actor identity still needs an audit facility or trusted application context.
How long must audit logs be kept under PCI DSS?
PCI DSS version 4.0.1 requires keeping audit log history for at least 12 months, with at least the most recent three months immediately available for analysis. Other rules work differently: HIPAA's six-year retention requirement applies to required security documentation, and neither figure automatically sets the lifetime of every database log. Translate each applicable obligation into an approved retention policy for each category of records, and protect and review the logs you keep.

About the Database Programming course

How many college credits is Database Programming?
Database Programming (Computer Science 381) carries a NCCRS credit recommendation for 3 semester credits. ACE and NCCRS have over 2,100 cooperating colleges that will consider accepting credits; the final decision is with the universities.
How much does Database Programming cost and what is included?
$250, paid once, with lifetime access: all 76 video lessons, a practice quiz after each, the graded work and final exam, and an official transcript when you finish. Students who want several courses choose UPI Study PRO instead.
Which universities accept UPI Study credits?
UPI Study has signed partner agreements with universities such as Thomas Edison State University, University of the People and Charter Oak State College, and works with universities such as Penn State, SNHU and SUNY. ACE and NCCRS have over 2,100 cooperating colleges that will consider accepting credits; the final decision is with the universities. Use "Find my college" on this page to check yours.
How long does Database Programming take?
It is self-paced with no deadlines. The 76 lessons total about 11 hours of video; most students add reading and practice time and finish in a few weeks to a few months, on their own schedule.
How are the exams done?
Quizzes and assignments are online in the course. The final exam is taken online with proctoring; a person on the UPI Study team checks assignments, usually within two days.
How do my credits reach my college?
When the course shows 100% complete, request the official transcript from your dashboard. It is sent to the college you name, and you can send it to more than one. Check your college first with "Find my college" on this page, or ask Athena.

Ready for the full course? Earn 3 credits in Database Programming.

76 video lessons, a quiz after each one, and the graded work that earns the credit. Recommended for credit by NCCRS.

Updated

Database Programming
3 credits · NCCRS
Enroll →