Database and MySQL I

Download as pdf or txt
Download as pdf or txt
You are on page 1of 48

Database and MySQL I & II

Q. DATABASE – Structured collection of data

• Database
• Tables
• Fields

Q. SQL

• Structured query language


• Lets you access and manipulate databases
• SQL became a standard of the American National Standards Institute (ANSI) in
1986, and of the International Organization for Standardization (ISO) in 1987

Q. What can you do with SQL

• Create database
• Create tables in database
• Query or request info from a database
• Insert records in a database
• Update or modify records in a database
• Delete records from database
• Set permissions or access control within database for data security
• Create views to avoid typing frequently used complex queries

Q. Database management system

• Manages the storage and retrieval of data to and from the database and hides the
complexity of what is actually going on from the user.


• MySQL is a RDBMS
Q. Relational vs non-relational database system

Aspect Relational Database (RDBMS) Non-relational Database (NoSQL)


1 Data Model Structured in tables (rows and Flexible schema, data stored as
columns) with predefined key-value pairs, documents,
schemas graphs, or wide columns
2 Schema Fixed schema, requires data to Dynamic schema, allows schema-
fit the structure less data
3 Relationships Supports relationships Generally does not support
between tables using foreign complex relationships, uses
keys and joins embedding or referencing instead
4 Query SQL (Structured Query No fixed query language; depends
Language Language) on the type (e.g., MongoDB uses
MQL, Cassandra uses CQL)
5 Scalability Vertically scalable (requires Horizontally scalable (can add
more powerful hardware) more servers to handle large
datasets)
6 Consistency Follows ACID (Atomicity, Follows BASE (Basically Available,
Consistency, Isolation, Soft state, Eventual consistency)
Durability) principles principles
7 Use Cases Best for structured data, Best for unstructured or semi-
complex queries, and multi- structured data, real-time
row transactions applications, and big data
8 Storage Data is stored in tables where Data storage depends on the type:
model each row is a record and each document-oriented (JSON, BSON),
column is an attribute key-value pairs, column-family
stores, or graph-based

Q. MySQL as a non-procedural language

MySQL can be classified as a non-procedural language (also known as a declarative


language) because it focuses on what the result should be rather than how to obtain it. In
MySQL, users specify the desired outcome (like retrieving certain data) rather than
providing step-by-step instructions on how to compute that outcome.

Characteristics of MySQL as a Non-Procedural Language:

1. Focus on "What" Rather than "How":


a. In MySQL, the user declares what they want in terms of a query (e.g.,
retrieve data from a table), and the MySQL engine figures out how to execute
the request.
b. Example: SELECT name, age FROM students WHERE age > 18;
c. Here, the user states what data is required but does not specify how MySQL
should search through the tables.
2. No Explicit Flow Control:
a. Non-procedural languages like SQL lack control structures such as loops or
conditionals to direct the flow of execution. The database management
system (DBMS) automatically optimizes and executes the query.
b. SQL does not require specifying how to iterate over rows or how to fetch the
data.
3. Declarative Syntax:
a. SQL, including MySQL, is a declarative language where you declare your
intent. The DBMS optimizes query plans internally, meaning users don't
need to manage low-level execution details (like memory or iteration).
b. Example: In UPDATE employees SET salary = salary * 1.1 WHERE
department = 'HR';, the user simply describes the operation they want,
and MySQL handles how it's executed efficiently.
4. Query Optimization by the DBMS:
a. Since MySQL is non-procedural, the responsibility of query optimization lies
with the DBMS. It decides the best way to retrieve or manipulate data,
without the user having to give procedural steps.

Q. What do you mean by DML – data statements?

A.

Data statements, or Data Manipulation Language (DML), are used to manage the data
within the tables of the database. These statements allow users to insert, retrieve,
update, or delete data from the database without modifying the schema.

Common Data Statements:

• SELECT: Retrieves data from one or more tables.


SELECT name, department FROM employees WHERE department = 'HR';
• INSERT: Adds new records (rows) into a table.
INSERT INTO employees (id, name, department) VALUES (1, 'John Doe',
'HR');

• UPDATE: Modifies existing data in a table.


UPDATE employees SET department = 'Finance' WHERE id = 1;

• DELETE: Removes records from a table.


DELETE FROM employees WHERE id = 1;

Q. What do you mean by DDL – Schema Statements?

A.

Schema statements, also known as Data Definition Language (DDL), are used to define or
modify the structure of database objects like tables, indexes, views, and constraints.
These statements primarily deal with the database schema and its organization.

Common Schema Statements:


CREATE: Creates new database objects such as tables, indexes, views, or
databases.
CREATE TABLE employees (
id INT PRIMARY KEY,
name VARCHAR(50),
department VARCHAR(50)
);


ALTER: Modifies an existing database object, such as adding or dropping columns
from a table.
ALTER TABLE employees ADD salary INT;

• DROP: Removes a database object from the system, like deleting a table or a view.
DROP TABLE employees;

• TRUNCATE: Deletes all rows from a table but keeps its structure intact.
TRUNCATE TABLE employees;
Q. Transaction Statements (TCL - Transaction Control Language):

Transaction statements, also known as Transaction Control Language (TCL), are used to
manage database transactions. A transaction is a sequence of one or more SQL
statements that are executed as a unit to ensure data consistency and integrity.

Common Transaction Statements:


BEGIN TRANSACTION / START TRANSACTION: Starts a new transaction block,
allowing multiple SQL statements to be executed within it.
START TRANSACTION;

• COMMIT: Saves all the changes made in the current transaction permanently.
COMMIT;


ROLLBACK: Reverts the changes made during the transaction, undoing all
modifications since the transaction started.
ROLLBACK;


SAVEPOINT: Sets a savepoint within a transaction, allowing partial rollback to that
specific point.
SAVEPOINT savepoint_name;

Q. What is a table?

A.

In MySQL, a table is a structured collection of data organized in rows and columns. It is


one of the fundamental building blocks of a database. Each table in a database holds data
for a specific entity or subject, and each column in the table represents an attribute (or
field) of that entity, while each row represents a record (or entry) for that entity.

Key components of a table:

• Columns: Represent the attributes or fields. Each column has a data type (e.g.,
INT, VARCHAR, DATE) that defines the kind of data it can store.
• Rows: Represent individual records. Each row holds data for each column in the
table.
• Primary Key: A column or combination of columns that uniquely identifies each
row in the table.

