Securing Databases with SQL: Techniques and Examples

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

Securing Databases with SQL: Techniques and Examples

Database Programming · Chapter 12: Database Security and AuditingSection 12.2 · lesson 71 of 769 min · free with a free account

← Managing Database Security: Key Practices and ToolsNext lesson: How SQL Injection Attacks Exploit Vulnerable Queries — Patterns and Real-World Examples →

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

Control database access with GRANT, REVOKE, roles, views and procedures.

  • Write GRANT and REVOKE statements at table, database and column scope
  • Use roles in MySQL and SQL Server, including MySQL role activation
  • Explain how SQL Server DENY differs from REVOKE
  • Limit access through views and stored procedures instead of base tables

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,122 words). Read along, or search it.

Opening Scenario

A Lookup Account That Can Do Too Much

Sofia Alvarez, a sales associate at fictional Lantern Books, needs to look up customer names and cities. Amina Diallo, the database administrator, notices the proposed reporting account can also edit points and delete orders. Should Sofia receive that account, or can the database expose exactly the information her task needs?

Identities

Accounts, Logins and Database Users

Start with identity. In MySQL, an account combines a user name with a host; localhost restricts matching connections to the local server. The same name with a wildcard host is a different account. Amina chooses the required origin instead of leaving access broadly open. Create user establishes that identity. Its secret comes from protected provisioning, never a password copied from an instructional screen. SQL Server commonly creates a server login, then maps a database user to it. Permissions inside shop belong to that database identity. These are server-specific examples, not commands for SQLite. Our local shell has no equivalent server account and grant model.

GRANT

Naming the Action, Object and Recipient

A privilege permits an action on an object. Grant names the action, the object, and the recipient. Read GRANT SELECT ON shop.customers TO 'reports'@'localhost'. That gives the MySQL account a table-level read permission. A database-wide grant covers a broader set of tables, including future tables. In SQL Server, a schema grant can similarly cover future objects. Amina names the required object instead. Broad scope is convenient, but it can expose data created after today's review. All privileges is too broad for this lookup. With grant option adds delegation: the recipient can pass permitted rights to other accounts.

REVOKE

Removing One Permission Entry

Revoke removes a permission entry. It does not promise that the person loses every route to the same effective permission. A direct grant might be removed while a role still grants read access. Amina reviews the whole permission path before declaring the change complete. In MySQL, show grants lists an account's grants. In SQL Server, permission and principal catalog views reveal recorded grants, denials, and memberships. Test using the intended identity too. Catalog inspection alone can miss the practical effect of inherited rights or execution context. When an identity is no longer needed, remove it. SQL Server database users and server logins are distinct objects, so retirement needs both considered.

Roles

Bundling Privileges for a Real Job

A role is a named bundle of privileges. Give the bundle the required rights, then assign people to that job role. Now a change to the role updates its members consistently. It also makes a permissions review easier to explain. MySQL supports create role and grant role membership. A granted role may still need activation before its permissions become effective. Set role activates a role for the session. Set default role controls activation on later connections; a grant alone is not that setting. SQL Server adds members with alter role, add member. Removing membership and changing the role's permissions solve different problems. Amina keeps support and administration separate. A role should describe a real job, rather than serve as a convenient bucket for every permission.

Column Permissions

Keeping Customer Points Out of Reach

Sofia's task needs first name, last name, and city. Customer points are outside that task, so Amina considers column-level permission. Grant select with a named column list, on the customers table. A statement selecting only those permitted columns can run. Select star includes points, and fails without the corresponding right. Mentioning a hidden column in filtering or sorting can require permission too. Otherwise, repeated questions about a hidden value could reveal it indirectly. Protecting a column involves more than omitting it from the displayed result. Column permissions differ by engine and action. Read, update, and references have column forms in both systems; MySQL also supports column-level insert.

SQL Server DENY

Explicit Refusals and Their Limits

SQL Server adds deny, an explicit refusal. Revoke removes an existing grant or denial; it does not create a new refusal. A denial generally overrides a grant received through another role. Amina uses that tool for a deliberate exception, rather than routine cleanup. There are important limits. Object owners and sysadmins are special, and a table-level denial does not override a column-level grant. No direct permission entry also does not settle access: role membership or broader permissions may still allow the action. MySQL has no deny statement. Arrange narrow grants there, and review other privilege paths rather than expecting a missing entry to block inherited rights.

