A guide for when you have to add/remove/update/and/20/other/things in both mysql & postgres databases, and you wind up getting lost trying to do seemingly simple things. I've been keeping a running doc where I keep snippets of SQL for those times when I have to remember, and I hope they help if you happen to be using both postgres and mysql and need to manage user access.
Below, we've got 10 frequently used SQL snippets for managing users.
- add a user
- reset a password
- checking users privileges
- revoking privileges
- remove a user
- expire passwords/temporary credentials
- checking expiration time
- granting read-only access
- checking if a user exists
- some debug information that might help
If you want to play around with these scripts with a development database, start them up using docker and connect to it:
in postgres:
# start postgres in docker
docker run --rm --name pgsql -e POSTGRES_PASSWORD=password -p 5555:5432 -d postgres
e0e76a6af8b1f83cf91295ae5430cbf2ecd95337977b53653f312024d8aab3ad
# connect to postgres
psql -h 127.0.0.1 -p 5555 -U postgres -d postgres
in mysql:
# start mysql in docker
docker run --rm --name mysql -p3307:3306 -e MYSQL_ROOT_PASSWORD=password -d mysql
# connect to mysql
mysql -h 127.0.0.1 -P 3307 -u root -p
1. add a user
in postgres:
CREATE USER '${user}' WITH PASSWORD '${password}';
GRANT ALL ON DATABASE '${db}' TO '${user}'; -- grants read/write to everything in this database instance
-- OR
GRANT CONNECT ON DATABASE '${db}' to '${user}'; -- only allows the user to connect, but nothing more.
* https://www.postgresql.org/docs/8.0/static/sql-createuser.html
in mysql:
CREATE USER '${user}' IDENTIFIED BY '${password}';
GRANT ALL PRIVILEGES ON ${db}.* TO '${user}';
* https://dev.mysql.com/doc/refman/8.0/en/adding-users.html
2. reset a password
in postgres:
ALTER ROLE '${user}' WITH PASSWORD '${pw}';
* https://www.postgresql.org/docs/8.0/static/sql-alteruser.html
in mysql:
ALTER USER '${user}' IDENTIFIED BY '${pw}'
*heres 2 more ways of doing this: https://www.geeksforgeeks.org/mysql-change-user-password/
3. checking a users privileges
in postgres:
This will list all the databases and show you all the roles that have access to it.
postgres=# \l
List of databases
Name | Owner | Encoding | Collate | Ctype | Access privileges
-----------+----------+----------+------------+------------+-----------------------
postgres | postgres | UTF8 | en_US.utf8 | en_US.utf8 |
template0 | postgres | UTF8 | en_US.utf8 | en_US.utf8 | =c/postgres +
| | | | | postgres=CTc/postgres
template1 | postgres | UTF8 | en_US.utf8 | en_US.utf8 | =c/postgres +
| | | | | postgres=CTc/postgres
This will show all the role names and the other roles they include.
postgres=# \du
List of roles
Role name | Attributes | Member of
-----------+------------------------------------------------------------+-----------
postgres | Superuser, Create role, Create DB, Replication, Bypass RLS | {}
This will show all the tables that a user has access to
postgres=# \z
Access privileges
Schema | Name | Type | Access privileges | Column privileges | Policies
--------+--------+-------+---------------------------+-------------------+----------
public | foobar | table | postgres=arwdDxt/postgres+| |
| | | dperez=r/postgres | |
public | test | table | postgres=arwdDxt/postgres+| |
| | | dperez=r/postgres | |
(2 rows)
...
See the postgres docs on grants to decipher that description
in mysql:
mysql> SHOW GRANTS FOR '${user}';
+---------------------------------------------------------------------+
| Grants for root@localhost |
+---------------------------------------------------------------------+
| GRANT ALL PRIVILEGES ON *.* TO '${user}'@'localhost' WITH GRANT OPTION |
+---------------------------------------------------------------------+
4. revoke privileges
in postgres:
REVOKE ALL PRIVILEGES ON DATABASE '${db}' from '${user}';
* https://www.postgresql.org/docs/9.1/static/sql-revoke.html
in mysql:
REVOKE ALL PRIVILEGES ON '${db}.*' FROM '${user}';
*https://dev.mysql.com/doc/refman/8.0/en/revoke.html
5. remove a user
in postgres:
DROP ROLE IF EXISTS '${user}';
You might see an error message like:
ERROR: role "testuser" cannot be dropped because some objects depend on it DETAIL: $somethingUseful
this means that your user has dependencies with other objects - things like privileges and other tables. In this case, you'd need to run:
REVOKE ALL PRIVILEGES ON DATABASE '${db}' from '${user}';
DROP ROLE IF EXISTS '${user}';
If this fails, then try
DROP OWNED BY '${user}';
DROP ROLE IF EXISTS '${user}'
The irony here is that you would typically use DROP ROLE IF EXISTS
so that a script would not error out if the role did not exist. However, when the role does NOT exist, you get back a successful response. When the role DOES exist, it will likely have privileges and require you to run REVOKE ALL PRIVILEGES
- and unfortunately you cannot do REVOKE ALL ... IF EXISTS
. It kind of renders the whole DROP ROLE IF EXISTS
convenience statement useless.
in mysql:
DROP USER IF EXISTS '${user}';
Thank you for being so straightforward about it, mysql.
6. expire a password / temporary credentials
in postgres:
ALTER ROLE '${user}' WITH PASSWORD '${password}' VALID UNTIL '${expiration_timestamp}';
Here, expiration_timestamp
has the format Nov 3 12:00:00 2018 +1
and means the time at which the password will no longer work.
*https://www.postgresql.org/docs/9.2/static/sql-alterrole.html
in mysql:
ALTER USER '${user}' PASSWORD EXPIRE INTERVAL 1 DAY;
The statement seems to only allow DAY
as the interval unit. So INTERVAL 90 DAY
would be correct (note: no plural s in day).
7. how to check expiration time of password
Once you set a password expiration time, it would be useful to see what that time is.
in postgres:
SELECT valuntil AS valid_until FROM pg_user WHERE usename = '${user}';
in mysql:
SELECT DATE_ADD(password_last_changed, interval password_lifetime day) AS valid_until FROM mysql.user WHERE user = '${user}';
8. granting read-only access
in postgres:
GRANT USAGE ON SCHEMA public TO '${user}';
GRANT SELECT ON ALL TABLES IN SCHEMA public TO '${user}';
* related thread about what grant all privileges on database
actually does
You might find later on that if you add a table, this read-only user does not have access to read that table. In which case, run the following to make sure that you by default get privileges on tables:
ALTER DEFAULT PRIVILEGES IN SCHEMA public GRANT SELECT ON TABLES TO '${user}';
* more info here - https://stackoverflow.com/questions/760210/how-do-you-create-a-read-only-user-in-postgresql
in mysql:
GRANT SELECT ON '${db}'.* TO '${user}';
9. check if a user exists
in postgres:
SELECT 1 FROM pg_roles WHERE rolname='${user}';
in mysql:
SELECT EXISTS(SELECT 1 FROM mysql.user WHERE user = '${user}');
10. get some debug info about your current user
in postgres:
postgres=# \conninfo
You are connected to database "postgres" as user "postgres" on host "127.0.0.1" at port "5555".
postgres=# SELECT CURRENT_USER;
current_user
--------------
postgres
(1 row)
postgres=# SELECT CURRENT_USER(); -- you can't use it as a function
ERROR: syntax error at or near "("
LINE 1: SELECT CURRENT_USER();
in mysql:
mysql> select CURRENT_USER();
mysql> select CURRENT_USER; -- both this and the above function return the same result
+----------------+
| current_user() |
+----------------+
| dperez@% |
+----------------+
mysql> status
--------------
mysql Ver 14.14 Distrib 5.7.22-22, for osx10.11 (x86_64) using EditLine wrapper
Connection id: 683
Current database: dpereztest
Current user: dperez@10.162.9.100
SSL: Cipher in use is DHE-RSA-AES128-SHA
Current pager: less
Using outfile: ''
Using delimiter: ;
Server version: 8.0.11 Source distribution
Protocol version: 10
Connection: 127.0.0.1 via TCP/IP
Server characterset: utf8mb4
Db characterset: utf8mb4
Client characterset: utf8
Conn. characterset: utf8
TCP port: 5555
Uptime: 2 days 7 hours 55 min 53 sec
Threads: 3 Questions: 107602 Slow queries: 0 Opens: 285 Flush tables: 2 Open tables: 259 Queries per second avg: 0.534
--------------
I hope this helps as a useful guide the next time you need to manage users on a postgres or mysql database. There's dozens of more things you can do to customize your users and their access levels, but this guide should serve as a starting off point with links to the docs to help you do what you're trying to do.
If you're managing users and credentials across multiple teams, you might want to check out:
108 Comments. Leave new
Hi, there, thank you for sharing such a great piece of content with us. It is really an informative and amazing post, it also helps me a lot.
Screenshot on Macbook
String Alphanumeric
Twitter Heart button
Very nice blog post. I definitely love this site. Stick with it! news 12 new jersey
Looking forward to reading more. great article. Really looking forward to reading more books. cool. I really enjoy reading a thought provoking article. Also, thanks for allowing me to comment!
Greetings! Very helpful advice in this particular article! It is the little changes which will make the most important changes. Thanks a lot for sharing! watch free horse racing
I don’t think the title of your article matches the content lol. Just kidding, mainly because I had some doubts after reading the article.
Can you be more specific about the content of your article? After reading it, I still have some doubts. Hope you can help me.
Thanks for sharing. I read many of your blog posts, cool, your blog is very good.
Thank you for your sharing. I am worried that I lack creative ideas. It is your article that makes me full of hope. Thank you. But, I have a question, can you help me?
Can you be more specific about the content of your article? After reading it, I still have some doubts. Hope you can help me. https://accounts.binance.com/vi/register-person?ref=S5H7X3LP
I don’t think the title of your article matches the content lol. Just kidding, mainly because I had some doubts after reading the article. https://accounts.binance.com/cs/register-person?ref=OMM3XK51
Thanks for shening. I read many of your blog posts, cool, your blog is very good. https://www.binance.com/en/register?ref=P9L9FQKY
I may need your help. I’ve been doing research on gate io recently, and I’ve tried a lot of different things. Later, I read your article, and I think your way of writing has given me some innovative ideas, thank you very much.
naturally like your web site however you need to take a look at the spelling on several of your posts. A number of them are rife with spelling problems and I find it very bothersome to tell the truth on the other hand I will surely come again again.
You have noted very interesting points! ps decent web site. “Formal education will make you a living self-education will make you a fortune.” by Jim Rohn.
Your article gave me a lot of inspiration, I hope you can explain your point of view in more detail, because I have some doubts, thank you.
Rüyada Altın Nişan Yüzüğü Görmek Ne Demek?
13k Ne Demek?
Thank you very much for sharing, I learned a lot from your article. Very cool. Thanks. nimabi
Thank you for your sharing. I am worried that I lack creative ideas. It is your article that makes me full of hope. Thank you. But, I have a question, can you help me? https://accounts.binance.com/ph/register-person?ref=53551167
Thank you for great article. Hello Administ .
Can you be more specific about the content of your article? After reading it, I still have some doubts. Hope you can help me. https://www.binance.info/zh-TC/join?ref=P9L9FQKY
Thank you for great content. Hello Administ.
LeanBiome is an innovative and effective supplement that has been specifically formulated to support healthy weight loss. The product is the result of the latest Ivy League research and is backed by real-world results.
Thank you for content. Area rugs and online home decor store. Hello Administ . Website Giriş için Tıklayın: deneme bonusu veren siteler
Thank you for great information. Hello Administ . Website Giriş için Tıklayın: asyabahisgo1.com
Sumatra Slim Belly Tonic is a unique weight loss supplement that sets itself apart from others in the market. Unlike other supplements that rely on caffeine and stimulants to boost energy levels, Sumatra Slim Belly Tonic takes a different approach. It utilizes a blend of eight natural ingredients to address the root causes of weight gain. By targeting inflammation and improving sleep quality, Sumatra Slim Belly Tonic provides a holistic solution to weight loss. These natural ingredients not only support healthy inflammation but also promote better sleep, which are crucial factors in achieving weight loss goals. By addressing these underlying issues, Sumatra Slim Belly Tonic helps individuals achieve sustainable weight loss results.
Sugar Defender stands as a beacon of natural, side-effect-free blood sugar support. Crafted from a blend of pure, plant-based ingredients, this formula not only helps regulate blood sugar levels but also empowers you on your journey to weight loss, increased vitality, and overall life improvement.
Thank you for great content. Hello Administ.
After all, what a great site and informative posts, I will upload inbound link – bookmark this web site? Regards, Reader.
Nice article inspiring thanks. Hello Administ .
Thank you great post. Hello Administ .
Hi, just required you to know I he added your site to my Google bookmarks due to your layout. But seriously, I believe your internet site has 1 in the freshest theme I??ve came across.
Your article helped me a lot, is there any more related content? Thanks! https://www.binance.com/ph/register?ref=V3MG69RO
I really love to read such an excellent article. Helpful article. Hello Administ .
Thank you for great content. Hello Administ.
Thank you for great information. Hello Administ .
Thank you for great information. Hello Administ .
Share with us in the comments your favorite blog posts of all time!
Good info. Lucky me I reach on your website by accident, I bookmarked it.
Thank you for great article. Hello Administ .
Hello! I could have sworn I’ve been to this blog before but after browsing through some of the post I realized it’s new to me.
Hi, just required you to know I he added your site to my Google bookmarks due to your layout. But seriously, I believe your internet site has 1 in the freshest theme I??ve came across.
marsbahis”>
Hello! I could have sworn I’ve been to this blog before but after browsing through some of the post I realized it’s new to me.
Can you be more specific about the content of your article? After reading it, I still have some doubts. Hope you can help me. https://www.binance.com/join?ref=V3MG69RO
Hi, just required you to know I he added your site to my Google bookmarks due to your layout. But seriously, I believe your internet site has 1 in the freshest theme I??ve came across.Website Giriş için Tıklayın: marsbahis
Hi, just required you to know I he added your site to my Google bookmarks due to your layout. But seriously, I believe your internet site has 1 in the freshest theme I??ve came across.
Everything is very open and very clear explanation of issues. was truly information.
I really love to read such an excellent article. Helpful article. Hello Administ .
Nice article inspiring thanks. Hello Administ .
Hi, just required you to know I he added your site to my Google bookmarks due to your layout. But seriously, I believe your internet site has 1 in the freshest theme I??ve came across.
Thank you for content. Area rugs and online home decor store. Hello Administ .
Thank you for content. Area rugs and online home decor store. Hello Administ .
Thank you for great content. Hello Administ.
I really love to read such an excellent article. Helpful article. Hello Administ .
Thank you for great article. Hello Administ .
Thank you great posting about essential oil. Hello Administ .
Thank you for content. Area rugs and online home decor store. Hello Administ .
Thank you for great content. Hello Administ.
Hello! I could have sworn I’ve been to this blog before but after browsing through some of the post I realized it’s new to me.
Thank you for content. Area rugs and online home decor store. Hello Administ .
Hi, just required you to know I he added your site to my Google bookmarks due to your layout. But seriously, I believe your internet site has 1 in the freshest theme I??ve came across.
Thanks for sharing. I read many of your blog posts, cool, your blog is very good. https://www.binance.info/uk-UA/join?ref=OMM3XK51
Hello! I could have sworn I’ve been to this blog before but after browsing through some of the post I realized it’s new to me.Website Giriş için Tıklayın: cinsel sohbet
Everything is very open and very clear explanation of issues. was truly information.Website Giriş için Tıklayın: imajbet
Can you be more specific about the content of your article? After reading it, I still have some doubts. Hope you can help me.
Thanks for sharing. I read many of your blog posts, cool, your blog is very good.
Thank you for your sharing. I am worried that I lack creative ideas. It is your article that makes me full of hope. Thank you. But, I have a question, can you help me?
Thanks for sharing. I read many of your blog posts, cool, your blog is very good.
I just like the helpful information you provide in your articles
Your article helped me a lot, is there any more related content? Thanks!
I’ve been following this blog for years and it’s amazing to see how much it has grown and evolved Congratulations on all your success!
Your point of view caught my eye and was very interesting. Thanks. I have a question for you.
Your writing style is so engaging and makes even the most mundane topics interesting to read Keep up the fantastic work
I love how this blog gives a voice to important social and political issues It’s important to use your platform for good, and you do that flawlessly
Your article helped me a lot, is there any more related content? Thanks!
Thank you for this wonderful post! I found it very informative and engaging. Your thorough research and clear writing style made it easy to understand. I appreciate the time and effort you put into creating this valuable content. Keep up the excellent work.
Thanks for sharing. I read many of your blog posts, cool, your blog is very good.
Thanks for sharing. I read many of your blog posts, cool, your blog is very good.
Can you be more specific about the content of your article? After reading it, I still have some doubts. Hope you can help me.
gluco6 reviews : https://gluco6reviews.usaloves.com/
gluco6 reviews : https://gluco6reviews.usaloves.com/
gluco6 reviews : https://gluco6reviews.usaloves.com/
gluco6 reviews : https://gluco6reviews.usaloves.com/
gluco6 reviews : https://gluco6reviews.usaloves.com/
gluco6 reviews : https://gluco6reviews.usaloves.com/
gluco6 reviews : https://gluco6reviews.usaloves.com/
gluco6 reviews : https://gluco6reviews.usaloves.com/
gluco6 reviews : https://gluco6reviews.usaloves.com/
gluco6 reviews : https://gluco6reviews.usaloves.com/
gluco6 reviews : https://gluco6reviews.usaloves.com/
gluco6 reviews : https://gluco6reviews.usaloves.com/
gluco6 reviews : https://gluco6reviews.usaloves.com/
gluco6 reviews : https://gluco6reviews.usaloves.com/
Thanks for sharing. I read many of your blog posts, cool, your blog is very good.
Can you be more specific about the content of your article? After reading it, I still have some doubts. Hope you can help me.
Your article helped me a lot, is there any more related content? Thanks!
Thank you for your sharing. I am worried that I lack creative ideas. It is your article that makes me full of hope. Thank you. But, I have a question, can you help me?
Thanks for sharing. I read many of your blog posts, cool, your blog is very good. https://accounts.binance.com/en-IN/register-person?ref=UM6SMJM3
Can you be more specific about the content of your article? After reading it, I still have some doubts. Hope you can help me.
Is SonoVive a scam or a legitimate supplement?: sonovive scam
Is SonoVive a scam or a legitimate supplement?: sonovive scam
Is NeuroPrime a Scam or Legit?: NeuroPrime scam
Is Cacao Bliss a scam or is it a legitimate product?: Cacao Bliss scam
Is Pineal Pure a scam or is it legitimate?: pineal pure scam
Thanks for sharing. I read many of your blog posts, cool, your blog is very good.
I don’t think the title of your article matches the content lol. Just kidding, mainly because I had some doubts after reading the article.
Can you be more specific about the content of your article? After reading it, I still have some doubts. Hope you can help me.