Notes for getting started with SQL

foreword

        I started to learn the database, as the title, this blog is my study notes for getting started with SQL. There is not much grammar, but more about the use of some functions, that is, it is mainly to directly write codes, not to talk about theoretical things. So this blog is really just notes, not an explanation.

content

        First, install a SQL editor , I am using SQLserver : SQLsever installation tutorial

        Then there is the practice website : SQL practice website (39 questions in the introductory chapter, which can be solved in one day if you are a liver) (the order of this note is written in the order of the questions)

What needs to be explained in advance is that SQL is not case-sensitive, as long as the words are not wrong, I personally prefer to use lowercase.

        The following is the official content

        Create a table : This is the first table I created based on the first question (I later found out that the original question does not require me to create a table), this is the learning link

create table user_profile(/*user_profile是表名*/
	id char(8),
	device_id char(8),
	gender char(8),
	age int,
	university char(20),
	province char (20),
)

insert data into table , learn link

INSERT INTO user_profile VALUES(1,2138,'male',21,'北京大学','BeiJing');
INSERT INTO user_profile VALUES(2,3214,'male',null,'复旦大学','Shanghai');
INSERT INTO user_profile VALUES(3,6543,'female',20,'北京大学','BeiJing');
INSERT INTO user_profile VALUES(4,2315,'female',23,'浙江大学','ZheJiang');
INSERT INTO user_profile VALUES(5,5432,'male',25,'山东大学','Shandong');

 Drop a table , learn link

         drop table [table name]

Query a table: select*from [table name]

Query specified columns: select [field name], ... , [field name] from [table name]

         Between select and from is the field name, that is, the column name

Perform deduplication query on a column in the table (without changing the original table):

        select [field name] from [table name] group by [field name] 

        group by [field name] is a grouping statement, and there can be multiple basis for grouping

Output the first few lines of the table:
        select top n *from [table name] (SQLserver supports top, but not limit)
or
        select *from [table name] limit 0,n

Or
        select *from [table name] limit n
        (you only need to change the * number to the name of a certain column to output the first few rows of a certain column)


Modify the name of a column in the table:
        exec sp_rename '[table name].[old field name]','[new field name]','column'

Change the name of a column in the table when outputting (but the name of the column in the original table remains unchanged, use as to rename the header) :
        select top 2 [field name] as [new field name] from [table name] (SQLserver Applicable in )
or
        select [field name] as [new field name] from [table name] (when used in SQLserver, an error will be reported)

        Note: The as statement can also be used for the table name, which is much more convenient when the table name is too long.

Query the corresponding row by a certain value: (multiple columns can be output) learning link

        select [field name] from [table name] where [field name]='xxx'

        Example: select device_id,university from user_profile where university='Peking University'

Query the corresponding row by being greater than a certain value: (the code is: output student information whose age is greater than 24)
        select device_id,gender,age,university from user_profile where age>24

Query rows within a certain value range:
        select device_id,gender,age from user_profile where age>=20 and age<=23
or
        select device_id,gender,age from user_profile where age between 20 and 23

        Note: The and or statement in SQL is the same as python: and (and), or (or)

Query other line information except a certain value:
       Example: select device_id,gender,age,university from user_profile where university != 'Fudan University'

Filter rows whose value is null: (This example is to filter rows whose age is null)
        select device_id,gender,age,university from user_profile where age is not NULL

Query the row with a certain value among several values: (Example is to query the information of classmates whose schools are Peking University, Fudan University, and Shanda University)
        select device_id,gender,age,university from user_profile
        where university in ('Peking University','Fudan University' ,'Shan Dong University')

Query the row containing a certain field in a certain value: (Example is to query the row containing 'Beijing' in the school)
        select device_id,gender,age,university from user_profile
        where university like '%Beijing%'

       Note: like statement learning link and wildcard learning link


Output the maximum and minimum values ​​of a value:
        select max([field name]) from [table name]
        select min([field name]) from [table name]

        Note: max() min() can also be used for char type, or text type, the highest or lowest value in alphabetical order will be obtained, and null (empty value) will not be recorded

Count the number of all records :
        select count (*) from [table name]
Count the number of a column: (excluding null) (example is to find the number of males in the table)
        select count(gender) from user_profile where gender=' male'
counts the number of unique columns:
        select count(distinst [field name]) from [table name]

        The keyword distinct is used to return unique and different values
​​to count how many times a value in a column is repeated: (example is to query how many people are of each age)
        select age count(1) as age from user_profile group by age

Calculate the average value of a field:
        select avg([field name]) as [new field name] from [table name]

round() function:
        used to round the numeric field to the specified number of decimal places: round ([field name], number of digits)

The difference between where and having:

        "Where" is a constraint statement. Use Where to constrain the data from the database.
        Where works before the result is returned, and aggregate functions cannot be used in Where.

        "Having" is a filtering statement, which is a filtering operation on the query results after the query returns the result set, and
        aggregate functions can be used in Having. Aggregation functions refer to functions such as max, avg, count, and round

Sort the table by a certain value
        order by sal (column name) (default ascending order)
        order by sal desc (add desc to descending order)
        When there are multiple fields behind order by, first sort by the previous field, and then by the latter field sort

Association table: ( learn the difference between left join, inner join, and right join )

        Associating two tables:
                can be associated through inner join,
                inner join table name on table name.same element = table name.same element

        Associate 3 tables:
                from (table 1 inner join table 2 on table 1. field number = table 2. field number)
                inner join table 3 on table 1. field number = table 3. field number

Statements that do not deduplicate the output: union all (multiple parallel select statements can be used as one output, and redundant table headers will not be output)

When judging that a value is null, you should use is instead of the equal sign =


Conditional function case when usage: learning link
        1. Simple function 
        case [col_name] when [value1] then [result1]…else [default] end
        2. Search function 
        case when [expr] then [result1]…else [default] end( and can be used in when expressions)

Commonly used date functions
        year (column name), month (column name), day (column name), you can get the year, month and day in the table respectively
or
        date_format (column name, '%y') as year
        date_format (column name, '% m') as month
        date_format(column name, '%d') as day
        Get the year, month, day,
        and get the current time: now() function: You can get the year, month, day, hour, minute, and second

interval statement: Learning links
        are commonly used in date_add() and date_sub() functions, and are often used for addition and subtraction of time
 

Function for intercepting strings: substring_index(), learning link
        usage rules:
        substring_index ("string to be intercepted useful part", "characters for intercepting data based on",
        position N of intercepted characters)
        substring_index(()) can be nested intercept

Query the minimum value (or maximum value) of a field:
        select * from [table name] where [field name] in ( select min([field name])from [table name] )
or:
        select * from [table name] order by [field name] asc limit 0,1

The difference between sum and count functions: learning link
        sum() is used for summing, and count() is used for counting the number of rows.
        If the sum() column value is empty, it will not be calculated, and if count() is empty, it will be considered that there is no such row.
        When sum() is empty, the return result is null

epilogue

        After I finished writing, I realized that my writing was disorganized, without typesetting and classification, and it was basically useless to most people. It was regarded as a garbage blog. In the future, those who write blogs should first consider whether they can help everyone.

        In case, someone really reads and finds an error, please point it out! grateful!

Guess you like

Origin blog.csdn.net/xiexieyuchen/article/details/123306079