Views

A View as a Controlled Doorway

A view provides another controlled doorway. Amina defines customer contacts as a select of names and cities, with points excluded. She grants support access to that view, while withholding direct access to customers. The caller cannot bypass the projection through the base table. A view can also filter rows or join tables. Its definition determines the information exposed, so review changes to the doorway itself. MySQL views normally use definer security: the creator's privileges support access. Invoker security instead uses the caller's rights. SQL Server can follow an ownership chain when the view and base object share an owner. A broken chain changes which permissions are required. The doorway needs a deliberately limited owner and definition. Putting a view in front of a powerful account is not automatically safe.

Stored Procedures

Granting EXECUTE on Fixed Work

A stored procedure is named work saved in the database. A fixed customer-order lookup accepts a customer identifier and runs its reviewed query. Grant execute permits that operation. Under the appropriate definer context or ownership chain, the caller need not receive direct table permission. That narrows the available actions, but not necessarily the customers. If any identifier is accepted, the application must still enforce who may request it. Dynamic SQL inside the procedure can introduce injection. Keep values bound, and never treat stored code as proof that its inputs are safe. Views limit a data picture; procedures limit a piece of work. Choose the doorway that matches the task, then test both permitted and forbidden requests.

Quick Check

Rows Still Visible After a Revoke

A former cashier loses a direct orders permission, yet an access test still returns order rows. Which place should Amina inspect first? Pause, and decide. Inspect the role memberships. Another permission path can remain after a direct grant is removed. An index or a data type changes neither membership nor the remaining grant. Review effective permissions, then repeat the access test.

Resolution

A Limited View Through a Support Role

Back to Sofia's lookup. Amina gives her the limited view through a support role, and verifies that names and cities are available. Direct customer access and points changes are refused in the intended identity's access tests. The review records the scope and why it is needed. Sofia gets a usable tool, while the database preserves a boundary around unrelated work. Future role changes now have a clear owner and test.

Key Takeaways

Narrowest Scope, Tested Access

Choose the right identity and the narrowest permission scope for the task. Use roles to manage shared job rights, and remember MySQL role activation. Revoke removes entries; effective access can still arrive through other paths. Review columns, views, and procedures as deliberate doorways, including their execution context.

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 Securing Databases with SQL: Techniques and Examples

How do you grant SELECT on a single table in MySQL?
Name the privilege, the object and the account: GRANT SELECT ON shop.customers TO 'reports'@'localhost'; lets that account read only the customers table. A grant ON shop.* covers every table in the database, including tables created later, so name the specific table when that is all the job needs. ALL PRIVILEGES is far too broad for a lookup, and WITH GRANT OPTION lets the recipient pass its rights to other accounts.
Why can a user still access data after REVOKE?
REVOKE removes one permission entry, but the same access can still arrive another way, most often through a role or a broader grant. In MySQL, SHOW GRANTS FOR 'cashier'@'localhost'; lists the account's privileges and roles; in SQL Server, catalog views show grants, denials and role memberships. Then test with the intended identity, because inherited rights and execution context can still allow access that a single entry does not show.
What is the difference between DENY and REVOKE in SQL Server?
DENY creates an explicit refusal that generally overrides a grant received through a role, while REVOKE only removes an existing grant or denial without creating any refusal. After a REVOKE, access may still come from role membership. DENY has limits: it does not stop object owners or sysadmin members, and a table-level DENY does not override a column-level GRANT. MySQL has no DENY statement, so it relies on narrow grants.
How do you restrict a user to certain columns of a table?
Grant SELECT on a named column list, or grant access to a view that selects only the allowed columns. In MySQL, GRANT SELECT (first_name, last_name, city) ON shop.customers TO 'support'@'localhost'; allows SELECT first_name, city but makes SELECT * fail, because it includes hidden columns. Referring to a hidden column in WHERE or ORDER BY can also require permission. MySQL supports column-level SELECT, INSERT, UPDATE and REFERENCES; SQL Server has no column-level INSERT.

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 →