0% found this document useful (0 votes)
5 views

DB

The document provides a comprehensive overview of SQL commands and database management concepts, including data types, table creation, data manipulation, and query syntax. It covers various SQL operations such as SELECT, INSERT, UPDATE, DELETE, and JOIN, along with concepts like normalization, functional dependencies, and integrity constraints. Additionally, it discusses aggregation functions, subqueries, and the use of views and indexes in databases.

Uploaded by

sr01lok20230501
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views

DB

The document provides a comprehensive overview of SQL commands and database management concepts, including data types, table creation, data manipulation, and query syntax. It covers various SQL operations such as SELECT, INSERT, UPDATE, DELETE, and JOIN, along with concepts like normalization, functional dependencies, and integrity constraints. Additionally, it discusses aggregation functions, subqueries, and the use of views and indexes in databases.

Uploaded by

sr01lok20230501
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 5

ABSOLUTE (ABS), AVG, INT, MAX, MIN, SUM, COUNT

ASC, AT, CHAR (CHR), CHAR_LENGTH (LEN), LOWER, TRIM, SPACE, SUBSTRING
(SUBSTR/MID), UPPER, VALUE (VAL)
DATE, DAY, MONTH, YEAR
ADD, ALL, ALTER, ANY, AS, ASC, BETWEEN, BY, CREATE, DELETE, DESC, DISTINCT,
DROP, EXISTS, FROM, GROUP, HAVING, IN, INDEX, INNER JOIN, INSERT, INTEGER,
INTERSECT, INTO, LEFT [OUTER] JOIN, LIKE, MINUS, NULL, RIGHT [OUTER] JOIN,
FULL [OUTER] JOIN, ON, ORDER, SELECT, SET, TABLE, TO, UNION, UNIQUE,
UPDATE, VALUES, VIEW, WHERE

BOOL: 0 is FALSE, 1 is TRUE

DATE, TIME: like character, need '', eg, '2025-12-31'

NOT > AND > NO

CREATE TABLE EVENT (


EID CHAR(5),
ENAME VARCHAR(255),
EDATE DATE,
FEE FLOAT,,
FINISHED BOOL
)

INSERT INTO STUDENT (CNO, NAME, SID, CLASS) VALUES (28, 'Eva', '03505', '1B') # can be any order
TABLE FIELD VALUE

INSERT INTO STUDENT (CNO, NAME, SID, CLASS) VALUES


(28, 'Eva', '03505', '1B'),
(29, 'Eva', '03505', '1B')

nothing inserted -> NULL value

SELECY NAME, CNO FROM STUDENT WHERE CLASS = '1B' ORDER BY CNO DESC

SELECY NAME, CNO FROM STUDENT WHERE CLASS = '1B' ORDER BY CNO # default order is ASC

SELECT DISTINCT CLASS FROM STUDENT # remove duplicate results

UPDATE STUDENT SET NAME = 'Bob', CLASS = '1B' WHERE SID = '03517' # UPDATE ... SET

DELETE FROM STUDENT WHERE CLASS = '1B' # DELETE FROM

DROP TABLE STUDENT # delete sepecific table

DROP DATABASE SCHOOL_C # delete sepecific DATABASE

CREATE TABLE EVENT (


EID CHAR(5) PRIMARY KEY,
ENAME VARCHAR(255)
)

CREATE TBALE STUDENT (


NAME VARCHAR(40),
CLASS CHAR(2),
CNO INT,
PRIMARY KEY(CLASS, CNO)
)
CREATE TBALE STUDENT (
SID CHAR(5) PRIMARY KEY,
NAME VARCHAR(40),
CLASS CHAR(2),
FOREIGN KEY (CLASS) REFERENCES CLASSLIST(CLASSNAME)
) # STUDENT is host table, CLASS is foreign key in host table, CLASSLIST is parent table, CLASSNAME is primary key in parent
table

CREATE TABLE STUDENT (


SID CHAR(5) PRIMARY KEY,
NAME VARCHAR(40) NOT NULL DEFAULT 'to be assigned',
CLASS CHAR(2),
CNO INT,
UNIQUE(CLASS, CNO),
SCORE INT,
CHECK (SCORE >= 0)
) # NOT NULL. UNIQUE(), DEFAULT ..., CHECK (...)

