Database and MySQL I
Database and MySQL I
Database and MySQL I
• Database
• Tables
• Fields
Q. 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
• 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
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.
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.
•
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.
•
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.
• 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.
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.
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.
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:
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:
5. LONGTEXT:
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:
8. BOOLEAN:
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:
11. DOUBLE:
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:
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');
1. Creating a Database
This command creates a database named school. You can use the USE statement to
select the database you want to work with.
Example:
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';
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:
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 ...;
1. CREATE
Example:
USE school;
3. ALTER
a. Add Column
Example:
b. Remove Column
Example:
c. Change Column
Example:
4. RENAME
5. SHOW
SHOW DATABASES;
SHOW TABLES;
6. DESCRIBE
Description: Provides details about a table structure (columns, types, and constraints).
• Usage: Displays the structure of a specified table, including columns, types, and
constraints.
• Example:
DESCRIBE students;
b. SHOW COLUMNS
• Usage: Provides information about the specified table, including size, number of
rows, and engine type.
• Example:
SHOW TABLE STATUS LIKE 'students';
d. SHOW DATABASES
7. DROP
a. Drop Table
Example:
b. Drop Column
Example:
ALTER TABLE learners
DROP COLUMN email;
c. Drop Database
Example:
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:
• 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:
• 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:
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:
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:
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.
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.
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:
In this example:
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
1. NOT NULL
2. UNIQUE
3. CHECK
4. DEFAULT
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)
);
A.
Example of Auto-Increment:
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:
After these inserts, the user_id column will automatically have the following values:
You can reset the auto-increment value using the ALTER TABLE statement:
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.
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.
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.
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:
START TRANSACTION;
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
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;
UPDATE accounts
WHERE account_id = 1;
UPDATE accounts
WHERE account_id = 2;
ELSE
END IF;
Q. SELECT statement (From, Where, Group By, Having, Order By, Distinct)
A.
•
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;
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.
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.
• Description: The WHERE clause filters records based on specified conditions. You
can use different operators to create complex conditions.
This retrieves all columns from the students table where the age is 18 or older.
2. Comparison Operators
• = (Equal)
• != or <> (Not Equal)
• > (Greater Than)
• < (Less Than)
• >= (Greater Than or Equal)
• <= (Less Than or Equal)
3. Logical Operators
Example: Using OR
This retrieves records for students younger than 18 or older than 25.
This retrieves all records except for those where the age is 20.
4. IN Operator
Example:
5. BETWEEN Operator
Example:
Example:
This retrieves records where the first_name starts with the letter 'J'.
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).
3. Logical Operators
4. LIKE Operator
5. Simple Conditions
Example:
SELECT * FROM students WHERE age > 18;
6. Complex Conditions
This retrieves records for students aged 18 or older with an 'A' grade.
This retrieves records for students younger than 18 or who have an 'F' grade.
7. Combining Conditions
Example:
This retrieves records for female students aged 18 or older or students under 16 years old
who have an 'A' grade.
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;
2. SUM()
• Example:
SELECT SUM(salary) AS total_salary FROM employees;
This retrieves the total salary of all employees in the employees table.
3. AVG()
• Example:
SELECT AVG(age) AS average_age FROM students;
This retrieves the average age of all students in the students table.
4. MAX()
• Example:
SELECT MAX(score) AS highest_score FROM exam_results;
5. MIN()
• 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
Example Scenario
2. departments Table:
department_id department_name
1 HR
2 IT
3 Finance
To retrieve a list of employees along with their department names, you can use an INNER
JOIN as follows:
Result Set
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:
This retrieves the names of employees who are working on "Project A."
Description: Subqueries can be used as conditions in the WHERE clause to filter results
based on the result of the subquery.
Example:
Description: You can use subqueries in conjunction with joins to retrieve data from
multiple tables.
Example:
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:
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:
This retrieves the names of employees whose salary is greater than the average salary of
their respective departments.
Description: Subqueries can also be used in the HAVING clause to filter results based on
aggregate calculations.
Example:
This retrieves the departments with more employees than the average number of
employees per department.