create a table to store the login information
CREATE TABLE user_login (
username VARCHAR(50) PRIMARY KEY,
last_login TIMESTAMP
);
Create a PL/pgSQL function that updates the last login timestamp whenever a user
logs in
CREATE OR REPLACE FUNCTION update_last_login()
RETURNS TRIGGER AS $$
BEGIN
-- Update the last login timestamp for the logged-in user
UPDATE user_login
SET last_login = NOW()
WHERE username = current_user;
-- If the user doesn't exist in the table, insert a new record
IF NOT FOUND THEN
INSERT INTO user_login (username, last_login)
VALUES (current_user, NOW());
END IF;
RETURN NULL;
END;
$$ LANGUAGE plpgsql;
Next, create a trigger that fires the update_last_login function whenever a user
logs in.
CREATE TRIGGER update_last_login_trigger
AFTER LOGON ON DATABASE
EXECUTE FUNCTION update_last_login();
Try
SELECT last_login
FROM user_login
WHERE username = 'desired_username';