Creating a Table in MySQL:


CREATE TABLE employees (
employee_id INT PRIMARY KEY,
name VARCHAR(100),
department VARCHAR(50),
salary DECIMAL(10, 2)
);

Q. Names (table & column names)

In SQL, table names and column names are used to identify tables and fields within a
database. These names should be meaningful and descriptive to clearly represent the data
they hold. Here’s an explanation of both:

1. Table Names:

A table name identifies a specific table in a database, and it should describe the kind of
data the table holds. Table names are usually written in the singular form and should be
short but descriptive.

Examples of Table Names:

• employees – A table that stores data related to employees.


• orders – A table containing order details.
• students – A table that holds information about students.
• products – A table storing product details.

2. Column Names:

Column names represent the fields or attributes of a table and describe the type of data
stored in each column. They should clearly define what each field represents in the context
of the table.

Examples of Column Names:


• id – A unique identifier for each row (often the primary key).
• name – Represents the name of a person, product, etc.
• email – Stores email addresses of users or customers.
• created_at – Stores the date and time when the record was created.
• price – Represents the price of a product or service.
• quantity – Stores the number of items or units.

Example:
CREATE TABLE employees (
employee_id INT PRIMARY KEY,
first_name VARCHAR(50),
last_name VARCHAR(50),
email VARCHAR(100),
hire_date DATE,
salary DECIMAL(10, 2)
);

Q. What are the datatypes available in MySQL? - Char, Varchar, Text, Mediumtext,
Longtext, Smallint, Bigint, Boolean, Decimal, Float, Double, Date, Date Time,
Timestamp, Year, Time

A.

1. CHAR:


Description: Fixed-length string data type. It stores a string with a specified length,
padding with spaces if the length is less than the defined size.
• Syntax: CHAR(n) where n is the length.
• Example:
CREATE TABLE users (username CHAR(10));
INSERT INTO users (username) VALUES ('John');
-- 'John' will be stored as 'John ' (padded with spaces)

2. VARCHAR:

• Description: Variable-length string data type. It stores strings up to a defined length


but does not pad with spaces.
• Syntax: VARCHAR(n) where n is the maximum length.
• Example:
CREATE TABLE users (username VARCHAR(50));
INSERT INTO users (username) VALUES ('John');
-- 'John' will be stored as 'John' (without extra spaces)

3. TEXT:

• Description: A variable-length string data type designed for large text fields. It can
store up to 65,535 characters.
• Example:
CREATE TABLE posts (content TEXT);
INSERT INTO posts (content) VALUES ('This is a long blog post...');

4. MEDIUMTEXT:

• Description: Allows for storage of larger text, up to 16,777,215 characters.


