0% found this document useful (0 votes)
28 views55 pages

MySQL Subqueries and Constraints Guide

The document provides a comprehensive overview of SQL subqueries, constraints, indexes, views, and transaction management in MySQL. It includes syntax and examples for inserting, retrieving, updating, and deleting records using subqueries, as well as defining various constraints like primary keys, foreign keys, and check constraints. Additionally, it explains how to create and manage indexes and views, along with transaction modes and their implications.

Uploaded by

razel gicale
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPT, PDF, TXT or read online on Scribd

Topics covered

  • Data Validation,
  • Database Operations,
  • Indexes,
  • Autocommit,
  • Data Access,
  • Transaction Management,
  • Update Statement,
  • Record Insertion,
  • Data Manipulation,
  • Transaction Control
0% found this document useful (0 votes)
28 views55 pages

MySQL Subqueries and Constraints Guide

The document provides a comprehensive overview of SQL subqueries, constraints, indexes, views, and transaction management in MySQL. It includes syntax and examples for inserting, retrieving, updating, and deleting records using subqueries, as well as defining various constraints like primary keys, foreign keys, and check constraints. Additionally, it explains how to create and manage indexes and views, along with transaction modes and their implications.

Uploaded by

razel gicale
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPT, PDF, TXT or read online on Scribd

Topics covered

  • Data Validation,
  • Database Operations,
  • Indexes,
  • Autocommit,
  • Data Access,
  • Transaction Management,
  • Update Statement,
  • Record Insertion,
  • Data Manipulation,
  • Transaction Control

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:

DELETE FROM table_name


WHERE column_name = (SELECT column_name
FROM table_name
WHERE column_name = value):
SUBQUERY: DELETE ROWS
DELETE FROM students
WHERE STUD_NUM = (SELECT STUD_NUM
FROM students2
WHERE STUD_NUM = ‘112’);

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.

 With constraints, maintaining consistency of data


will be attained including:

1. insertion of required fields


2. identification of unique records through the keys
3. By default a column can hold NULL values.
CONSTRAINTS
 The following are the available constraints in MySQL:

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.

 Primary key must contain only unique values.

 The column that is assigned to hold primary key


values must not contain null NULL values.

 Each table must have a primary key.

 Each table must have only one(1) primary key.


PRIMARY KEY CONSTRAINT:
CREATING A TABLE
Syntax:

CREATE TABLE tb_name(column_name1 type(length)


constraint, ... PRIMARY KEY(column_name));

CREATE TABLE tb_studentinfo (stud_id int(20) not null auto_increment, lastname


varchar(50) not null, firstname varchar(50) not null, middlename varchar(50) not null,
course varchar(20) not null, PRIMARY KEY(stud_id));

See the result by using describe


PRIMARY KEY CONSTRAINT:
ALTER TABLE
 Add a PRIMARY KEY constraint in a table that is
created already.

Syntax:
ALTER TABLE tb_name
ADD PRIMARY KEY(column_name);

ALTER TABLE tb_studentsinfo


ADD PRIMARY KEY(stud_id);
PRIMARY KEY CONSTRAINT:
DROP
 To delete the PRIMARY KEY constraint in a
particular table.

Syntax:
ALTER TABLE tb_name
DROP PRIMARY KEY;

ALTER TABLE tb_studentinfo


DROP PRIMARY KEY;

(can’t drop primary key if the table is not empty)


FOREIGN KEY CONSTRAINT
 The FOREIGN KEY constraint in a particular table
points the PRIMARY KEY in another table.

 Values must match the PRIMARY KEY of another table.


FOREIGN KEY CONSTRAINT
 Persons

 Orders

Note: Data types and length


of the column names must
be the same.
FOREIGN KEY CONSTRAINT
 Persons

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:

CREATE TABLE tb_name(column_name1 type(length) constraint, ...


PRIMARY KEY(column_name),FOREIGN KEY(column_name)
REFERENCES table_name(column_name));