ALTER TABLE old_name RENAME new_name # renaming table

ALTER TABLE STUDENT RENAME old_name to new_name # renaming filed

ALTER TABLE STUDENT MODIFY SID INT # change data type of SID to INT

ALTER TABLE STUDENT ADD NAME VARCHAR(40) DEFAULT 'to be assigned' # adding filed

ALTER TABLE STUDENT DROP CNO # dropping filed

ALTER TABLE STUDENT ADD PRIMARY KEY (SID)

ALTER TABLE STUDENT MODIFY SID CHAR(5) PRIMARY KEY # input the data tyoe is needed

ALTER TABLE STUDENT DROP PRIMARY KEY

ALTER TABLE STUDENT ADD FOREIGN KEY (CLASS) REFERENCES CLASSLIST(CLASS)

ALTER TABLE STUDENT DROP FOREIGN KEY cn # cn is constraint name which will be given

ALTER TABLE STUDENT ADD field data_type [constraints]

ALTER TABLE STUDENT ADD constraint

ALTER TABLE STUDENT MODIFY field data_type [constraints]

ALTER TABLE STUDENT DROP field

ALTER TABLE STUDENT DROP constraint

SELECT NAME, SCORE_1 * 0.4 + SCORE_2 * 0.6 AS FINAL FROM STUDENT

SELECT SID, NAME FROM STUDENT WHERE CLASS IN ('1A', '1B', '2C')

SELECT SID, NAME FROM STUDENT WHERE DOB BETWEEN '2013-08-03' AND '2013-09-22'

wildcard '%': it means there may be any number of characters


wildcard '_': it means there is exactly one character
SELECT SID, NAME from STUDENT WHERE NAME LIKE '%an%' # result: Hans. Jean, Anna

SELECT SID, NAME FROM STUDENT WHERE SCORE1 IS NULL / IS NOT NULL

SELECT LENGTH('A cat!') # result: 6

SELECT MID('Luggage', 4, 3) # result: 'gag', (<string>, <start_num>, <num_char>)

SELECT UPPER('A Cat!') # result: 'A CAT!'

SELECT LOWER('A Cat!') # result: 'a cat!'

SELECT TRIM(' A Cat! ') # result: 'A cat!' (removes all spaces from the start and the end of <string)

SPACE(<num>) # Return <num> whitespaces

SELECT YEAR('2023-05-06') # result: 2023

SELECT MONTH('2023-05-06') # result: 5

SELECT DAY('2023-05-06') # result: 6

Aggregation functions

SELECT COUNT(*) FROM STUDENT # count total number of records, include NULL

MAX(SCORE), MIN(SCORE), SUM(SCORE), AVG(SCORE)

SELECT CLASS, COUNT(*) FROM STUDENT


WHERE Score >= 60
GROUP BY CLASS
HAVING COUNT(*) > 1
ORDER BY CLASS

SELECT CLASS, SEX, COUNT(*) FROM STUDENT GOURP BY CLASS, SEX ORDER BY CLASS

SELECT NAME, SCORE FROM STUDENT WHERE SCORE = (SELECT MAX(SCORE) FROM STUDENT) # subquery

SELECT * FROM STUDENT INNER JOIN CLUB ON STUDENT.CID = CLUB.CID


/ SELECT * FROM STUDENT, CLUB WHERE STUDENT.CID = CLUB.CID # equi-join, which = inner join

SELECT * FROM STUDENT FULL JOIN CLUB WHERE STUDENT.CID = CLUB.CID

SELECT SID, s.NAME, CLASS, c.NAME, ROOM


FROM STUDENT s INNER JOIN CLUB c ON s.CID = c.CID

SELECT * FROM STUDENT NATURAL JOIN CLUB # natural join, which = inner join, but join automatically by using the only pair of
same field name

SELECT s1.NAME, s2.NAME AS Monitor_NAME FROM STUDENT s1 INNER JOIN STUDENT s2 ON s1.Monitor_SID = s2.SID

