Documenti di Didattica
Documenti di Professioni
Documenti di Cultura
- Study note
By Maggie Zhou Sep, 2008
Preface
This is one of my study note for SQL Main part of this note is from
Head First SQL: Your Brain on SQL -- A Learner's Guide By Lynn Beighley August 2007 Pages: 607 Series: Head First ISBN 10: 0-596-52684-9 | ISBN 13: 9780596526849 This is a great book for beginner, and you will have a lot of fun when you go through this book (trust me, this is not a commercial)
Basic concepts
SQL: /si kw l/, Structured Query Language, RDBMS: Relational DataBase Management Systems SQL Appeared in 1974
MySQL: SQL/PSM
SQL/Persistent Stored Module (as in ISO SQL:2003)
Oracle: PL/SQL
Procedural Language/SQL (based on Ada)
3
MySQL installation
MySQL community Server
Official free version of the MySQL RDBMS
Create (1)
Case insensitive Database
CREATE DATABASE name
Table
CREATE TABLE name ( data_name1 CHAR/CHARACTER(x~256), data_name2 DEC/DECIMAL(x,x), data_name3 INT/INTEGER, data_name4 BLOB, data_name5 DATE, data_name6 DATETIME/TIMESTAMP, data_name7 VARCHAR(x~256) );
Create (2)
Columns / Attributes
Mandatory value
( data_name CHAR(10) NOT NULL, )
INT
Unsigned integer: values in the range 0 to 4294967295 Signed integer: INT(SIGNED) SMALLINT BIGINT MySQL also has: TINYINT, MEDIUMINT
7
CAST
CAST (column, TYPE); Types
CHAR() DATE, DATETIME, TIME DECIMAL SIGNED [INTEGER] UNSIGNED [INTEGER]
CAN
Be included inside the INSERT, SELECT
CANT
DEC to INT TIME, DATE, DATETIEM, CHAR to DEC, or INT
9
10
Maintain
Change database
USE database_name;
Change
Please see from Slides 23
Delete
DROP TABLE table_name;
Only can use on empty table
11
Add data
Insert data
INSERT INTO table_name (column_name1, column_name2,) VALUES (value1, value2,);
For the AUTO_INCREMENT column, can use , instead input value
Select (1)
Show all data & all column
SELECT * FROM table_name;
Select (2)
Show multiple choose conditions
SELECT * FROM table_name WHERE condition1 AND, OR
AND: match all the conditions OR: match only one condition is enough
Condition2;
Comparison operators
=, >, <, >=, <= <> mean not equal
Find NULL
SELECT * FROM table_name WHERE column_name IS NULL;
14
Select (3)
Wide card
SELECT * FROM table_name WHERE column_name LIKE %XX;
% any number of unknown characters _ just only one unknown character
Given Range
SELECT * FROM table_name WHERE column_name BETWEEN xx AND xx;
Given Group
SELECT * FROM table_name WHERE column_name IN (value, value,);
IN NOT IN
Select (4)
NOT conditions
Combine AND, OR, IS with NOT
Right after AND, OR AND NOT IS NOT NULL means WHERE NOT name IS NULL
16
Database design
Steps to design
Pick one thing your table want to describe Make a list of information using the table Break down information into pieces and organizing table
Atomic data
Column with atomic data cant have several value of the same type of data Table with atomic data cant have multiple columns with same type of data
Normal table
Normal table wont have duplicate data With less data to search through
17
18
Primary key
Create
CREATE TABLE table_name (key_name data_type NOT NULL, PRIMARY KEY (key_name) ); OR CREATE TABLE table_name (key_name data_type NOT NULL PRIMARY KEY,
);
Key:
Can not be NULL Must be compact Can not be changed
Auto incrementally
(key_name INT NOT NULL AUTO_INCREMENT PRIMARY KEY, );
Data has same key value wont be accepted The key can be overwritten you still can make own value AUTO-INCREMENT Only one per table, must be INT, cannot be 19 NOT NULL
Show statements
SHOW CREATE TABLE table_name;
Return a CREATE TABLE statement
Delete row
Delete row/rows base on condition
DELETE FROM table_name WHERE condition;
21
Change row
Update row/rows base on condition
UPDATE table_name SET column_name = new value, other changes WHERE column_name = value;
Without condition, you will update all data Update can use simple math:
Can use *, /, +, SET column_name = column_name +1
Modify
Data type or position of existing column
Add
Add new column
Drop
Delete column from table
23
Add column
ADD COLUMN column_name type NOT NULL AUTO_INCREMENT FIRST, (dont forget , ) ADD PRIMARY KEY (column_name); OR ADD COLUMN column_name type AFTER another_column_name;
25
26
Remove AUTO_INCREMENT
ALTER TABLE table_name CHANGE column_name new_column_name new_type; without AUTO_INCREMENT
Just simply without AUTO_INCREMENT After remove AUTO_INCREMENT, then you can drop the PRIMARY KEY, otherwise, will be error
28
RTRIM(string LENGTH(string);
30
Copy
Change all the data in a column
UPDATE table_name SET column_name = new_value;
Copy column
UPDATE table_name SET column_name = source_column_name;
Can use all the string function
31
32
CASE expression can be used with SELECT, INSERT, DELETE and UPDATE
33
Order rules
Non-alphabet Number < text character NULL < Number NULL < alphabet character Uppercase < Lowercase Space < number
34
Descending order
ORDER BY column_name DESC;
Can use DESCRIBE for DESC table_name But can not use DESCENDING
Default order
ASC means default order
35
AVG()
SELECT columns, AVG (column_name1) FROM table_name GROUP BY column_name1;
36
MAX()
SELECT columns, MAX (column_name1) FROM table_name GROUP BY column_name1;
37
SCHEMA
Schema is : A description of the data (columns and tables) in your database, along with any other related objects and the way they all connect Diagram for table design Split the non-atomic field into another table
40
UNIQUE
Not available in MySQL
CHECK
42
CONSTRAINT parent_id_fk
name: parent_table_name + parent_column_name + fk(foreign key)
FOREIGN KEY (child_column_name) REFERENCES parent_table_name (parent_column_name) ) ; book has mistake here
43
Relationships
One-to-one: plain line
Faster queries Isolate column to avoid NULL in main table Make part of data less accessible Put large piece data into a separate table
One-to-many: black arrow line, only one arrow at the end of many Many-to-many: black arrow line, arrows at both ends
Two one-to-many relationships with a junction table in between
44
Junction table
Avoid duplicate data in many-to-many relationship A table step in between two many-tomany tables and simplify the relationship to one-to-many. Contain the two primary key columns of the two related table.
45
46
Dependent column
The A column functionally depend B column, A must change when Bs data is modified Notations
T.x ; T.y
Relational table T, column y is functionally dependent on column x
Table is in 2NF
If it has an artificial primary key and no composite primary key
49
50
INSERT INTO table_name (column_name) SELECT column_name FROM parent_table_name GROUP BY column_name ORDER BY column_name;
51
AS funneling all the output of the SELECT into the new table
52
alias
SQL allow to temporarily give the columns and tables new names Column aliases
SELECT column_name AS column_alias
temporary
Return every row from table_A cross with every row from table_B The column which has more values, the column show up in groups.
55
56
Inner Join
Inner Join combine records from two tables using comparison operator in a condition
Columns only return the matched join rows Inner Join is a Cross Join with some result rows removed by a condition in the query
Inner join identify matching column names Do not need ON conditions
58
Subquery (1)
A query is wrapped within another query
OUTER query INNER query Subquery
Take the result of one query and use it as the input to another query Can be used to
Avoid duplicate data Make queries more dynamic
59
Subquery (2)
Subquery is always a single SELECT statement Subqueries are always inside () parentheses Subqueries do not get their own ; semicolon
One ; semicolon goes at the end of entire query
Subquery (3)
SELECT columns FROM table_A NATURAL JOIN table_B WHERE column_name IN (SELECT column FROM table_C);
Subquery All others are OUTER query
61
Subquery (4)
SELECT columns FROM table_name WHERE condition (subquery) Usually, Subquery return single value, one row from one column where column = (subquery) Subquery return more than one value when using IN where column IN (subquery) Subquery also can use WHERE condition Can use subquery instead the INNER JOIN
Join combine all columns from two tables Subquery can only use the columns from one table
62
Noncorrelated subquery
Correlated subquery is slow Noncorrelated subquery
Subquery stands alone Doesnt reference anything from the outer query
Inner query in no way depends on values from the outer query It can run as a standalone query Noncorrelated subquery with IN, NOT IN
Use IN, NOT IN to test if the values returned in subquery are members of a set(or not)
64
Correlated subquery
Correlated subquery
Inner query relies on the outer query before it can be resolved Use the same alias or correlated name from the outer query
Common use
Find all the rows in the outer query for which no rows exist in a related table EXISTS NOT EXISTS
65
66
Takes all the rows in the Left_table and matches them to rows in the Right_table.
67
Similar with INNER JOIN but not OUTER JOIN gives all the rows whether there is a match with the other table or not
Use NULL value to show no match exists
In LEFT OUTER JOIN, NULL means the Right_table has no value that correspond to the Left_table
Some RDBMS use FULL OUTER JOIN, but not in MySQL, SQL Server or Access
68
Self-join (1)
Self-referencing foreign key
means that it is a key is referencing another field in the same table
The primary key of a table used in that same table for another purpose
The primary key use to describe other attribute of the elements
Join a single table to itself Used to simulate having two tables with exactly same information
In a normalized database, would never have two copies of the same table
69
Self-join (2)
Use different alias to separate the same table act as two tables
SELECT alias1.column, , alias.column, , FROM table_name AS alias1 INNER JOIN Table_name AS alias2 ON alias1.primary_key = alias2.self_referencing_key;
70
Union
Combine the results of queries Combine the results from multiple tables
SELECT column FROM table_A UNION OR UNION ALL
Return every match, including the duplicate values By default, results removed duplicate values
Rules:
Number of columns in each SELECT statement must match Must have same expression and aggregate function in each SELECT statement Order of SELECT statement doesnt matter The data types in the columns need to either same or convertible to each other 71
EXCEPT:
Returns only those values that are in the first query but not in the second query
How about:
SELECT title FROM job_listings ORDER BY salary DESC LIMIT 1;
Self-join
subquery
SELECT f1.name, f2.name AS boss FROM friend f1 INNER JOIN friend f2 ON f1.id = f2.boss;
How about:
SELECT f1.name, (SELECT name FROM friend WHERE f1.boss = id) AS boss FROM friend f1;
73
Subquery
SELECT title FROM job_listings jl INNER JOIN job_current jc ON jl.title = jc.title; SELECT title FROM job_listings WHERE title IN (SELECT title from job_current);
How about:
74
Database management
Defensive database
Avoid entering wrong data Stop concurrent operation on the same data at the same time
CHECK constraints and views both help maintain control when you have multiple users
75
CHECK CONSTRAINT
Constraint
Is a restriction on what you can insert into a column Example: NOT NULL, PRIMARY KEY, FOREIGN KEY, UNIQUE
CHECK
CREATE TABLE table_name ( Column_name type CHECK (column_name IN (F, M))
condition
CHECK constraint restricts what values you can insert into a column
Try to INSERT INTO wrong data will get a error and nothing be inserted
Use the same conditions as a WHERE clause, such as AND, OR, IN, NOT, BETWEEN, but not subquery CHECK doesnt enforce data integrity in MySQL
Can create table with check, but MySQL wont do anything and just ignores it.
76
View (1)
View
Is basically a table that only exists when you use view in query Virtual table
Can turn any query as a SELECT into a view View can do more than SELECT data from tables, also can UPDATE, INSERT, DELETE Benefits
Keep change database structure from breaking the applications that depend on the tables Make easier by simplifying the complex query into a simple command Create view to hide information that isnt needed by the use
77
View (2)
Create a view
CREATE VIEW view_name AS Conditions All the queries you want to do ;
Delete view
DROP VIEW view_name;
Different RDBMSs has different behaviors Best drop views before drop the table it is based on MySQL wont let you drop views without its base table is existing, but you can drop table which has view
Check structure
DESC view_name;
78
View (3)
CHECK OPTION
CREATE VIEW view_name AS WHERE Conditions WITH CHECK OPTION;
Force all inserts and updates to satisfy the WHERE clause in the view
View (4)
Updatable view
An updatable view includes all the NOT NULL columns from the table it references Allow this kind of view to do the INSERT, UPDATE, DELETE due to all the NOT NULL column can be touched via the view
Non-updatable view
doesnt include all the NOT NULL columns Only can do is SELECT
ACID
A: ATOMICITY
All the pieces of transaction must be completed or none of them be completed.
C: CONSISTENCY
Keep database in a consistent state at the end of transaction.
I: ISOLATION
Every transaction has a consistent view of the database regardless of other transaction take place at the same time.
D: DURABILITY
After transaction, the database needs to save the data correctly and protect it from power outages or other threats.
81
Transaction (1)
Transaction is a set of SQL statements to accomplish a single unit of work During a transaction, if all the steps cant be completed without interference, none of them should be completed.
Avoid concurrent problem
82
Transaction (2)
START TRANSACTION;
START TRANSACTION keeps track of all the SQL
COMMIT;
Make the actions permanent
ROLLBACK;
Reverse everything to the way it was before you START TRANSACTION
No change will occur to the database until you COMMIT RDBMS keep record of everything that has been done when you inside a transaction
It cost storage space
83
Storage engines
Make sure your storage engine is either BDB or InnoDB,
BDB, InnoDB are two possible way that support transaction RDBMS can store data behind the scenes.
84
Set password
SET PASSWORD FOR root @ localhost = PASSWORD(password); ORACLE use: ALTER user root IDENTIFIED BY new_password;
Root users user name: root localhost indicates that this is where the SQL software is installed and running localhost is the default value, and it is optional
Remote access
You have to tell the query: IP address, or a hostname instead of localhost.
root@A100.simpleworlf.com
85
86
GRANT (1)
Control exactly what users can do to tables and columns Typical
GRANT SELECT
Can change to INSERT, DELETE, UPDATE
ON table_name TO user_name;
GRANT (2)
Assign ALL privileges
GRANT ALL ON table_name TO user_name;
Allow all permission with SELECT, INSERT, DELETE, UPDATE
GRANT (3)
Specific column: only can used for SELECT
GRANT SELECT (column_name, column_name 2) ON table_name TO user_name
Wildcard: Give the user the privilege for every table in the database
GRANT SELECT ON database_name.* TO user_name
REVOKE (1)
REVOKE privileges
REVOKE SELECT ON table_name FROM user_name; If the unassigned privilege with get an error
Revoke GRANT OPTION privilege: Without remove the privilege on current user, just remove the GRANT OPTION privilege
REVOKE GRANT OPTION ON DELETE ON table_name FROM user_name;
CAN NOT assign this privilege to others any more But, all the user got the privilege from this user, will lose their permission as well
90
REVOKE (2)
CASCADE: Remove the privilege from current user as well as anyone else that current user gave permission to. (usually is default)
REVOKE DELETE ON table_name FROM user_name CASCADE;
RESTRICT: both current user and the sub_user can retain the privilege, the root get an error, if the current user gave any other user this privilege before
REVOKE DELETE ON table_name FROM user_name RESTRICT;
91
REVOKE (3)
If the user get the privilege from different time/people
Different RDBMSs have different response Some will pay attention to where GRANT came from when CASCADE is used Some will ignore it Just check the documentation
Both GRANT, REVOKE can use on VIEW, but be careful with the non-updatable view
92
Role (1)
There is no ROLE in MySQL To give groups the privileges instead of assign them individually Create
CREATE ROLE role_name;
Role (2)
Delete role
DROP ROLE role_name;
Drop a role in use, it also cut related users off from the permissions Revoke role from user
REVOKE role_name FROM user_name;
Role (3)
Allow the roles users to grant this role to anyone else
GRANT role_name TO user_name WITH ADMIN OPTION
CASCADE
REVOKE role_name FROM user_name CASCADE;
RESTRICT
REVOKE role_name FROM user_name RESTRICT;
95
96
Check status
Check current user
SELECT CURRENT_USER;
root@localhost
Check current
SELECT CURRENT_DATE; SELECT CURRENT_TIME;
97
Reserved words
There are bunch of reserved words.
When try to use single-world, you glance through the lists to make sure
SQL has a list of non-reserved words may become reserved in future releases of SQL.
98
Special characters
* () ; , . _ % ! \ + Comparison > < = !> !< <>, != >= <= & | ^ ~
ALL
Before
SELECT columns FROM table_name WHERE column IN (SELECT column FROM table_name);
ALL:
Greater than ALL finds any values larger than the biggest value in the set
SELECT columns FROM table_name WHERE column > ALL (SELECT column FROM table_name);
Less than ALL finds any values smaller than the smallest value in the set
WHERE column < ALL
100
ANY
ANY Greater than ANY finds any values larger than the smallest value in the set
SELECT columns FROM table_name WHERE column >ANY (SELECT column FROM table_name);
Less than ANY finds any values smaller than the largest value in the set
SELECT columns FROM table_name WHERE column < ANY (SELECT column FROM table_name);
101
SOME
Means the things as ANY in standard SQL syntax, and in MySQL . Check the RDBMS to confirm that it works which way
102
Temporary table
Temporary table exists from the time you create it until you drop it, or until the user session ends
Session means from signed in to sign out RDBMS syntax varies greatly with this, please check first CREATE TEMPORARY TABLE table_name ( columns); OR CREATE TEMPORARY TABLE table_name AS SELECT * FROM permanent_table;
103
Numeric functions
ABS(x) ACOS(x) ASIN(x) ATAN(x,y) CELL(x) COS(x) COT(x) EXP(x) FLOOR(x) FORMAT(x,y) LN(x) LOG(x), LOG(x,y) MOD(x,y) PI() POWER(x,y) RADIANS(x) RAND(x) ROUND(x), ROUND(x,y) SIGN(x) SIN(x) SQRT(x) TAN(x) TRUNCATE(x,y)
104
Indexing
Index help RDBMS speed up
If you search the column frequently
Add index
ALTER TABLE table_name ADD INDEX (column_name);
To be continue
105
CocoaMySQL
http://cocoamysql.sourceforge.net/
To be continue
106
PHP/MySQL
PHP help you get data via web PHP code take all date from database and store it in an array
To be continue
107