CREATE TABLE orders(O_id int(5) not null,orderNo int(5) not


null,P_id int(5) not null, PRIMARY KEY(O_id), FOREIGN KEY(P_id)
REFERENCES persons(P_id));
FOREIGN KEY CONSTRAINT:
ALTER TABLE
 To create a FOREIGN KEY constraint in a particular
column where the table is already created.

Syntax:
ALTER TABLE tb_name
ADD FOREIGN KEY(column_name)
REFERENCES tb_name(column_name);

ALTER TABLE orders


ADD FOREIGN KEY(P_id)
REFERENCES person(P_id);
FOREIGN KEY CONSTRAINT: DROP
 To delete the FOREIGN KEY constraint in a
specific table.

Syntax:
ALTER TABLE tb_name
DROP FOREIGN KEY(column_name)

ALTER TABLE tb_ordersinfo


DROP FOREIGN KEY(cust_id);
CHECK CONSTRAINT
 The constraint used to limit the range of value that
can be inserted in a column.

 If you define check constraint on a single column it


allows only certain values for this column.

 It can limit the values in certain columns based on


values in other columns in the row.
CHECK CONSTRAINT: LIMIT THE
VALUE RANGE
Syntax:

CREATE TABLE tb_name(column_name1 type(length)


constraint,... PRIMARY KEY(column_name) CHECK
(column_name condition)

CREATE TABLE tb_ordersinfo (order_id int(20) not null,


order_items varchar(50) not null, order_price int(50) not
null, order_date date not null, cust_id int(20) not null
PRIMARY KEY(order_id), FOREIGN KEY(cust_id)
REFERENCES
tb_customersinfo(cust_id),CHECK(order_id>0));
CHECK CONSTRAINT: MULTIPLE
COLUMNS

CREATE TABLE tb_ordersinfo (order_id int(20) not null,


order_items varchar(50) not null, order_price int(50) not null,
order_date date not null, cust_id int(20) not null
PRIMARY KEY(order_id), FOREIGN KEY(cust_id)
REFERENCES
tb_customersinfo(cust_id),CHECK(order_id>0 AND
cust_id>0));
CHECK CONSTRAINT: ALTER
TABLE
 To create a CHECK CONSTRAINT when the table
is already created.

Syntax:
ALTER TABLE table_name
ADD CHECK(column_name constraint);

ALTER TABLE tb_ordersinfo


ADD CHECK (cust_id>0);
CHECK CONSTRAINT: ALTER
TABLE(MULTIPLE COLUMNS)

ALTER TABLE tb_ordersinfo


ADD CHECK (cust_id>0 AND order_id>0);
CHECK CONSTRAINT: DROP
 To delete a CHECK CONSTRAINT

ALTER TABLE tb_ordersinfo


DROP CHECK (cust_id>0);
DEFAULT CONSTRAINT
 Enables insertion of a default value for specified
column.

 The default value will be added to all new records, if


no other value is specified.
DEFAULT CONSTRAINT: CREATING
A TABLE
Syntax:

CREATE TABLE tb_name(column_name1


type(length) constraint,... DEFAULT value);

CREATE TABLE tb_ordersinfo(order_id int(20) not


null, order_items varchar(50) not null, order_price
int(50) not null, order_date date not null DEFAULT
GETDATE());

(the value of the date is the system date)


DEFAULT CONSTRAINT: CREATING
A TABLE

CREATE TABLE tb_employees(emp_id int(20) not


null, emp_lastname varchar(50) not null,
emp_firstname varchar(50) not null, emp_address
varchar(50) not null DEFAULT ‘Manila’);
DEFAULT CONSTRAINT: ALTER
TABLE
Syntax:

ALTER TABLE table_name


ALTER column_name SET DEFAULT value;

ALTER TABLE employees


ALTER address SET DEFAULT ‘Manila’;
DEFAULT CONSTRAINT: DROP
Syntax:

ALTER TABLE table_name


ALTER column_name DROP DEFAULT;

ALTER TABLE tb_employees


ALTER address DROP DEFAULT;
NOT NULL CONSTRAINT
 Enforces a column to NOT accept NULL values.

 Enforces a field to always contain a value.

 This means you cannot insert or update a record


without adding a value to this field.
UNIQUE CONSTRAINT: CREATING
A TABLE
 Uniquely identifies each record in a database table.

 Both the UNIQUE and PRIMARY KEY constraints


provides a guarantee for uniqueness for a column
or set of columns.

 A PRIMARY KEY constraint automatically has a


UNIQUE constraint defined on it.
INDEXES AND
VIEW
INDEX
 Indexes can be created to find data efficiently and
quickly .

 Used to find rows with specific column quickly.


INDEX
 Properties of indexes:
 Without an index, MySQL begin with the first row and then
read through the entire table to find the relevant rows. The
larger the table, the more this costs.

 Ifthe table has an index for the columns in question, MySQL


can quickly determine the position to seek to in the middle of
the data file without having to look at all the data.

 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:

CREATE INDEX index_name


ON table_name(column_name);

CREATE INDEX employees_Index


ON tb_employeee(e_id);

• Created an index that will only contain uniqe values.


• Duplicate values will not be allowed.
• Updating a table with indexes takes more time than updating a table
without index. So you should only create indexes on columns(and
tables)that will be frequently searched against.
INDEX : VIEW THE CREATED
INDEX
Syntax:

SHOW INDEX
FROM table_name;

SHOW INDEX
FROM tb_employees;
INDEX : DROP
Syntax:

ALTER TABLE table_name


DROP INDEX index_name

ALTER TABLE tb_employees


DROP INDEX employees_index;
VIEW
 Views are stored queries that when invoked produce a
result set.

 A view acts as a virtual table.

 In MySQL, view is a virtual table based on the result set


of a MySQL statement.

 The view contains rows and columns which is also the


same with database table.
VIEW
 Properties of views:
 The fields in a view are fields from one or more real tables in
the database

 You cam add SQL functions, WHERE and JOIN statements


to a view and present the data as if the data were coming
from one single table.
VIEW: CREATE
Syntax:

CREATE VIEW view_name AS SELECT


column_name(s) FROM table_name WHERE
Condition ORDER BY column_name;

CREATE VIEW SalesPerOrder AS SELECT order_id,


SUM(quantityOrdered * priceEach)
Total
GROUP BY order_id;
ORDER BY total desc;
VIEW: SELECT/SHOW A VIEW
Syntax:

SELECT * FROM view_name;

SELECT * FROM Employees_view;


VIEW: UPDATE
Syntax:

CREATE OR REPLACE VIEW AS view_name AS


SELECT column_name(s) FROM table_name WHERE
condition;

CREATE OR REPLACE VIEW SalesPerOrder AS


SELECT order_id, SUM(quantityOrdered * priceEach)
total GROUP BY order_id ORDER BY total DESC;
VIEW: DROP
Syntax:

DROP VIEW view_name;

DROP VIEW Employees_view;


TRANSACTION
MANAGEMENT
TRANSACTION MODES
Mode Syntax
Autocommit ON SET AUTOCOMMIT=1
Autocommit OFF SET AUTOCOMMIT=0
AUTOCOMMIT ON
 Default mode
 Can be started wit “SET AUTOCOMMIT=1” command

 In this mode, every single SQL statement is a new

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

into a single transaction.


FIND THE CURRENT TRANSACTION
MODE
 To find out the current transaction is ON of OFF

Syntax:
SELECT @@AUTOCOMMIT FROM DUAL;

 By default, your MySQL server is set to ON(1) mode.


START TRANSACTION
Same with BEGIN TRANSACTION
START NEW TRANSACTION EXPLICITLY
(CLEARLY STATED)
START TRANSACTION;

INSERT INTO tb_employees


values(‘8’,’Alvin’,’Teruel’,’Pasay City’);
INSERT INTO tb_employees
Values(‘9’,’Bryan’,’Dadiz’,’Quezon City’);
ROLLBACK;

Common questions

Powered by AI

A view in MySQL functions as a virtual table representing the result of a stored query. It presents data from one or more tables as if it were a single table, allowing for abstracted data access and simplifying complex queries. Using a view is advantageous in scenarios where you need to hide complex joins and calculations from end users, making the data easier to query, or when providing a layer of security by exposing only specific columns from tables, thereby restricting access to sensitive data .

The NOT NULL constraint ensures that a column cannot have NULL values, enforcing the presence of data in that field. It is effectively used in columns where data is mandatory, like a user's unique identifier or password. The DEFAULT constraint sets a default value for a column if no value is provided during an insert, which is useful for optional fields with default settings, such as setting a default city for new employees in a location-specific office without manually entering it each time. For instance, using DEFAULT 'Manila' ensures 'Manila' is automatically inserted unless overridden .

Dropping a primary key constraint on a populated table can lead to challenges such as loss of data integrity, as the ability to uniquely identify records is compromised. Previously referenced foreign key relationships may become invalid, leading to potential orphaned records. Precautions include ensuring no foreign key dependencies exist, or updating them accordingly, and backing up data before making changes to prevent irreversible data loss or inconsistencies .

A primary key constraint is critical in a MySQL database table because it uniquely identifies each record, ensuring data integrity and preventing duplicate entries. It must contain unique values, and the column designated as the primary key cannot have NULL values, thereby enforcing that each record is identifiable. We can only have one primary key per table to maintain the uniqueness of records, as multiple primary keys would complicate the identification of unique records .

SQL Views provide several benefits for data presentation and management, including simplifying complex queries by encapsulating them into reusable objects, improving security by restricting data access to specific columns, and enabling better control over how data is presented to users. They can create a consistent and unified view of data from multiple tables. However, the limitations include potential performance slowdowns because views do not store data themselves but generate it dynamically during queries. Incremental maintenance needs can also arise, as changes to underlying tables require updates to the views .

A foreign key constraint ensures data consistency in relational databases by establishing a relationship between tables through the primary key of another table. This means that values in the foreign key column must match those in the referenced primary key, thus maintaining referential integrity. It prevents actions that would violate the relationships between tables, such as deleting referenced data .

Altering an existing table to add a check constraint is beneficial when there is a need to enforce data validation rules on existing data, impose new business logic constraints, or enhance data quality by restricting the range of acceptable values. The syntax for adding a check constraint is: ALTER TABLE table_name ADD CHECK(column_name condition);. Considerations include ensuring that the existing data complies with the new constraint, as non-compliant data may cause the operation to fail. Additionally, performance impacts should be assessed, as check constraints can add overhead during data insertions and updates .

Indexes improve query performance by allowing for faster data retrievals. They enable MySQL to quickly locate and read relevant rows, significantly reducing the number of records that need to be scanned in large tables. For example, without an index, MySQL reads the entire table to find relevant rows, which is computationally expensive. However, the trade-offs include increased time and resources to maintain indexes during data modifications, such as insertions, updates, or deletions, as every modification necessitates updating the index as well .

Enabling AUTOCOMMIT mode in MySQL results in every individual SQL statement being considered a separate transaction, which is automatically committed upon completion. This simplifies transaction management by removing the need for explicit commit commands but can lead to unintended data changes if errors occur, as each statement is irrevocable once executed. This can make error recovery more challenging, as there is no opportunity to review changes before commitment unless explicitly disabled .

It is necessary to ensure that data types and lengths of columns in foreign key constraints match between parent and child tables to maintain data integrity and ensure valid relationships. Mismatched data types can cause data consistency errors and prevent the foreign key from establishing a valid link to the primary key, potentially leading to data anomalies or referential integrity issues .

You might also like