• Example:
CREATE TABLE articles (content MEDIUMTEXT);
INSERT INTO articles (content) VALUES ('A very long article
content...');

5. LONGTEXT:

• Description: The largest text type, it stores up to 4,294,967,295 characters.


• Example:
CREATE TABLE books (description LONGTEXT);
INSERT INTO books (description) VALUES ('A massive amount of book
content...');

6. SMALLINT:

• Description: Stores small integer values, typically between -32,768 and 32,767 (2
bytes).
• Example:
CREATE TABLE inventory (quantity SMALLINT);
INSERT INTO inventory (quantity) VALUES (1500);
7. BIGINT:

• Description: Stores large integer values, typically between -


9,223,372,036,854,775,808 and 9,223,372,036,854,775,807 (8 bytes).
• Example:
CREATE TABLE transactions (transaction_id BIGINT);
INSERT INTO transactions (transaction_id) VALUES (12345678912345);

8. BOOLEAN:

• Description: Stores TRUE or FALSE values. Internally, it's often represented as 0


(false) and 1 (true).
• Example:
CREATE TABLE products (is_available BOOLEAN);
INSERT INTO products (is_available) VALUES (TRUE);

9. DECIMAL:

• Description: Used for storing exact numeric values with a fixed precision and scale.
Ideal for monetary values.
• Syntax: DECIMAL(precision, scale) where precision is the total number of
digits and scale is the number of digits after the decimal point.
• Example:
CREATE TABLE products (price DECIMAL(10, 2));
INSERT INTO products (price) VALUES (99.99);

10. FLOAT:

• Description: Stores floating-point numbers with less precision compared to


DOUBLE. Typically used for smaller, less precise values.
• Example:
CREATE TABLE measurements (temperature FLOAT);
INSERT INTO measurements (temperature) VALUES (36.6);

11. DOUBLE:

• Description: Stores larger, more precise floating-point numbers. It is used for


scientific calculations requiring high precision.
• Example:
CREATE TABLE distances (light_years DOUBLE);
INSERT INTO distances (light_years) VALUES (4.367);

12. DATE:

• Description: Stores a date in the format YYYY-MM-DD. Does not store time
information.
• Example:
CREATE TABLE events (event_date DATE);
INSERT INTO events (event_date) VALUES ('2024-10-20');

13. DATETIME:

• Description: Stores both date and time in the format YYYY-MM-DD HH:MM:SS.
Used for logging events with timestamps.
• Example:
CREATE TABLE appointments (appointment_time DATETIME);
INSERT INTO appointments (appointment_time) VALUES ('2024-10-20
14:30:00');

14. TIMESTAMP:

• Description: Similar to DATETIME, but it stores date and time with automatic time
zone conversion. Often used for tracking changes and modifications.
• Example:
CREATE TABLE users (created_at TIMESTAMP);
INSERT INTO users (created_at) VALUES (CURRENT_TIMESTAMP);

15. YEAR:

• Description: Stores a year in either 2-digit (YY) or 4-digit (YYYY) format.


• Example:
CREATE TABLE contracts (start_year YEAR);
INSERT INTO contracts (start_year) VALUES (2024);

16. TIME:

• Description: Stores time in the format HH:MM:SS. Does not store date information.
• Example:
CREATE TABLE shifts (shift_start TIME);
INSERT INTO shifts (shift_start) VALUES ('09:30:00');

Data Type Description Example


CHAR(n) Fixed-length string (padded with spaces). CHAR(10)
VARCHAR(n) Variable-length string. VARCHAR(50)
TEXT Large variable-length string (up to 65,535 characters). TEXT
MEDIUMTEXT Larger text field (up to 16,777,215 characters). MEDIUMTEXT
LONGTEXT Very large text field (up to 4,294,967,295 characters). LONGTEXT
SMALLINT Small integer, typically -32,768 to 32,767. SMALLINT
BIGINT Large integer, typically - BIGINT
9,223,372,036,854,775,808 to
9,223,372,036,854,775,807.
BOOLEAN Stores TRUE or FALSE values. BOOLEAN
DECIMAL(p,s) Exact numeric with defined precision and scale. DECIMAL(10,
2)
FLOAT Floating-point number with less precision. FLOAT
DOUBLE More precise floating-point number. DOUBLE
DATE Date in YYYY-MM-DD format. DATE
DATETIME Date and time in YYYY-MM-DD HH:MM:SS format. DATETIME
TIMESTAMP Date and time with time zone handling. TIMESTAMP
YEAR Year, either 2-digit or 4-digit format. YEAR
TIME Time in HH:MM:SS format. TIME

Q. Creating Database, inserting data, Updating data, Deleting data

1. Creating a Database

To create a new database in SQL, use the CREATE DATABASE statement.

Example: CREATE DATABASE school;

This command creates a database named school. You can use the USE statement to
select the database you want to work with.

Example: USE school;


2. Inserting Data

To insert data into a table, use the INSERT INTO statement.

Example:

INSERT INTO students (first_name, last_name, age, email)


VALUES ('John', 'Doe', 20, '[email protected]');

INSERT INTO students (first_name, last_name, age, email)


VALUES ('Jane', 'Smith', 22, '[email protected]');

This inserts two new records into the students table.

3. Updating Data

To update existing records in a table, use the UPDATE statement. You can use the WHERE
clause to specify which records to update.

Example:

UPDATE students
SET age = 21
WHERE first_name = 'John' AND last_name = 'Doe';

This updates the age of John Doe to 21.

4. Deleting Data

To delete records from a table, use the DELETE statement. It’s crucial to use the WHERE
clause to avoid deleting all records.

Example:

DELETE FROM students


WHERE first_name = 'Jane' AND last_name = 'Smith';

This deletes the record of Jane Smith from the students table.
Operation SQL Command Example
Create CREATE DATABASE database_name; CREATE DATABASE school;
Database
Use USE database_name; USE school;
Database
Create CREATE TABLE table_name CREATE TABLE students
Table (column_definitions); (...);
Insert INSERT INTO table_name (columns) INSERT INTO students
Data VALUES (values); (...) VALUES (...);
Update UPDATE table_name SET column = UPDATE students SET age =
Data value WHERE condition; 21 WHERE ...;
Delete DELETE FROM table_name WHERE DELETE FROM students
Data condition; WHERE ...;

Q. CREATE,USE, ALTER (Add, Remove, Change columns), RENAME, SHOW, DESCRIBE


(CREATE TABLE, COLUMNS, STATUS and DATABASES only) and DROP (TABLE,
COLUMN, DATABASES statements)

1. CREATE

• Description: Used to create a new database or table.

Example: Create Database

CREATE DATABASE school;

Example: Create Table

CREATE TABLE students (


student_id INT PRIMARY KEY AUTO_INCREMENT,
first_name VARCHAR(50),
last_name VARCHAR(50),
age INT,
email VARCHAR(100)
);
2. USE

• Description: Selects the specified database for subsequent operations.

Example:

USE school;

3. ALTER

The ALTER command is used to modify an existing table structure.

a. Add Column

Example:

ALTER TABLE students


ADD COLUMN enrollment_date DATE;

b. Remove Column

Example:

ALTER TABLE students


DROP COLUMN enrollment_date;

c. Change Column

Example:

ALTER TABLE students


CHANGE COLUMN age INT NOT NULL;

This example modifies the age column to ensure it cannot be NULL.

4. RENAME

• Description: Renames a database or table.


Example: Rename Table

RENAME TABLE students TO learners;

5. SHOW

• Description: Displays various information about databases and tables.

Example: Show Databases

SHOW DATABASES;

Example: Show Tables in a Database

SHOW TABLES;

Example: Show Table Status

SHOW TABLE STATUS LIKE 'students';

6. DESCRIBE

Description: Provides details about a table structure (columns, types, and constraints).

a. DESCRIBE (CREATE TABLE)

• Usage: Displays the structure of a specified table, including columns, types, and
constraints.
• Example:
DESCRIBE students;

b. SHOW COLUMNS

• Usage: Shows detailed information about the columns of a specified table.


• Example:
SHOW COLUMNS FROM students;

c. SHOW TABLE STATUS

• Usage: Provides information about the specified table, including size, number of
rows, and engine type.
• Example:
SHOW TABLE STATUS LIKE 'students';

d. SHOW DATABASES

• Usage: Lists all databases available on the server.


• Example:
SHOW DATABASES;

7. DROP

The DROP command is used to delete databases, tables, or columns.

a. Drop Table

Deletes a specified table and all its data.

Example:

DROP TABLE students;

b. Drop Column

Deletes a specified column from a table.

Example:
ALTER TABLE learners
DROP COLUMN email;

c. Drop Database

Deletes a specified database and all its tables and data.

Example:

DROP DATABASE school;

Q. What do you understand by qualified column?


A.

In MySQL, a qualified column refers to a column name that is explicitly associated with its
table name. This is particularly useful when dealing with queries that involve multiple
tables (such as joins), where columns from different tables may have the same name. By
qualifying a column with its table name, you avoid ambiguity and ensure that the database
knows exactly which column you're referring to.

Syntax:

table_name.column_name

Example:

Suppose you have two tables: employees and departments, both of which have a column
named name.

• employees table:

employee_id name department_id


1 John Doe 101
2 Jane Smith 102

• departments table:
department_id name
101 HR
102 IT

If you want to retrieve both the employee's name and the department's name, you need to
qualify the columns to specify which name column you're referring to:

SELECT employees.name AS employee_name, departments.name AS


department_name
FROM employees
JOIN departments ON employees.department_id =
departments.department_id;

Here, employees.name and departments.name are qualified column names, making it


clear which name belongs to the employees table and which belongs to the departments
table.

Benefits of Qualified Columns:

• Avoids ambiguity when column names are the same in multiple tables.
• Improves query readability, especially in complex queries.
• Ensures that the correct column is referenced during operations like joins.

Q. SQL considerations for multi table queries (table aliases, qualified column names,
all column selections self joins).

When working with multi-table queries in SQL, there are several important considerations
to keep in mind to ensure that your queries are efficient, clear, and maintainable. Here’s a
breakdown of key considerations, including table aliases, qualified column names, and
self-joins.

1. Table Aliases

Description: Table aliases provide a shorthand for table names, making your SQL queries
easier to read and write, especially when dealing with multiple tables.

Usage:
• Assign an alias using the AS keyword (though AS is optional).
• Use the alias in your SELECT statement and JOIN conditions.

Example:

SELECT e.first_name, e.last_name, d.department_name


FROM employees AS e
INNER JOIN departments AS d ON e.department_id = d.department_id;

2. Qualified Column Names

Description: Qualified column names specify the table name or its alias alongside the
column name, which helps avoid ambiguity when two tables have columns with the same
name.

Usage:

• Always qualify column names when dealing with multiple tables to clarify which
table a column belongs to.

Example:

SELECT e.first_name, e.last_name, d.department_name


FROM employees e
INNER JOIN departments d ON e.department_id = d.department_id;

By using e.first_name and d.department_name, we make it clear which table each


column comes from, reducing the chance of errors.

3. All Column Selections

Description: If you want to retrieve all columns from multiple tables, you can use the *
wildcard. However, be cautious, as this can lead to confusion, especially when dealing
with tables that have columns with the same names.

Usage:

• Use table_name.* or alias.* to specify that you want all columns from a
particular table.
Example:

SELECT e.*, d.department_name


FROM employees e
INNER JOIN departments d ON e.department_id = d.department_id;

This query retrieves all columns from the employees table and the department_name
from the departments table.

4. Self-Joins

Description: A self-join is a join where a table is joined with itself. This is useful for
comparing rows within the same table or for hierarchical data structures.

Usage:

• You need to use table aliases to differentiate between the instances of the same
table.

Example: Consider a employees table that has a manager_id column indicating the
employee’s manager.

SELECT e1.first_name AS employee, e2.first_name AS manager


FROM employees e1
INNER JOIN employees e2 ON e1.manager_id = e2.employee_id;

In this example, e1 represents employees, and e2 represents their managers. The query
retrieves the names of employees along with their managers.

5. Performance Considerations

• Indexing: Ensure that the columns used in join conditions are indexed. This can
significantly speed up query performance.
• Filter Early: Use WHERE conditions to filter data as early as possible in the query
execution to reduce the amount of data being processed in joins.
• Avoid Select: While SELECT * is convenient, it can lead to performance issues and
ambiguity. Instead, specify only the columns you need.
Q. What do you understand by primary key and foreign key?

A.

Primary Key:

• A primary key is a column (or a set of columns) that uniquely identifies each row in
a table.
• Each table can have only one primary key.
• The primary key ensures that no two rows in a table can have the same value for the
primary key column(s), and it also enforces that the column cannot contain NULL
values.
• The primary key is typically used to ensure each record is unique and to create
relationships with other tables.

Example of a Primary Key:

CREATE TABLE employees (


employee_id INT PRIMARY KEY, -- employee_id is the primary key
name VARCHAR(100),
department VARCHAR(50)
);

In this example, the employee_id column is the primary key, meaning each employee
must have a unique employee_id, and it cannot be NULL.

Foreign Key:

• A foreign key is a column (or a set of columns) in one table that refers to the
primary key of another table.
• The foreign key establishes a relationship between two tables, enforcing referential
integrity by ensuring that a value in the foreign key column must correspond to a
value in the referenced primary key.
• It ensures that the data remains consistent, meaning you cannot insert a value into
a foreign key column that does not exist in the referenced table's primary key.
Example of a Foreign Key:

CREATE TABLE departments (


department_id INT PRIMARY KEY, -- primary key in the departments
table
department_name VARCHAR(100)
);

CREATE TABLE employees (


employee_id INT PRIMARY KEY,
name VARCHAR(100),
department_id INT,
FOREIGN KEY (department_id) REFERENCES departments(department_id)
-- foreign key
);

In this example:

• department_id is the primary key in the departments table.


• In the employees table, department_id is a foreign key that references the
department_id in the departments table. This ensures that each employee
belongs to a valid department.

Key Differences:

• Primary Key: Uniquely identifies each record in a table and ensures no NULL values.
• Foreign Key: Establishes a link between two tables and ensures that a value in one
table matches a valid value in the referenced table.

Together, primary keys and foreign keys help maintain data integrity and define
relationships between tables in a relational database.

Q. What do you understand by TERMS NULL, NOT NULL, ENUM, DEFAULT, UNSIGNED
A.

1. NULL


Definition: NULL represents a missing or undefined value in a column. It indicates
that the data for that column is not available.
• Usage: By default, columns can hold NULL values unless specified otherwise.
• Example:
CREATE TABLE employees (
employee_id INT PRIMARY KEY,
name VARCHAR(100),
department VARCHAR(50) NULL -- department can be NULL
);

2. NOT NULL


Definition: The NOT NULL constraint ensures that a column cannot have NULL
values, meaning it must contain a valid data entry.
• Usage: This constraint is used when a column is mandatory for every record in the
table.
• Example:
CREATE TABLE employees (
employee_id INT PRIMARY KEY,
name VARCHAR(100) NOT NULL, -- name cannot be NULL
department VARCHAR(50)
);

3. ENUM


Definition: ENUM is a string data type that allows you to define a list of permitted
values for a column. A column of this type can hold one value from the specified
list.
• Usage: Useful for columns that should have a limited set of values (e.g., status,
category).
• Example:
CREATE TABLE orders (
order_id INT PRIMARY KEY,
status ENUM('pending', 'shipped', 'delivered', 'cancelled') --
restricted values
);

In this case, the status column can only contain one of the specified values.

4. DEFAULT

• Definition: The DEFAULT constraint sets a default value for a column when no value
is provided during insertion.
• Usage: It is useful for ensuring that a column has a value even if the user does not
specify one.
• Example:
CREATE TABLE employees (
employee_id INT PRIMARY KEY,
name VARCHAR(100) NOT NULL,
department VARCHAR(50) DEFAULT 'General' -- default value if
department is not specified
);

5. UNSIGNED

• Definition: The UNSIGNED attribute is applied to numeric data types to indicate


that the column cannot hold negative values. Only zero and positive numbers can
be stored.
• Usage: Useful when you know that the values will always be non-negative (e.g., age,
quantity).
• Example:
CREATE TABLE products (
product_id INT UNSIGNED PRIMARY KEY, -- product_id cannot be
negative
quantity INT UNSIGNED NOT NULL -- quantity cannot be negative
);

Q. Simple Validity checking using CONSTRAINTS


In SQL, constraints are used to enforce rules on the data in a table to maintain data
integrity. Here’s a brief overview of some common constraints used for simple validity
checking, along with examples.

1. NOT NULL

• Description: Ensures that a column cannot have a NULL value.


• Example:
CREATE TABLE students (
student_id INT PRIMARY KEY,
first_name VARCHAR(50) NOT NULL, -- Cannot be NULL
last_name VARCHAR(50) NOT NULL
);

2. UNIQUE

• Description: Ensures that all values in a column are unique.


• Example:
CREATE TABLE students (
student_id INT PRIMARY KEY,
email VARCHAR(100) UNIQUE -- Email must be unique
);

3. CHECK

• Description: Ensures that all values in a column satisfy a specific condition.


• Example:
CREATE TABLE students (
student_id INT PRIMARY KEY,
age INT CHECK (age >= 0) -- Age must be a non-negative value
);

4. DEFAULT

• Description: Provides a default value for a column when no value is specified


during insertion.
• Example:
CREATE TABLE students (
student_id INT PRIMARY KEY,
enrollment_date DATE DEFAULT CURRENT_DATE -- Default to current
date
);

5. FOREIGN KEY


Description: Ensures referential integrity between two tables by requiring that a
value in one table matches a value in another.
• Example:
CREATE TABLE courses (
course_id INT PRIMARY KEY,
course_name VARCHAR(100)
);

CREATE TABLE enrollments (


enrollment_id INT PRIMARY KEY,
student_id INT,
course_id INT,
FOREIGN KEY (student_id) REFERENCES students(student_id),
FOREIGN KEY (course_id) REFERENCES courses(course_id)
);

Q. What do you understand by auto-increment?

A.

Auto-increment is a feature in MySQL used to automatically generate unique integer


values for a column in a table, typically for primary key columns. When a new row is
inserted into a table, the auto-increment column is assigned the next available integer
value, eliminating the need for the user to manually specify the value for that column.

Key Points about Auto-Increment:

1. Unique Identifier: Auto-incremented columns are commonly used as primary keys


to uniquely identify each record in a table.
2. Starting Value and Increment: You can define the starting value of the auto-
incrementing column and the increment step. By default, the starting value is 1, and
the increment is also 1. However, you can modify these settings if needed.
3. NULL Values: When inserting data, you should specify NULL or omit the auto-
increment column in the INSERT statement; the database will automatically assign
the next value.
4. Only One Auto-Increment Column: A table can have only one auto-increment
column.

Example of Auto-Increment:

Here's how to define an auto-increment column in a MySQL table:

CREATE TABLE users (


user_id INT AUTO_INCREMENT PRIMARY KEY,
username VARCHAR(100) NOT NULL,
email VARCHAR(100)
);

In this example:

• The user_id column is set as an auto-increment column and is also the primary
key.
• When you insert a new user, you do not need to specify a value for user_id; it will
automatically receive the next integer value.

Inserting Data:

Here’s how to insert data into the users table:

INSERT INTO users (username, email) VALUES ('alice',


'[email protected]');
INSERT INTO users (username, email) VALUES ('bob', '[email protected]');

After these inserts, the user_id column will automatically have the following values:

• user_id for Alice: 1


• user_id for Bob: 2
Resetting Auto-Increment:

You can reset the auto-increment value using the ALTER TABLE statement:

ALTER TABLE users AUTO_INCREMENT = 100; -- Next value will be 100

Q. Explain built-in functions: lower, upper, reverse, length, ltrim, rtrim, trim, left, right,
mid, concat, now, time, date, curdate, day, month, year, dayname, monthname, abs,
pow, mod, round, sqrt

A.

• LOWER(): Converts all characters in a string to lowercase.

Example: SELECT LOWER('HELLO'); -- Output: 'hello'

• UPPER(): Converts all characters in a string to uppercase.

Example: SELECT UPPER('hello'); -- Output: 'HELLO'

• REVERSE(): Reverses the order of characters in a string.

Example: SELECT REVERSE('hello'); -- Output: 'olleh'

• LENGTH(): Returns the number of characters in a string.

Example: SELECT LENGTH('hello'); -- Output: 5

• LTRIM(): Removes leading spaces from a string.

Example: SELECT LTRIM(' hello'); -- Output: 'hello'

• RTRIM(): Removes trailing spaces from a string.

Example: SELECT RTRIM('hello '); -- Output: 'hello'

• TRIM(): Removes leading and trailing spaces from a string.

Example: SELECT TRIM(' hello '); -- Output: 'hello'

• LEFT(): Returns the leftmost characters from a string.


Example: SELECT LEFT('hello', 3); -- Output: 'hel'

• RIGHT(): Returns the rightmost characters from a string.

Example: SELECT RIGHT('hello', 2); -- Output: 'lo'

• MID() (also known as SUBSTRING()): Extracts a substring from a string starting at a


specified position.

Example: SELECT MID('hello', 2, 3); -- Output: 'ell'

• CONCAT(): Concatenates two or more strings together.

Example:SELECT CONCAT('Hello', ' ', 'World'); -- Output: 'Hello


World'

• NOW(): Returns the current date and time.

Example: SELECT NOW(); -- Output: '2024-10-02 10:30:45'

• TIME(): Extracts the time part from a date-time expression.

Example: SELECT TIME(NOW()); -- Output: '10:30:45'

• DATE(): Extracts the date part from a date-time expression.

Example: SELECT DATE(NOW()); -- Output: '2024-10-02'

• CURDATE(): Returns the current date.

Example: SELECT CURDATE(); -- Output: '2024-10-02'

• DAY(): Returns the day of the month (1-31) from a date.

Example: SELECT DAY('2024-10-02'); -- Output: 2

• MONTH(): Returns the month (1-12) from a date.

Example: SELECT MONTH('2024-10-02'); -- Output: 10

• YEAR(): Returns the year from a date.

Example: SELECT YEAR('2024-10-02'); -- Output: 2024


• DAYNAME(): Returns the name of the weekday for a date.

Example: SELECT DAYNAME('2024-10-02'); -- Output: 'Wednesday'

• MONTHNAME(): Returns the name of the month for a date.

Example: SELECT MONTHNAME('2024-10-02'); -- Output: 'October'

• ABS(): Returns the absolute (positive) value of a number.

Example: SELECT ABS(-5); -- Output: 5

• POW(): Returns a number raised to the power of another number.

Example: SELECT POW(2, 3); -- Output: 8 (2^3 = 8)

• MOD(): Returns the remainder of the division of two numbers.

Example: SELECT MOD(10, 3); -- Output: 1 (10 % 3 = 1)

• ROUND(): Rounds a number to a specified number of decimal places.

Example: SELECT ROUND(123.456, 2); -- Output: 123.46

• SQRT(): Returns the square root of a number.

Example: SELECT SQRT(16); -- Output: 4

Q. Explain Transaction in MySQL.

A.

In MySQL, a transaction is a sequence of one or more SQL statements that are executed
as a single unit of work. Transactions are essential for ensuring data integrity and
consistency in a database, especially when multiple operations are involved that depend
on each other. If any part of the transaction fails, the entire transaction can be rolled back,
meaning that the database state will revert to what it was before the transaction began.

Key Properties of Transactions (ACID):

Transactions in MySQL adhere to the ACID properties, which ensure reliable processing:
5. Atomicity: A transaction is treated as a single unit. It either completely succeeds
(commits) or completely fails (rolls back). If any part of the transaction fails, the
changes made by the entire transaction are undone.
6. Consistency: A transaction brings the database from one valid state to another
valid state. It ensures that all data integrity constraints are satisfied before and after
the transaction.
7. Isolation: Transactions are isolated from each other. Changes made in one
transaction are not visible to other transactions until the first transaction is
committed. This prevents data corruption due to concurrent transactions.
8. Durability: Once a transaction has been committed, its changes are permanent,
even in the event of a system failure. The changes are saved to the database.

Transaction Control Statements:

MySQL provides several commands to manage transactions:

• BEGIN or START TRANSACTION: Initiates a new transaction.

START TRANSACTION;

• COMMIT: Saves all changes made in the current transaction to the database.

COMMIT;

• ROLLBACK: Undoes all changes made in the current transaction, reverting the
database to its previous state.

ROLLBACK;

Example of a Transaction:

Here’s a simple example to illustrate the use of transactions:

START TRANSACTION;

-- Deduct amount from Account A


UPDATE accounts SET balance = balance - 100 WHERE account_id = 1;
-- Add amount to Account B
UPDATE accounts SET balance = balance + 100 WHERE account_id = 2;

-- Check if both operations were successful


IF (condition to check if both updates were successful) THEN
COMMIT; -- Save changes
ELSE
ROLLBACK; -- Undo changes if any update failed
END IF;

Use Cases for Transactions:

• Banking Systems: Transactions are crucial in banking operations, such as


transferring money from one account to another, where both the debit and credit
operations must succeed or fail together.
• Inventory Management: When updating inventory levels, it's essential to ensure
that stock is correctly deducted and replenished across various items in one atomic
operation.
• E-commerce: Transactions ensure that the order placement process is reliable,
involving inventory checks, payment processing, and order confirmation.

Q. Explain terms START, COMMIT and ROLLBACK in MySQL

A.

In MySQL, START, COMMIT, and ROLLBACK are transaction control statements that
manage the execution of transactions. Each of these commands serves a specific purpose
in ensuring data integrity and consistency within a database. Here’s a detailed explanation
of each term:
1. START TRANSACTION

• Definition: The START TRANSACTION statement initiates a new transaction. This


means that any subsequent SQL statements executed will be part of this
transaction until a COMMIT or ROLLBACK is executed.
• Usage: Use this statement when you want to group multiple SQL operations
together as a single unit of work.
• Example:
START TRANSACTION;

2. COMMIT

• Definition: The COMMIT statement is used to save all the changes made during the
current transaction to the database. Once a transaction is committed, all changes
become permanent and are visible to other transactions.
• Usage: This command is used when all operations within the transaction have been
executed successfully, and you want to make those changes permanent.
• Example:
COMMIT;

3. ROLLBACK

• Definition: The ROLLBACK statement is used to undo all changes made during the
current transaction, reverting the database to its state before the transaction
began. This is useful when an error occurs or when you want to discard the changes
made during the transaction.
• Usage: Use this command when you encounter an issue or decide not to proceed
with the changes made in the transaction.
• Example:
ROLLBACK;

Example Scenario:

Here’s an example scenario that demonstrates the use of these transaction control
statements:
-- Start the transaction

START TRANSACTION;

-- Step 1: Deduct from source account

UPDATE accounts

SET balance = balance - 100

WHERE account_id = 1;

-- Step 2: Add to target account

UPDATE accounts

SET balance = balance + 100

WHERE account_id = 2;

-- Step 3: Check for errors

IF (SELECT balance FROM accounts WHERE account_id = 1) < 0 THEN

ROLLBACK; -- Rollback if source account has insufficient funds

SELECT 'Transaction rolled back due to insufficient funds.' AS message;

ELSE

COMMIT; -- Commit the transaction if successful

SELECT 'Transaction completed successfully.' AS message;

END IF;

Explanation of the Transaction Steps

1. START TRANSACTION: This begins the transaction.


2. UPDATE Statements: The first UPDATE deducts the amount from the source
account, and the second UPDATE adds the amount to the target account.
3. Error Check: Before committing, check whether the source account still has a valid
balance (e.g., non-negative). If there’s insufficient funds, ROLLBACK is executed,
undoing the changes.
4. COMMIT: If there are no issues, the transaction is committed, saving the changes to
the database.

Q. SELECT statement (From, Where, Group By, Having, Order By, Distinct)

A.

1. SELECT ... FROM


Description: The SELECT statement is used to retrieve data from one or more
tables. The FROM clause specifies the table(s) from which to retrieve the data.
• Example:
SELECT first_name, last_name
FROM students;

This retrieves the first_name and last_name columns from the students table.

2. WHERE


Description: The WHERE clause filters records based on specified conditions. Only
records that meet the conditions will be returned.
• Example:
SELECT *
FROM students
WHERE age >= 18;

This retrieves all columns from the students table for students aged 18 or older.

3. GROUP BY

• Description: The GROUP BY clause groups rows that have the same values in
specified columns into summary rows, often used with aggregate functions (like
COUNT, SUM, etc.).
• Example:
SELECT age, COUNT(*) AS student_count
FROM students
GROUP BY age;

This counts the number of students for each age and returns the result as
student_count.

4. HAVING

• Description: The HAVING clause filters records that work on summarized GROUP BY
data. It is used with aggregate functions to filter the results of the grouping.
• Example:
SELECT age, COUNT(*) AS student_count
FROM students
GROUP BY age
HAVING COUNT(*) > 1;

This retrieves ages with more than one student.

5. ORDER BY

• Description: The ORDER BY clause sorts the result set in ascending (ASC) or
descending (DESC) order based on one or more columns.
• Example:
SELECT first_name, last_name
FROM students
ORDER BY last_name ASC;

This retrieves all students' names and sorts them alphabetically by last_name in
ascending order.

6. DISTINCT

• Description: The DISTINCT keyword is used to return only unique (different) values
within a column.
• Example:
SELECT DISTINCT age
FROM students;
This retrieves a list of unique ages from the students table.

Q. Filtering Data by using conditions

Filtering data using conditions in SQL is primarily accomplished through the WHERE clause.
It allows you to specify criteria that must be met for the records to be included in the result
set. Here’s a guide on how to filter data effectively, including various operators and
examples.

1. Using the WHERE Clause

• Description: The WHERE clause filters records based on specified conditions. You
can use different operators to create complex conditions.

Example: Basic Filtering

SELECT * FROM students WHERE age >= 18;

This retrieves all columns from the students table where the age is 18 or older.

2. Comparison Operators

Common comparison operators include:

• = (Equal)
• != or <> (Not Equal)
• > (Greater Than)
• < (Less Than)
• >= (Greater Than or Equal)
• <= (Less Than or Equal)

Example: Using Different Operators

SELECT * FROM students WHERE age < 20; -- Less than 20

3. Logical Operators

You can combine multiple conditions using logical operators:


• AND: All conditions must be true.
• OR: At least one condition must be true.
• NOT: Reverses the truth value of the condition.

Example: Using AND

SELECT * FROM students WHERE age >= 18 AND gender = 'Female';

This retrieves records for female students aged 18 or older.

Example: Using OR

SELECT * FROM students WHERE age < 18 OR age > 25;

This retrieves records for students younger than 18 or older than 25.

Example: Using NOT

SELECT * FROM students WHERE NOT (age = 20);

This retrieves all records except for those where the age is 20.

4. IN Operator

The IN operator allows you to specify multiple values in a WHERE clause.

Example:

SELECT * FROM students WHERE age IN (18, 19, 20);

This retrieves records for students aged 18, 19, or 20.

5. BETWEEN Operator

The BETWEEN operator filters records within a specified range.

Example:

SELECT * FROM students WHERE age BETWEEN 18 AND 25;

This retrieves records for students aged 18 to 25, inclusive.


6. LIKE Operator

The LIKE operator is used for pattern matching in string fields.

Example:

SELECT * FROM students WHERE first_name LIKE 'J%';

This retrieves records where the first_name starts with the letter 'J'.

Example: Using Wildcards

• % represents zero or more characters.


• _ represents a single character.

SELECT * FROM students WHERE email LIKE '%@example.com';

This retrieves records where the email ends with @example.com.

Q. Simple and complex conditions using logical, arithmetic and relational operators
(=, !,=, <, >,<>, AND, OR, NOT, LIKE)

1. Relational Operators

These operators compare two values and return a boolean result (TRUE, FALSE, or
UNKNOWN).

Operator Description Example


= Equal to WHERE age =
20
!= or <> Not equal to WHERE age <>
20
> Greater than WHERE age >
20
< Less than WHERE age <
20
>= Greater than or equal WHERE age >=
to 18
<= Less than or equal to WHERE age <=
25
2. Arithmetic Operators

These operators perform arithmetic calculations.

Operator Description Example


+ Addition SELECT salary + bonus AS
total_income
- Subtraction SELECT salary - deductions AS
net_salary
* Multiplication SELECT price * quantity AS
total_price
/ Division SELECT total_amount / total_items AS
average

3. Logical Operators

These operators combine multiple conditions.

Operator Description Example


AND All conditions must be true WHERE age >= 18 AND gender =
'Female'
OR At least one condition must WHERE age < 18 OR age > 25
be true
NOT Reverses the truth value of a WHERE NOT (age = 20)
condition

4. LIKE Operator

Used for pattern matching in string fields.

Operator Description Example


LIKE Matches a specified WHERE first_name LIKE 'J%' (starts with 'J')
pattern
% Represents zero or WHERE email LIKE '%@example.com' (ends
more characters with @example.com)
_ Represents a single WHERE first_name LIKE '_an' (any character
character followed by 'an')

5. Simple Conditions

A simple condition uses a single operator to compare values.

Example:
SELECT * FROM students WHERE age > 18;

This retrieves all records for students older than 18.

6. Complex Conditions

Complex conditions combine multiple conditions using logical operators.

Example with AND:

SELECT * FROM students WHERE age >= 18 AND grade = 'A';

This retrieves records for students aged 18 or older with an 'A' grade.

Example with OR:

SELECT * FROM students WHERE age < 18 OR grade = 'F';

This retrieves records for students younger than 18 or who have an 'F' grade.

Example with NOT:

SELECT * FROM students WHERE NOT (age = 20);


This retrieves all records except those for students who are 20 years old.

7. Combining Conditions

You can create complex queries by combining various types of conditions.

Example:

SELECT * FROM students WHERE (age >= 18 AND gender = 'Female') OR


(grade = 'A' AND age < 16);

This retrieves records for female students aged 18 or older or students under 16 years old
who have an 'A' grade.

Q. Aggregate Functions- count, sum, avg, max, min.

Aggregate functions in SQL are used to perform calculations on a set of values and return a
single value. They are commonly used with the GROUP BY clause to summarize data.
Here’s an overview of the most commonly used aggregate functions: COUNT, SUM, AVG,
MAX, and MIN.

1. COUNT()

• Description: Counts the number of rows that match a specified condition or counts
all rows in a table.
• Syntax:
COUNT(column_name) -- Counts non-NULL values in the specified column
COUNT(*) -- Counts all rows

• Example:
SELECT COUNT(*) AS total_students FROM students;

This retrieves the total number of students in the students table.

2. SUM()

• Description: Calculates the total sum of a numeric column.


• Syntax:
SUM(column_name)

• Example:
SELECT SUM(salary) AS total_salary FROM employees;

This retrieves the total salary of all employees in the employees table.

3. AVG()

• Description: Calculates the average value of a numeric column.


• Syntax:
AVG(column_name)

• Example:
SELECT AVG(age) AS average_age FROM students;

This retrieves the average age of all students in the students table.
4. MAX()

• Description: Returns the maximum value from a specified column.


• Syntax:
MAX(column_name)

• Example:
SELECT MAX(score) AS highest_score FROM exam_results;

This retrieves the highest score from the exam_results table.

5. MIN()

• Description: Returns the minimum value from a specified column.


• Syntax:
MIN(column_name)

• Example:
SELECT MIN(age) AS youngest_student FROM students;

This retrieves the youngest student's age from the students table.

Q. Inner Join

The INNER JOIN is one of the most commonly used SQL joins. It is used to combine rows
from two or more tables based on a related column between them. Only rows that have
matching values in both tables are returned.

Syntax

SELECT columns FROM table1 INNER JOIN table2 ON table1.common_column =


table2.common_column;

Example Scenario

Let's consider two example tables: employees and departments.


1. employees Table:

employee_id first_name last_name department_id


1 John Doe 1
2 Jane Smith 2
3 Mike Johnson 1
4 Emily Davis 3

2. departments Table:

department_id department_name
1 HR
2 IT
3 Finance

INNER JOIN Example

To retrieve a list of employees along with their department names, you can use an INNER
JOIN as follows:

SELECT e.first_name, e.last_name, d.department_name FROM employees e


INNER JOIN departments d ON e.department_id = d.department_id;

Result Set

This query would return the following result:

first_name last_name department_name


John Doe HR
Mike Johnson HR
Jane Smith IT
Emily Davis Finance

Explanation of the Query

• SELECT: Specifies the columns to be retrieved. Here, we select first_name and


last_name from the employees table and department_name from the
departments table.
• FROM: Specifies the primary table (employees) and assigns it an alias (e).
• INNER JOIN: Combines records from the employees table with records from the
departments table.
• ON: Defines the condition for the join, which states that department_id from the
employees table must match department_id from the departments table.

Q. Nested Queries (Only upto two levels): Using sub queries, sub query search
conditions, sub queries & joins, nested sub queries, correlated sub queries, sub
queries in the HAVING clause.

Nested queries, or subqueries, are queries that are embedded within another SQL query.
They allow you to perform complex operations and can be used in various clauses,
including the SELECT, WHERE, FROM, and HAVING clauses. Here's an overview of nested
queries, including subqueries, subquery search conditions, and their various forms.

1. Subqueries

Description: A subquery is a query nested inside another query. Subqueries can return a
single value, a list of values, or a complete result set.

Example:

SELECT first_name, last_name


FROM employees
WHERE employee_id IN (SELECT employee_id FROM projects WHERE
project_name = 'Project A');

This retrieves the names of employees who are working on "Project A."

2. Subquery Search Conditions

Description: Subqueries can be used as conditions in the WHERE clause to filter results
based on the result of the subquery.

Example:

SELECT first_name, last_name


FROM employees
WHERE department_id = (SELECT department_id FROM departments WHERE
department_name = 'HR');

This retrieves the names of employees who belong to the HR department.

3. Subqueries and Joins

Description: You can use subqueries in conjunction with joins to retrieve data from
multiple tables.

Example:

SELECT e.first_name, e.last_name, d.department_name


FROM employees e
INNER JOIN departments d ON e.department_id = d.department_id
WHERE e.employee_id IN (SELECT employee_id FROM project_assignments
WHERE project_id = 1);

This retrieves employee names along with their department names for employees assigned
to a specific project.

4. Nested Subqueries

Description: A nested subquery is a subquery within another subquery. You can use them
to perform more complex filtering.

Example:

SELECT first_name, last_name


FROM employees
WHERE department_id IN (
SELECT department_id
FROM departments
WHERE location_id IN (
SELECT location_id
FROM locations
WHERE city = 'New York'
)
);

This retrieves the names of employees who work in departments located in New York.
5. Correlated Subqueries

Description: A correlated subquery is a subquery that references a column from the outer
query. It is executed for each row processed by the outer query.

Example:

SELECT e1.first_name, e1.last_name


FROM employees e1
WHERE e1.salary > (SELECT AVG(salary) FROM employees e2 WHERE
e1.department_id = e2.department_id);

This retrieves the names of employees whose salary is greater than the average salary of
their respective departments.

6. Subqueries in the HAVING Clause

Description: Subqueries can also be used in the HAVING clause to filter results based on
aggregate calculations.

Example:

SELECT department_id, COUNT(*) AS employee_count


FROM employees
GROUP BY department_id
HAVING COUNT(*) > (SELECT AVG(employee_count)
FROM (SELECT COUNT(*) AS employee_count
FROM employees
GROUP BY department_id) AS subquery);

This retrieves the departments with more employees than the average number of
employees per department.

Summary of Nested Queries

Type Description Example


Simple A query inside another SELECT ... WHERE employee_id IN
Subquery query. (SELECT ...)
Subquery Used in WHERE clause to WHERE department_id = (SELECT
Search filter results based on department_id FROM ...)
Conditions subquery.
Subqueries & Combine subqueries with SELECT ... FROM employees INNER
Joins joins to retrieve data from JOIN departments ON ... WHERE
multiple tables. employee_id IN (SELECT ...)
Nested Subquery within another WHERE department_id IN (SELECT
Subqueries subquery. department_id FROM departments
WHERE location_id IN
(SELECT ...))
Correlated Subquery that references WHERE salary > (SELECT
Subqueries a column from the outer AVG(salary) FROM employees e2
query. WHERE e1.department_id =
e2.department_id)
Subqueries in Used in HAVING clause to HAVING COUNT(*) > (SELECT
HAVING filter grouped results. AVG(employee_count) FROM (SELECT
COUNT(*) FROM employees GROUP
BY ...))

You might also like