…
…
SQL and Database Fundamentals · Lesson 40 / 41 · Indexes and permissions
PreviewIn this lesson you will
You can read the explanation without an account. The exercises and quiz at the end of the lesson are for members.
More than one person now uses the database: the reporting team will only read, the registrar's office will add and fix enrollments, and the summer intern will see only the students' names and departments. On top of that, someone noticed that typing ' OR '1'='1 into the student number box on the student lookup screen shows every GPA. You need to give everyone only the access their job needs and close this hole.
Until now you ran every command as the owner of the database, a user who can do everything. Since the start of the unit you added rows, updated them, deleted them, rolled back transactions, and built views and indexes. You could do all of it because nobody told you "this is not your job." In a real system it is different: dozens of people and several applications connect to the same database, and none of them should be able to do everything.
By the end of the lesson you will build the following privilege table yourself and check each row by trying it as that role:
| Role | What it can do |
|---|---|
reporter | Only SELECT on the tables the report needs |
registrar | SELECT, INSERT, UPDATE on the enrollment table (no DELETE) |
intern | Only SELECT on the student_basic view; no access to the student table |
In this lesson you will:
Imagine that a bug in a report tool could run DELETE FROM enrollment;. Or that a summer intern could see every student's GPA and birth date. Neither should be possible. GPA, birth date and email are personal data. Privacy laws (GDPR and similar) expect that only people who need the data for their work can reach it. In a database, privileges are the tool for this: who can run which command on which table?
In PostgreSQL, a user and a group are the same concept: a role. A role that can log in (created with the LOGIN option) acts like a user; a role that cannot log in works like a group that collects privileges. You create a role with CREATE ROLE name;. A new role has no privileges on tables; you give a privilege with GRANT command ON table TO role;. To ask about a role's privilege, use has_table_privilege('role', 'table', 'command'), which returns true or false.
Example 1 (case): Read access for the reporting team
CREATE ROLE reporter; GRANT SELECT ON department TO reporter; SELECT has_table_privilege('reporter', 'department', 'SELECT') AS reads_department, has_table_privilege('reporter', 'student', 'SELECT') AS reads_student;
| reads_department | reads_student |
|---|---|
| true | false |
The reporter role can read the department table, but nobody gave it a privilege on student, so the answer is false. The idea that "a new role starts with read access to the tables" is common but wrong: a role starts with an empty card, and you open each door separately.
Try it yourself: in the cell below, also give SELECT on the student table and see the second column become true. Hint: you can list several tables with commas, like GRANT SELECT ON department, student TO reporter;.
Try it now· not graded; doesn't affect progress
Instead of asking about each privilege one by one, you can also see all granted privileges as a list. The list is in the information_schema.role_table_grants view; it is the first place to look when you audit privileges.
Example 2 (case): The list of granted privileges
CREATE ROLE reporter; GRANT SELECT ON student, department TO reporter; SELECT table_name, privilege_type FROM information_schema.role_table_grants WHERE grantee = 'reporter' ORDER BY table_name, privilege_type;
| table_name | privilege_type |
|---|---|
| department | SELECT |
| student | SELECT |
The basic table privileges are SELECT, INSERT, UPDATE, DELETE and TRUNCATE. Each one is a separate door: a role that can read cannot add rows, and a role that can add cannot delete.
Asking about a privilege is good, but the real proof is to take the role's place and try. SET ROLE reporter; runs the session with that role's privileges for a while; RESET ROLE; goes back. current_user shows who you are acting as at that moment.
Example 3 (case): A query as reporter
CREATE ROLE reporter; GRANT SELECT ON department TO reporter; SET ROLE reporter; SELECT current_user, COUNT(*) AS departments FROM department; RESET ROLE;
| current_user | departments |
|---|---|
| reporter | 8 |
If you run SELECT * FROM student; with the same role, the database rejects the query:
OutputERROR: permission denied for table studentThis error is not a failure; it is the wanted behavior: the card does not open that door.
A privilege can also be given at column level instead of table level. The outreach team will send emails to students; they should see the student number, first name, last name and email, but not the GPA or birth date. The column list goes in parentheses right after the command.
Example 4 (case): Column privilege
CREATE ROLE outreach; GRANT SELECT (student_no, first_name, last_name, email) ON student TO outreach; SET ROLE outreach; SELECT first_name, last_name, email FROM student WHERE student_no = '202504001';
| first_name | last_name | |
|---|---|---|
| Hiro | Lefèvre | hiro.lefevre@students.northbridge.example |
Now let's make a small change with the same role: find the student by id instead of by number. The SELECT list has only first_name, and first_name is a column with a privilege.
The outreach role can read only the columns student_no, first_name, last_name and email. What happens if this role runs the query below?
SET ROLE outreach; SELECT first_name FROM student WHERE id = 4;
Why is it like this? Filtering is also reading. If you write WHERE gpa > 3.5 and see only names in the result, you still learn which students have a GPA above 3.5. So the idea that "every query works as long as I put columns I can read in the SELECT list" is dangerous: you need a privilege for every column the query touches. WHERE student_no = '202504001' works because student_no is allowed; WHERE id = 4 does not.
Every time a new analyst joins the team, giving privileges one by one is tiring and easy to get wrong. Instead, you give the privileges to a group role that cannot log in, and make people members of that group. A member gets all the privileges of the group.
Example 5 (case): A reader group
CREATE ROLE reader NOLOGIN; GRANT SELECT ON ALL TABLES IN SCHEMA public TO reader; CREATE ROLE amara LOGIN; GRANT reader TO amara; SELECT has_table_privilege('amara', 'enrollment', 'SELECT') AS can_read, has_table_privilege('amara', 'enrollment', 'UPDATE') AS can_update;
| can_read | can_update |
|---|---|
| true | false |
Amara never got a privilege directly; because she is a member of the reader group, she can read every table but cannot update. When she leaves the team, REVOKE reader FROM amara; is enough on its own.
REVOKE takes back a granted privilege, and its form mirrors GRANT: REVOKE command ON table FROM role;. If the registrar's office was given DELETE by mistake, REVOKE DELETE ON enrollment FROM registrar; takes it back, and the role keeps INSERT, SELECT and UPDATE (the working version is in the Examples section below).
For the intern, a column privilege is also a way, but the view you saw in lesson 38 gives a cleaner solution: you do not open the table to the intern, only a view that selects the needed columns.
Example 6 (case): A view for the intern
CREATE ROLE intern; CREATE VIEW student_basic AS SELECT student_no, first_name, last_name, department_id FROM student; GRANT SELECT ON student_basic TO intern; SELECT has_table_privilege('intern', 'student_basic', 'SELECT') AS view_access, has_table_privilege('intern', 'student', 'SELECT') AS table_access;
| view_access | table_access |
|---|---|
| true | false |
The intern has no access to the table but can read the view. After the same setup, the query SET ROLE intern; SELECT current_user, COUNT(*) FROM student_basic; returns intern | 120: the intern sees all 120 students, but only four of their columns. The view reads the table with its owner's privileges; the intern sees only what the view shows.
Match each task with the privilege that follows the principle of least privilege.
For each row, pick its match from the list, then check.
The rule behind this table has a name: the principle of least privilege. Every user and application gets the least privilege that is enough to do its job. Why so strict? Because accounts can be taken over and code makes mistakes. If the report tool's account leaks, the attacker can at most read; DELETE does not work with that account. The damage stays limited to that role's privileges. Reviewing privileges from time to time and taking back the ones that are no longer needed with REVOKE is also part of this principle: a write privilege given for a project last term should be removed when the project ends.
By the principle of least privilege, which privilege should a tool that only pulls reports get?
One more note: privileges can also be given at row level. PostgreSQL's row level security feature lets each user see only their own rows; this site's database uses it on every table. Setting it up is outside the scope of this lesson.
Privileges protect the door of the database. But if an application sends its own query to the database and puts text typed by the user inside that query, the door can be opened from the inside. The hole in the case is exactly this.
The student lookup screen has a number box. The program builds the query by pasting what is typed in the box into the query text. The template in the program is roughly like this (this is not SQL code; it is the program's text joining):
Output"SELECT first_name, last_name, gpa FROM student WHERE student_no = '" + box + "'"When 202601001 is typed in the box, the resulting query looks harmless:
Example 7a (case): The expected input
SELECT first_name, last_name, gpa FROM student WHERE student_no = '202601001';
| first_name | last_name | gpa |
|---|---|---|
| Adaeze | Müller | NULL |
One row came back; Adaeze is in her first year and has no GPA yet. Now someone types ' OR '1'='1 into the box instead of a number. The program pastes this text into the same template. Put the parts of the resulting query in order:
' OR '1'='1 was typed into the box. Build the query text that the template and the input make together, in the right order, from its parts.
Click the lines in order; to undo one you placed wrong, click it in the list below.
Shuffled lines
Your order
This query is perfect in syntax, and the database runs it. Remember from lessons 4 and 8: if one of the conditions joined with OR is true, the row passes. '1'='1' is true on every row.
Example 7 (case): The query made by injection
SELECT COUNT(*) AS visible FROM student WHERE student_no = '' OR '1'='1';
| visible |
|---|
| 120 |
The screen was made to show one student; now the names and GPAs of all 120 students are on the screen. The attacker did not need deep SQL knowledge: one quote mark and a short condition were enough. So the idea that "injection is only for expert attackers, and the result does not change much" is wrong: 120 rows came back instead of 1.
It can get worse. If '; DELETE FROM enrollment; -- is typed into the box, the resulting text becomes two separate commands: first an empty search, then a DELETE that removes all enrollments. The -- at the end turns the rest of the template's quote into a comment.
SELECT first_name, last_name, gpa FROM student WHERE student_no = ''; DELETE FROM enrollment; --'; SELECT COUNT(*) AS remaining_enrollments FROM enrollment;
| remaining_enrollments |
|---|
| 0 |
All 781 enrollments are gone. On this site every run is rolled back, so the data is back in place on the next run; in a real system it would not be.
Try it yourself: the query made by injection is ready in the cell. First replace the input part ('' OR '1'='1') with a student number (for example '202601001') and see 1; then undo it and compare with 120.
Try it now· not graded; doesn't affect progress
The root of the problem is that the text typed by the user mixes into the query text. The solution comes from there too: send the query and the value separately. This is called a parameterized query. The query is prepared in advance with a placeholder ($1) where the value goes; the value is given later on its own, and the database always uses it as a value and never reads it as part of the query. Think of a form: whatever you write in the blank, the sentence of the form does not change; what you write only fills the blank.
In PostgreSQL you can see this directly in SQL with the PREPARE and EXECUTE commands.
Example 8 (case): A prepared statement
BEGIN; PREPARE find_student(text) AS SELECT first_name, last_name, gpa FROM student WHERE student_no = $1; EXECUTE find_student('202601001'); ROLLBACK;
| first_name | last_name | gpa |
|---|---|---|
| Adaeze | Müller | NULL |
Let's give the attacker's input to the same prepared statement. In SQL, a quote inside text is written as two quotes, so the text ' OR '1'='1 appears as ''' OR ''1''=''1'; the value is still the same as the text typed into the box.
How many rows come back if ' OR '1'='1 is typed into the box of a parameterized query?
BEGIN; PREPARE find_student(text) AS SELECT first_name, last_name, gpa FROM student WHERE student_no = $1; EXECUTE find_student(''' OR ''1''=''1'); ROLLBACK;
Indeed, this query returns no rows: the result has only the column headers first_name, last_name, gpa. The same idea is used in programming languages; for example in Python the query is written as cursor.execute(query, (no,)), and the value is sent as a separate argument. The rule is simple: never paste text from the user into the query text; send it as a parameter.
You often hear the suggestion "just delete the quotes from the input." Cleaning by hand leaves gaps: it is easy to forget other special characters, different encodings, or numeric fields (like WHERE id = + box, where no quote is needed at all), and one forgotten place is enough. A parameterized query solves this at the root. The second line of defense is privileges: if the role that the student lookup screen connects with did not have DELETE on enrollment, the second attack would also stop with the error permission denied for table enrollment. The two measures do not replace each other; you use them together.
The best-known target of injection is the login screen. A small application checks the username and password: what is typed in the boxes is pasted into the template WHERE username = '...' AND password = '...'. What happens if ' OR '1'='1 is typed into the password box?
Example 9 (outside the case): Login without a password
CREATE TABLE app_user (username VARCHAR(20), password VARCHAR(20)); INSERT INTO app_user VALUES ('ali', 'secret123'), ('maya', 'pass456'); SELECT username FROM app_user WHERE username = 'ali' AND password = '' OR '1'='1';
| username |
|---|
| ali |
| maya |
Remember from lesson 8: AND binds before OR. The condition reads as (username = 'ali' AND password = '') OR '1'='1', and the second part is true on every row. If the application thinks "at least one row came back, so the login worked," someone who does not know the password gets in, and as the first user in the list. Note: in a real system, passwords are not stored as plain text; they are stored as a hash, which is a separate topic.
Try it yourself: write the parentheses explicitly in the condition: WHERE (username = 'ali' AND password = '') OR '1'='1'. Did the result change? Then think about this: wherever you put the parentheses, the text typed into the box can also close the parenthesis and add its own condition. So parentheses are not a solution either; the solution is the parameter.
Try it now· not graded; doesn't affect progress
The roles you create here, the privileges you give and SET ROLE are all undone at the end of every run; you can try as much as you like. The CREATE ROLE ... LOGIN command works, but you cannot really connect to the database in the browser with that role: login, password and connection happen on a real server. To try things from a role's point of view, use SET ROLE. A statement prepared with PREPARE stays for the whole session and is not deleted even if the transaction is rolled back; if you run the same code a second time, you get the error prepared statement "find_student" already exists. So write code that has PREPARE between BEGIN; ... ROLLBACK;: then each run starts on a clean copy. Creating roles and handing out privileges in your own database is usually the database administrator's job; writing parameterized queries is your job when you write an application.
The registrar's office was also given the delete privilege on the enrollment table by mistake. The job description says "adds, reads, fixes"; DELETE is taken back.
CREATE ROLE registrar; GRANT SELECT, INSERT, UPDATE, DELETE ON enrollment TO registrar; REVOKE DELETE ON enrollment FROM registrar; SELECT privilege_type FROM information_schema.role_table_grants WHERE grantee = 'registrar' ORDER BY privilege_type;
| privilege_type |
|---|
| INSERT |
| SELECT |
| UPDATE |
REVOKE takes only the privilege it names; the other three stay in place.
If the role that the student lookup screen connects with can only read, a DELETE squeezed in by injection also stops.
CREATE ROLE web_app; student, enrollment TO web_app; web_app; enrollment;
Giving full privileges to an application or a team to make things easier: "everyone can be an admin for now, we will fix it later." Privileges given as temporary become permanent, and one bug, one leak or a single injection affects all the data. Giving privileges by task from the start, following the principle of least privilege, is much easier than collecting them later; write the application's queries as parameterized queries from the start too.
CREATE ROLE); a new role starts with no privileges, and a member gets the privileges of the group role it belongs to.GRANT gives a privilege and REVOKE takes it back; a privilege is given at table, column or view level, and a column privilege also covers a column used in WHERE; follow the principle of least privilege and check with SET ROLE as the role.Next lesson: In Unit 8 we move to advanced queries; with window functions you will rank and compare rows without grouping them, and then you will build the capstone application.
Exercises and quiz are for members
This lesson has 6 coding exercises and a 10-question quiz. Sign up free to solve them, save your progress and move on to the next lesson.
OutputERROR: permission denied for table enrollmentA parameterized query prevents injection; privileges limit the damage if something gets through.