1. Create a student database, which contains the data table student
student(sno,sname,sex,age,class).
Among them, the description of each column is as follows:
sno: student ID, string
sname: name, string
sex: gender, string
age: age, integer
class: class number, integer
sql statement:
create table student(
sno varchar(255) primary key,//设为主键
sname varchar(255),
sex varchar(10),
age int,
class int
);
2. Add
- Li Si, female, 121531001, 16 years old, class 10
- Li Si, male, 121530802, class 8
- Li Si, 121530806, class 8
sql statement:
insert into student values (121531001 , '李四' , '女' , '16' , '10'),
(121530802 , '李斯' , '男' , null ,'8'),
(121530806 , '李四' , ' ' , null, '8');
Insert some fields:
insert into student(sno,sname,) values (121531001 , '李四' );
note:
- If you add a blank value, please fill in
null
- Both insert date and string
''
3. Modify
1. Change the age of
Li Si to 17 2.
Change Li Si’s gender to female and age to 18 3. Change Li Si’s student ID to 121530802
sql statement:
update student set age = 18,sno=121530802 where sname='李四';
update student set sex='女',age=18 where sname='李斯';
4. Delete
Delete the information of the student whose student ID is 121530802
sql statement:
delete from student where sno=121530802;
5. General query
- Ascending:
select sname,sex from student order by sno;
- descending sort:
select * from student order by sno desc;
- Remove duplicate lines:
select distinct sname from student;
- Limit the number of fixed rows:
select top 5 sname from student order by birthday;
- Query all different ages
- Query the names and ages of all students under the age of 18
- Query the names and ages of students between 20 and 23 years old (including 20 and 23 years old)
- Query the names of students in class 3 under the age of 20
- Query the name and gender of students in Class 1, Class 2 and Class 5
sql statement:
select distinct age from student;
select sname,age from student where age<18;
select sname,age from student where age between 20 and 23;
select sname from student where age < 20 and class=3;
select sname,sex from student where class in (1,2,5);
6. Advanced query
- Query the names of all students who are not surnamed Liu
- Query the name and student ID of the student whose name contains "Yang"
- Query the maximum and minimum ages of students
- Query the average age of students
sql statement:
select * from student where sname not like '刘%' ;
select sname,sno from student where sname like '_阳';
select max(age),min(age) from student;
select avg(age) from student;
Common wildcards in sql are :
1. %
Replace 0 or more characters;
2. _
Replace one character;