SQL
目录
CH1
CH4 Select
CH5 Where
CH6 Group by & Order by
CH7 CASE
CH8 Join
CH9 Database Design
CH10 Managing Data
Appendix A/B
Chapter 1
- SQL stands for Structured Query Language
Chapter 4
select
-
use
select
to select columnsselect * from customers
-
use
round(1.0000,2)
to round the dataround(price*1.07,2) as taxed_price
round the number to 2 decimal places
-
use
||
to concatenate columnsselect name, city || ', ' || state as location from customer;
MySQL and some others require using
concat()
func.
Chapter 5
where
-
using
where
on numbersSELECT * FROM station_data WHERE year = 2010;
-
can alse use !=,<> to get but 2010
WHERE year <> 2010
-
Between … and …
WHERE year BETWEEN 2005 and 2010
can also use
and
(but a little verbose)where year>=2005 and year<=2010
-
IN
WHERE MONTH IN (3,6,9,12) WHERE MONTH NOT IN (3,6,9,12)
-
must wrap text in single quotes
-
some more e.p.
WHERE length(report_code) != 6
-
%
&_
%
is any number of characters and_
is any single character
WHERE report_code LIKE 'A%'
-
SQLite expects you to explicitly use 1 for true and 0 for false.
WHERE tornado = 1 AND hail = 1; WHERE tornado AND hail;
WHERE tornado = 0 AND hail = 1; WHERE NOT tornado AND hail;
-
ways to
quary null
- Nulls rarely qualify with anything and almost always get filtered out in a WHERE unless you explicitly handle them. So you have to use an
OR
to include nulls:
WHERE precipitation IS NULL OR precipitation <= 0.5;
- Nulls rarely qualify with anything and almost always get filtered out in a WHERE unless you explicitly handle them. So you have to use an
-
coalesce()
- convert null to 0:
WHERE coalesce(precipitation, 0) <= 0.5;
- a coalesce() can be used in the SELECT statement too, and not just the WHERE
SELECT report_code, coalesce(precipitation, 0) as rainfall FROM station_data;
Chapter 6
group by
&order by
-
order by
SELECT year, month, COUNT(*) AS record_count FROM station_data WHERE tornado = 1 GROUP BY year, month
-
order by
ORDER BY year, month
-
Aggregate Functions
SELECT month, AVG(temp) as avg_temp FROM station_data WHERE year >= 2000 GROUP BY month
-
having
SELECT year, SUM(precipitation) as total_precipitation FROM station_data GROUP BY year HAVING SUM(precipitation) > 30
HAVING is the aggregated equivalent to WHERE
-
distinct
SELECT DISTINCT station_number FROM station_data
Chapter 7
CASE
Statements
-
case
- You start a CASE statement with the word CASE and conclude it with an END.
- Between those keywords, you specify each condition with a WHEN [condition] THEN [value]
- have a catch-all value to default to if none of the conditions were met
SELECT report_code, year, month, day, wind_speed, CASE WHEN wind_speed >= 40 THEN 'HIGH' WHEN wind_speed >= 30 AND wind_speed < 40 THEN 'MODERATE' ELSE 'LOW' END as wind_severity FROM station_data
SELECT year, CASE WHEN wind_speed >= 40 THEN 'HIGH' WHEN wind_speed >= 30 THEN 'MODERATE' ELSE 'LOW' END as wind_severity, COUNT(*) as record_count FROM station_data GROUP BY 1, 2
-
The “Zero/Null” CASE Trick
SELECT year, month, SUM(CASE WHEN tornado = 1 THEN precipitation ELSE 0 END) as tornado_precipitation, SUM(CASE WHEN tornado = 0 THEN precipitation ELSE 0 END) as non_tornado_precipitation FROM station_data GROUP BY year, month
Chapter 8
Join
-
inner join
- With an INNER JOIN, any records that do not have a common joined value in both tables will be excluded.
SELECT CUSTOMER.CUSTOMER_ID, NAME, STREET_ADDRESS, CITY, STATE, ZIP, ORDER_DATE, SHIP_DATE, ORDER_ID, PRODUCT_ID, ORDER_QTY FROM CUSTOMER INNER JOIN CUSTOMER_ORDER ON CUSTOMER.CUSTOMER_ID = CUSTOMER_ORDER.CUSTOMER_ID
-
left join
- If we want to include all records from the CUSTOMER table, we can accomplish this with a LEFT JOIN.
- The LEFT JOIN will include all records on the “left” table, even if they have nothing to join to on the “right” table (which will be null)
SELECT CUSTOMER.CUSTOMER_ID, NAME, STREET_ADDRESS, CITY, STATE, ZIP, ORDER_DATE, SHIP_DATE, ORDER_ID, PRODUCT_ID, ORDER_QTY FROM CUSTOMER left JOIN CUSTOMER_ORDER ON CUSTOMER.CUSTOMER_ID = CUSTOMER_ORDER.CUSTOMER_ID
-
Grouping JOINs
SELECT CUSTOMER.CUSTOMER_ID, NAME AS CUSTOMER_NAME, sum(ORDER_QTY * PRICE) as TOTAL_REVENUE FROM CUSTOMER_ORDER INNER JOIN CUSTOMER ON CUSTOMER.CUSTOMER_ID = CUSTOMER_ORDER.CUSTOMER_ID INNER JOIN PRODUCT ON CUSTOMER_ORDER.PRODUCT_ID = PRODUCT.PRODUCT_ID GROUP BY 1,2
Chapter 9
Database Design
-
Design questions
- What are the business requirements?
- What tables will I need to fulfill those requirements?
- What columns will each table contain?
- How will the tables be normalized?
- What will their parent/child relationships be?
Populating data should be part of the planning process too. If the data is not maintainable and kept up to date, then the design has already failed.
-
Data questions
- How much data will be populated into these tables?
- Who/what will populate the data into these tables?
- Where will the data come from?
- Do we need processes to automatically populate the tables?
-
Security questions
- Who should have access to this database?
- Who should have access to which tables? Read-only access? Write access?
- Is this database critical to business operations?
- What backup plans do we have in the event of disaster/failure?
- Should changes to tables be logged?
- If the database is used for websites or web applications, is it secure?
-
primary key
- if you specified primary key on the two fields , you can never have two records with the same combination
- No duplicates are allowed
-
foreign key
- a foreign key does not enforce uniqueness, as it is the “many” in a “one-to-many” relationship.
-
creat table
CREATE TABLE COMPANY ( COMPANY_ID INTEGER PRIMARY KEY AUTOINCREMENT, NAME VARCHAR(30) NOT NULL, DESCRIPTION VARCHAR(60), PRIMARY_CONTACT_ID INTEGER NOT NULL );
column constraints: PRIMARY KEY, FOREIGN KEY, NOT NULL, AUTOINCREMENT, and DEFAULT, etc
-
foreign key
- foreign key in a child table isntied to the primary key of a parent table
-
Creating Views
CREATE VIEW [view_name] AS [a SELECT query]
Chapter 10
Managing Data
-
multiple
insert
INSERT INTO ATTENDEE (FIRST_NAME, LAST_NAME, PHONE, EMAIL, VIP) VALUES ('Jon', 'Skeeter',4802185842,'john.skeeter@rex.net', 1), ('Sam','Scala',2156783401,'sam.scala@gmail.com', 0), ('Brittany','Fisher',5932857296,'brittany.fisher@outlook.com', 0)
-
migrate data from one table to another
INSERT INTO ATTENDEE (FIRST_NAME, LAST_NAME, PHONE, EMAIL) SELECT FIRST_NAME, LAST_NAME, PHONE, EMAIL FROM SOME_OTHER_TABLE
-
delete
DELETE FROM ATTENDEE WHERE PHONE IS NULL AND EMAIL IS NULL
- Executing that query gives us a preview of what records will be deleted:
SELECT * FROM ATTENDEE WHERE PHONE IS NULL AND EMAIL IS NULL
-
TRUNCATE TABLE
TRUNCATE TABLE ATTENDEE
not used
in SQLite- allow the database engine to reset the autoincrements for any primary keys as well as any other constraint behaviors. It also allows it to make some optimizations behind the scenes to reset the table.
sqlite
allow some similar optimizations when you run aDELETE without a WHERE
.
-
update
- The UPDATE modifies existing records.
UPDATE ATTENDEE SET EMAIL = UPPER(EMAIL); UPDATE ATTENDEE SET FIRST_NAME = UPPER(FIRST_NAME), LAST_NAME = UPPER(LAST_NAME); UPDATE ATTENDEE SET VIP = 1 WHERE ATTENDEE_ID IN (3,4);
-
drop
- remove a table altogether
DROP TABLE MY_UNWANTED_TABLE
Appendix A
Operators and Functions
-
Date and Time Functions
SELECT DATE('now'); SELECT DATE('now','-1 day');
SELECT TIME('now') SELECT TIME('16:31','+1 minute')
APPENDIX B
Supplementary Topics
-
Further Topics of Interest
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-INkluA3B-1617552209580)(pic/Further%20Topics%20of%20Interest.jpg)]
-
index
CREATE INDEX price_index ON PRODUCT(price); DROP INDEX price_index;
- We name the index price_index and we apply it on the PRODUCT table, and in parentheses we specify it on the price column.
- indexes should only be used for very
large tables
that havenoticeable performance
issues withSELECT
statements. You should avoid using indexes onsmall tables
as the overhead will actuallyslow performance down
. You should also avoid using indexes on tables thatupdate heavily and frequently
.
-
Transactions
BEGIN TRANSACTION;
orBEGIN;
:begin the transacton until ‘commit’ or ‘ROLLBACK’COMMIT
: save the changeROLLBACK
: cancel the change
BEGIN; DELETE FROM COMPANY WHERE AGE = 25; ROLLBACK;
BEGIN; DELETE FROM COMPANY WHERE AGE = 25; COMMIT;