CREATE TABLE customers (
customer_id serial PRIMARY KEY,
firstname VARCHAR(100) NOT NULL,
lastname VARCHAR(100) NOT NULL,
username VARCHAR(50) UNIQUE NOT NULL,
password VARCHAR(50) NOT NULL,
email VARCHAR(255) UNIQUE NOT NULL,
created_on TIMESTAMPTZ NOT NULL
);
SELECT username FROM customers WHERE email LIKE '%@myemail.com';
利用选择的数据创建一个新表
sql复制代码
CREATE TABLE usernames AS SELECT username FROM customers WHERE email LIKE '%@myemail.com';
5. 排序
选择的数据将按照"lastname"字段进行降序排列
sql复制代码
SELECT firstname, lastname
FROM customers
ORDER BY lastname DESC;
返回的结果将会包含每个客户的完整姓名、邮箱地址以及密码的长度,并且按照密码长度从短到长进行排序。
sql复制代码
SELECT firstname || ' ' || lastname fullname, email, LENGTH(password) passwordlength
FROM customers
ORDER BY passwordlength;
选择 password 长度小于9的数据
sql复制代码
SELECT firstname || ' ' || lastname fullname, email, LENGTH(password) passwordlength
FROM customers
WHERE LENGTH(password) < 9
ORDER BY passwordlength;
6. 删除
使用RETURNING关键字,返回受影响的行。
sql复制代码
DELETE FROM customers
WHERE customer_id = 1
RETURNING *;
从"customers"表中删除"username"字段不等于'nkidman'的行
sql复制代码
DELETE FROM customers
WHERE username <> 'nkidman'
RETURNING *;
从"customers"表中删除所有行。
sql复制代码
DELETE FROM customers
RETURNING *;
7. 创建只读用户
该用户的有效期截止到'2024-02-02'。
sql复制代码
CREATE USER readitralph
WITH PASSWORD 'password'
VALID UNTIL '2024-02-02';