SELECT s.SID, s.NAME, c.NAME AS CLUBNAME FROM STUDENT s


LEFT JOIN SC on SC.SID = s.SID
LEFT JOIN CLUB c ON c.CID = SC.CID

SELECT * FROM L CROSS JOIN R ORDER BY LID, RID

SELECT NAME FROM STUDENT WHERE SID NOT IN (SELECT SID FROM SC)

INSERT INTO STUDENT (SELECT ID, NAME FROM STUDENT2)


SELECT NAME, SCORE FROM STUDENT s WHERE NOT EXISTS (SELECT 1 FROM STUDENT2 s2 WHERE s.SCORE =
s2.SCORE) # cannot be change to not in

SELECT NAME FROM STUDENT WHERE CLASS = ANY (SELECT CALSS FROM STUDENT2) # must follow a subquery

IN and EXISTS and Any and All p144 about NOT

SELECT NAME FROM STUDENT WHERE CLASS > ALL (SELECT CALSS FROM STUDENT2) # must follow a subquery

= ALL != IN
<> ALL = NOT IN

select * from Table2 h where (select count(c.ID) from Table1 c where HID = h.ID) > capacity

select h.NAME FROM CAT c, HOTEL h where HID = h.ID group by HID HAVING COUNT(c.ID) > AVG(capacity)

SELECT SID FROM STUDENT1 UNION SELECT STUDENT_ID FROM STUDENT2 ORDER BY SID
# fieldname from the 2nd table are not carried to the combined result
# duplicated rows(completely identical in all rows) are removed

UNION ALL # better performance

INTERSECT # should be completely identical in all rows

EXCEPT # should be completely identical in all rows

SELECT SID FROM S1 INTERSECT


SELECTSID FROM S2 INTERSECT
SELECTSID FROM S3

CREATE VIEW SCORESHEET AS


SELECT ...

DROP VIEW SCORESHEET

SELECT * FROM SCORESHEET

CREATE OR REPLACE VIEW COUNTCLUB AS


SELECT s.SID, COUNT(CID) AS CLUBNAME FROM STUDENT s LEFT JOIN SC on s.SID = SC.sid GROUP BY SID
# to modify an existing view

MAX(COUNT(*)) # error, grammar limit, Aggregation cannot include Aggregation

SHOW CREATE TABLE

CREATE INDEX SNAME ON STUDENT (NAME) # <index name>, <table name>, <dield to be indexed>
# normally, the name of the index is used only when dropping the index

ALTER TABLE STUDENT DROP INDEX SNAME # SNAME is the index name

A schema for a table: STUDENT(SID, NAMEm CLASS) # primary key should be underlined

candidate key # cannot be NULL

composite key # inseparable candidate key pair

primary key: only one, one of the candidate keys


entity integrity:
a table must hae its primary key defined; and
the primary key for each records is unique and not NULL

violate e. i.:
no primary key
duplicate primary key
primary key is null

referential integrity:
the references of foreign keys in a table are valid

violate r. i.:
insert/update record with foreign key cannot be found in the referenced table
delete/update the primary key in the referenced table

domain integrity:
value of an attribute must fall within a reasonable domain

rollback

| must
O optional

cardinality

one to one: one table


one to many: different tables

anomaly / anomalies

update anomaly occurs when a database with data redundancy fails to maintain data consistency after an update is made

insertion anomaly refers to the inability to insert data of one entity type without having the data of another entity type

deletion anomaly refers to the loss of data of one entity type when deleting the data of another entity type

Functional dependency exists between 2 sets of attributes when the values of 1 set can be uniquely determined by the values of
another set

Full functional dependency: all attributes that are not primary key are dependent on the primary key

Partial functional dependency: some attributes that are not primary key are dependent on part of the primary key
# only exists when the primary key of a table is a composite key

Transitive functional dependency: some non-primary key attributes are dependent on other non-primary ket attributes

Normalisation

First Normal Form(1NF):


no multiple values, and no repeating attributes

Second Normal Form(2NF):


no any partial functional dependency

Third Normal Form(3NF):


no any transitive functional dependency

Denormalisation

You might also like