Lesson3c-subquery
Lesson3c-subquery
STUDENTS
STUD_NUM STUD_NAME GRADE
206 Juliet Styles 94
112 Drew Bieber 92
211 Xander Lee 94
210 Chris Stewart 98
207 Harry Brown 65
208 Andi Sparks 83
209 Sony Yang 70
STUDENTS2
STUD_NUM STUD_NAME GRADE
111 LuHan 98
112 Drew Bievbber 92
SUBQUERY: INSERT
INSERT INTO students2(STUD_NUM,STUD_NAME,grade)
(SELECT STUD_NUM,STUD_NAME,grade FROM students
WHERE STUD_NAME=‘Xander Lee’);
Note:
Insert records where data will be coming from another
table.
Insertion of record in a table that requires the same
information.
SUBQUERY: RETRIEVE ROWS
Syntax:
SELECT column_name(s)
FROM table_name
WHERE column_name = (SELECT column_name
FROM table_name WHERE column_name
condition):
SUBQUERY: RETRIEVE ROWS
SELECT STUD_NUM,STUD_NAME
FROM students
WHERE STUD_NAME = ( SELECT STUD_NAME
FROM students2 WHERE STUD_NAME = ‘Xander Lee’);
Note:
The same record will be displayed if the condition on the where
clause has been met.
SUBQUERY: UPDATE
Syntax:
UPDATE table_name
SET column_name = value
WHERE column_name = (SELECT column_name
FROM table_name
WHERE column_name = value):
SUBQUERY: UPDATE
UPDATE Student2
SET STUD_NAME = ‘Drew Bieber’
WHERE STUD_NUM = (SELECT STUD_NUM
FROM students
WHERE STUD_NUM = ‘112’);
Note:
The modified record will be displayed if the condition in the where
clause has been met.
SUBQUERY: DELETE ROWS
Syntax:
Note:
The existing record will be removed if the condition in the where
clause has been met.
CONSTRAINT
S
CONSTRAINTS
Are used to limit the data type that can be inserted
into a table.
1. Primary key
2. Foreign key
3. Unique key
4. Default
5. Not Null
PRIMARY KEY CONSTRAINT
The primary key constraint will help you to easily
identify uniquely each record in a database table.
Syntax:
ALTER TABLE tb_name
ADD PRIMARY KEY(column_name);
Syntax:
ALTER TABLE tb_name
DROP PRIMARY KEY;
Orders
CREATE TABLE persons(P_id int(5) not null, lastname varchar(20) not null,firstname
varchar(20) not null,address varchar(20) not null, city varchar(20) not null, PRIMARY
KEY(P_id));
FOREIGN KEY CONSTRAINT:
CREATING A TABLE
Syntax:
Syntax:
ALTER TABLE tb_name
ADD FOREIGN KEY(column_name)
REFERENCES tb_name(column_name);
Syntax:
ALTER TABLE tb_name
DROP FOREIGN KEY(column_name)
Syntax:
ALTER TABLE table_name
ADD CHECK(column_name constraint);
If a table has 1,000 rows, this atleast 100 times faster than
reading sequentially. If you need to access most of the rows,
it is faster to read sequentially because this minimizes disk
seeks.
INDEX : CREATE
Syntax:
SHOW INDEX
FROM table_name;
SHOW INDEX
FROM tb_employees;
INDEX : DROP
Syntax:
transaction.
All changes will be committed at the end of the
statement execution.
AUTOCOMMIT OFF
Can be started wit “SET AUTOCOMMIT=0” command
In this mode, multiple SQL statements can be grouped
Syntax:
SELECT @@AUTOCOMMIT FROM DUAL;