MY SQL Interview Questions and Answers
MY SQL Interview Questions and Answers
What is MySQL?
MySQL is an open-source relational database management system (RDBMS) that uses Structured Query Language (SQL) to manage and manipulate databases.
What are the features of MySQL?
Open-source.
High performance and scalability.
Secure with user access control.
Cross-platform support.
Supports large databases.
Provides replication and clustering.
What are the advantages of using MySQL?
Free and open-source.
Easy to use with a large community.
High security and scalability.
Strong support for transactions and foreign keys.
Works well with all major operating systems.
Explain the difference between SQL and MySQL.
SQL (Structured Query Language): A language used for querying and managing databases.
MySQL: A database management system that implements SQL.
What is a database?
A database is a structured collection of data that can be accessed, managed, and updated electronically.
What is a table in MySQL?
A table is a collection of related data in rows and columns in a database.
What are fields and columns in MySQL?
Field: A single piece of data in a table (a cell).
Column: A vertical set of fields within a table.
What are constraints in MySQL?
Constraints are rules applied to columns in a table to ensure data integrity. Examples include PRIMARY KEY, FOREIGN KEY, UNIQUE, NOT NULL, and CHECK.
What is a primary key?
A primary key is a column (or set of columns) that uniquely identifies each row in a table. It ensures that the values are unique and not NULL.
What is a foreign key?
A foreign key is a column that creates a relationship between two tables, referencing the primary key of another table to enforce referential integrity.
What are unique keys?
Unique keys ensure that all the values in a column are distinct, but unlike the primary key, a table can have multiple unique keys and can include NULL values.
What is normalization in MySQL?
Normalization is the process of organizing data in a database to reduce redundancy and improve data integrity by dividing larger tables into smaller ones and defining relationships between them.
What is denormalization?
Denormalization is the process of combining multiple tables into one to improve query performance by reducing the need for joins.
What is a stored procedure?
A stored procedure is a set of SQL statements stored in the database that can be executed as a single unit. It can accept parameters and return results.
What are indexes in MySQL?
Indexes are used to improve the performance of queries by allowing faster retrieval of records from a table. They are created on columns that are frequently searched or sorted.
Explain the difference between clustered and non-clustered indexes.
Clustered Index: Reorders the physical order of the rows to match the index order. A table can only have one clustered index.
Non-clustered Index: Maintains a separate structure that points to the original rows in the table. A table can have multiple non-clustered indexes.
What is a composite key in MySQL?
A composite key is a primary key made up of two or more columns in a table to uniquely identify rows.
What is auto-increment in MySQL?
Auto-increment is a feature that automatically generates a unique number for each row in a table, typically used for primary key columns.
What is the use of the DISTINCT keyword?
The DISTINCT keyword is used to return unique values in a query result, removing duplicates.
What is a query?
A query is a request for data or information from a database table or multiple tables.
What are the different types of joins in MySQL?
INNER JOIN: Returns records that have matching values in both tables.
LEFT JOIN (LEFT OUTER JOIN): Returns all records from the left table and matched records from the right table.
RIGHT JOIN (RIGHT OUTER JOIN): Returns all records from the right table and matched records from the left table.
FULL JOIN (FULL OUTER JOIN): Returns all records when there is a match in either left or right table.
Explain the difference between INNER JOIN and OUTER JOIN.
INNER JOIN: Only returns rows where there is a match in both tables.
OUTER JOIN (LEFT/RIGHT): Returns all rows from one table and the matched rows from the other table, with NULL for unmatched rows.
How do you perform a LEFT JOIN in MySQL?
sql
Copy code
SELECT columns
FROM table1
LEFT JOIN table2
ON table1.column = table2.column;
What is a RIGHT JOIN?
A RIGHT JOIN returns all rows from the right table and matched rows from the left table. If no match is found, NULL is returned for columns of the left table.
What is a FULL JOIN?
A FULL JOIN (or FULL OUTER JOIN) returns all records from both tables, with NULLs in places where no match exists in the other table.
What is the WHERE clause?
The WHERE clause is used to filter records based on specific conditions in a query.
What is the GROUP BY clause?
The GROUP BY clause groups rows that have the same values in specified columns into summary rows, often used with aggregate functions.
What is the HAVING clause?
The HAVING clause is similar to WHERE but is used to filter groups created by GROUP BY, typically with aggregate functions.
What is the difference between WHERE and HAVING?
WHERE: Filters rows before grouping.
HAVING: Filters groups after aggregation.
How do you perform a wildcard search using the LIKE operator in MySQL?
The LIKE operator is used for pattern matching, often with % (matches any string of any length) or _ (matches a single character). Example:
sql
Copy code
SELECT * FROM users WHERE name LIKE 'A%';
How do you use the IN operator in MySQL?
The IN operator is used to filter records based on a list of values. It is a shorthand for multiple OR conditions. Example:
sql
Copy code
SELECT * FROM users WHERE country IN ('USA', 'Canada', 'Mexico');
What is the BETWEEN operator?
The BETWEEN operator is used to filter the result set within a certain range. It includes both the start and end values. Example:
sql
Copy code
SELECT * FROM orders WHERE order_date BETWEEN '2023-01-01' AND '2023-12-31';
How do you use the LIMIT clause in MySQL?
The LIMIT clause is used to specify the number of rows to return in a query. Example:
sql
Copy code
SELECT * FROM customers LIMIT 10; -- Returns the first 10 records
What is the purpose of the UNION clause?
The UNION clause combines the result sets of two or more SELECT statements into a single result set, removing duplicates by default. Example:
sql
Copy code
SELECT name FROM employees
UNION
SELECT name FROM managers;
How do you fetch only the first 5 records from a table?
Use the LIMIT clause to specify the number of records:
sql
Copy code
SELECT * FROM table_name LIMIT 5;
How do you retrieve the current date and time in MySQL?
Use the NOW() function to retrieve the current date and time:
sql
Copy code
SELECT NOW();
What is the difference between CHAR and VARCHAR data types?
CHAR: A fixed-length string. The length is always the same, padded with spaces if necessary.
VARCHAR: A variable-length string. It only uses as much space as needed.
How do you concatenate two strings in MySQL?
Use the CONCAT() function to concatenate two or more strings. Example:
sql
Copy code
SELECT CONCAT(first_name, ' ', last_name) AS full_name FROM users;
How do you convert a string to lowercase or uppercase in MySQL?
Convert to lowercase using LOWER():
sql
Copy code
SELECT LOWER(name) FROM users;
Convert to uppercase using UPPER():
sql
Copy code
SELECT UPPER(name) FROM users;
How do you get the length of a string in MySQL?
Use the LENGTH() function to get the length of a string:
sql
Copy code
SELECT LENGTH(name) FROM users;
What is a subquery in MySQL?
A subquery is a query nested inside another query. It can return a single value, a row, or a table. Example:
sql
Copy code
SELECT name FROM users WHERE id = (SELECT manager_id FROM employees WHERE employee_id = 5);
What are correlated subqueries?
A correlated subquery is a subquery that refers to columns from the outer query. It is executed once for every row processed by the outer query. Example:
sql
Copy code
SELECT e1.name FROM employees e1 WHERE e1.salary > (SELECT AVG(e2.salary) FROM employees e2 WHERE e2.department = e1.department);
Explain EXISTS and NOT EXISTS in subqueries.
EXISTS: Returns TRUE if the subquery returns any rows.
NOT EXISTS: Returns TRUE if the subquery returns no rows. Example:
sql
Copy code
SELECT name FROM employees WHERE EXISTS (SELECT * FROM managers WHERE employees.manager_id = managers.id);
How do you optimize queries in MySQL?
Use indexes on columns used in WHERE, ORDER BY, and JOIN clauses.
Avoid using SELECT *; specify the required columns.
Use EXPLAIN to analyze the query execution plan.
Avoid correlated subqueries when possible.
Use proper data types for columns.
What is the difference between COUNT(), SUM(), AVG(), MIN(), and MAX() functions?
COUNT(): Returns the number of rows.
SUM(): Returns the sum of values in a numeric column.
AVG(): Returns the average value of a numeric column.
MIN(): Returns the smallest value.
MAX(): Returns the largest value.
How do you use CASE statements in MySQL?
The CASE statement allows you to perform conditional logic in queries:
sql
Copy code
SELECT name,
CASE
WHEN score >= 90 THEN 'A'
WHEN score >= 80 THEN 'B'
ELSE 'C'
END AS grade
FROM students;
What is the COALESCE() function used for?
The COALESCE() function returns the first non-NULL value from a list of arguments:
sql
Copy code
SELECT COALESCE(email, phone, 'N/A') FROM users;
What is a self-join in MySQL?
A self-join is a regular join, but the table is joined with itself. Example:
sql
Copy code
SELECT e1.name, e2.name AS manager_name
FROM employees e1
JOIN employees e2 ON e1.manager_id = e2.id;
What is a CROSS JOIN?
A CROSS JOIN returns the Cartesian product of two tables. Every row from the first table is combined with every row from the second table.
sql
Copy code
SELECT * FROM products CROSS JOIN categories;
How do you perform a DELETE operation in MySQL?
Use the DELETE statement to remove rows from a table:
sql
Copy code
DELETE FROM users WHERE id = 5;
What are aggregate functions in MySQL?
Aggregate functions perform calculations on multiple rows and return a single result. Examples include COUNT(), SUM(), AVG(), MIN(), and MAX().
What are string functions in MySQL?
Common string functions include:
CONCAT(): Concatenates strings.
LOWER(): Converts a string to lowercase.
UPPER(): Converts a string to uppercase.
LENGTH(): Returns the length of a string.
SUBSTRING(): Extracts a substring from a string.
What are date functions in MySQL?
Common date functions include:
NOW(): Returns the current date and time.
CURDATE(): Returns the current date.
DATE_ADD(): Adds a specified time interval to a date.
DATEDIFF(): Returns the difference between two dates.
How do you extract year, month, or day from a date in MySQL?
Use the YEAR(), MONTH(), and DAY() functions:
sql
Copy code
SELECT YEAR(order_date), MONTH(order_date), DAY(order_date) FROM orders;
How do you add or subtract days to/from a date in MySQL?
Use the DATE_ADD() and DATE_SUB() functions:
sql
Copy code
SELECT DATE_ADD('2023-01-01', INTERVAL 10 DAY);
SELECT DATE_SUB('2023-01-01', INTERVAL 5 DAY);
What is the DATEDIFF() function used for?
The DATEDIFF() function returns the difference in days between two dates:
sql
Copy code
SELECT DATEDIFF('2023-12-31', '2023-01-01');
How do you use mathematical functions like ABS(), ROUND(), and CEIL() in MySQL?
ABS(): Returns the absolute value.
ROUND(): Rounds a number to a specified number of decimal places.
CEIL(): Rounds a number up to the nearest integer. Example:
SELECT ABS(-15), ROUND(123.456, 2), CEIL(4.1);
What are NULL functions in MySQL?
NULL functions are used to handle NULL values, such as:
IFNULL(): Returns an alternate value if the expression is NULL.
COALESCE(): Returns the first non-NULL value from a list.
How do you handle NULL values in queries?
Use the IS NULL and IS NOT NULL conditions to check for NULL values:
sql
Copy code
SELECT * FROM users WHERE email IS NULL;
What is the IFNULL() function?
The IFNULL() function returns the second argument if the first argument is NULL, otherwise, it returns the first argument:
sql
Copy code
SELECT IFNULL(phone, 'N/A') FROM users;
What is MySQL workbench?
MySQL Workbench is a unified visual tool for database architects, developers, and DBAs. It provides functionalities like database design, SQL development, administration, and data modeling.
How do you create a database in MySQL?
Use the CREATE DATABASE statement:
sql
Copy code
CREATE DATABASE database_name;
How do you create a table in MySQL?
Use the CREATE TABLE statement:
sql
Copy code
CREATE TABLE table_name (
id INT AUTO_INCREMENT PRIMARY KEY,
name VARCHAR(100),
age INT
);
What is the syntax to drop a table in MySQL?
Use the DROP TABLE statement:
sql
Copy code
DROP TABLE table_name;
How do you alter an existing table in MySQL?
Use the ALTER TABLE statement to modify an existing table:
sql
Copy code
ALTER TABLE table_name ADD column_name INT;
ALTER TABLE table_name DROP COLUMN column_name;
ALTER TABLE table_name MODIFY column_name VARCHAR(255);
What is the purpose of the SHOW command in MySQL?
The SHOW command is used to display information about databases, tables, columns, and server status. Example:
sql
Copy code
SHOW DATABASES;
SHOW TABLES;
SHOW COLUMNS FROM table_name;
What is the purpose of the DESCRIBE command in MySQL?
The DESCRIBE command provides detailed information about a table's structure, including column names, data types, and constraints:
sql
Copy code
DESCRIBE table_name;
What is a view in MySQL?
A view is a virtual table based on the result set of a SQL query. It can simplify complex queries and provide a layer of security by restricting access to certain data.
sql
Copy code
CREATE VIEW view_name AS SELECT columns FROM table_name WHERE condition;
How do you update records in MySQL?
Use the UPDATE statement to modify existing records:
sql
Copy code
UPDATE table_name SET column1 = value1, column2 = value2 WHERE condition;
What is the purpose of the TRUNCATE command?
The TRUNCATE command removes all records from a table without logging individual row deletions, which makes it faster than DELETE. However, it cannot be rolled back if not used with a transaction.
What is a transaction in MySQL?
A transaction is a sequence of one or more SQL statements executed as a single unit of work. It ensures data integrity, and either all operations are completed successfully or none are applied.
How do you start a transaction in MySQL?
Use the START TRANSACTION statement to begin a transaction:
sql
Copy code
START TRANSACTION;
How do you commit and rollback a transaction in MySQL?
Commit: Use COMMIT to save the changes made during the transaction.
sql
Copy code
COMMIT;
Rollback: Use ROLLBACK to undo the changes made during the transaction.
sql
Copy code
ROLLBACK;
What are isolation levels in MySQL?
Isolation levels define the degree to which the operations in one transaction are isolated from those in other transactions. Common isolation levels include:
READ UNCOMMITTED
READ COMMITTED
REPEATABLE READ
SERIALIZABLE
How do you grant and revoke permissions in MySQL?
Grant permissions: Use the GRANT statement:
sql
Copy code
GRANT SELECT, INSERT ON database_name.* TO 'username'@'host';
Revoke permissions: Use the REVOKE statement:
sql
Copy code
REVOKE SELECT, INSERT ON database_name.* FROM 'username'@'host';
What is a stored function in MySQL?
A stored function is a stored program that can be called with a SELECT statement. It can accept parameters and return a single value.
sql
Copy code
CREATE FUNCTION function_name(parameter_list) RETURNS return_data_type AS
BEGIN
-- function body
END;
What are triggers in MySQL?
Triggers are special types of stored procedures that automatically execute in response to certain events on a particular table, such as INSERT, UPDATE, or DELETE.
How do you create a trigger in MySQL?
Use the CREATE TRIGGER statement:
sql
Copy code
CREATE TRIGGER trigger_name
BEFORE INSERT ON table_name
FOR EACH ROW
BEGIN
-- trigger body
END;
What is the difference between a function and a procedure in MySQL?
Function: Returns a single value, can be used in SQL statements, and cannot change database state.
Procedure: Does not return a value, can perform actions like modifying database state, and cannot be used directly in SQL statements.
What is MySQL replication?
MySQL replication is the process of copying data from one MySQL database server (master) to one or more MySQL database servers (slaves) to ensure data redundancy and availability.
How do you analyze a query's performance in MySQL?
Use the EXPLAIN statement before a query to see how MySQL executes it, which helps identify potential performance issues:
sql
Copy code
EXPLAIN SELECT * FROM users WHERE id = 1;
What are some common ways to optimize MySQL queries?
Use indexes on frequently searched columns.
Avoid using SELECT *; specify required columns.
Optimize JOIN conditions and avoid unnecessary joins.
Use WHERE clauses to filter data early.
Avoid using subqueries when possible.
What is an index?
An index is a database structure that improves the speed of data retrieval operations on a database table at the cost of additional space and slower writes.
How do you create an index in MySQL?
Use the CREATE INDEX statement:
sql
Copy code
CREATE INDEX index_name ON table_name (column_name);
What are the benefits and drawbacks of using indexes?
Benefits: Faster data retrieval, improved performance for search queries.
Drawbacks: Increased storage requirements, slower write operations (INSERT, UPDATE, DELETE).
What is a composite index?
A composite index is an index on two or more columns in a table, which improves performance for queries that filter or sort based on multiple columns.
What is the purpose of the ANALYZE TABLE statement?
The ANALYZE TABLE statement updates the statistics about a table, helping the MySQL query optimizer make better decisions about query execution plans.
What is query caching in MySQL?
Query caching is a feature that stores the result set of SELECT queries, allowing faster retrieval of results for identical queries without re-executing them.
How do you enable or disable query caching in MySQL?
You can enable or disable query caching by setting the query_cache_type system variable:
sql
Copy code
SET GLOBAL query_cache_type = ON; -- Enable
SET GLOBAL query_cache_type = OFF; -- Disable
What is the difference between UNION and UNION ALL?
UNION: Combines the result sets of two queries and removes duplicates.
UNION ALL: Combines the result sets of two queries and includes all duplicates.
These answers cover the next set of 61-90 questions. Let me know if you'd like me to continue with the remaining questions!
4o mini
You said:
yes Continue
ChatGPT said:
ChatGPT
Here are the answers to the next set of questions 91 to 120 from the MySQL interview questions:
What is a foreign key in MySQL?
A foreign key is a field (or a group of fields) in one table that uniquely identifies a row of another table. It establishes a link between the data in two tables, ensuring referential integrity.
sql
Copy code
CREATE TABLE orders (
order_id INT,
customer_id INT,
FOREIGN KEY (customer_id) REFERENCES customers(customer_id)
);
What is normalization?
Normalization is the process of organizing the fields and tables of a database to minimize redundancy and dependency. It typically involves dividing large tables into smaller ones and defining relationships among them.
What are the different normal forms in normalization?
First Normal Form (1NF): Each column contains atomic values; no repeating groups.
Second Normal Form (2NF): All non-key attributes are fully functional dependent on the primary key.
Third Normal Form (3NF): No transitive dependency; non-key attributes do not depend on other non-key attributes.
Boyce-Codd Normal Form (BCNF): A stronger version of 3NF.
What is denormalization?
Denormalization is the process of deliberately introducing redundancy into a database by merging tables, which can improve read performance at the cost of increased storage and potential data integrity issues.
What are the ACID properties in database transactions?
ACID stands for:
Atomicity: Transactions are all-or-nothing.
Consistency: Transactions bring the database from one valid state to another.
Isolation: Transactions are executed independently of one another.
Durability: Once a transaction is committed, it remains so, even in the event of a system failure.
What is a stored procedure in MySQL?
A stored procedure is a set of SQL statements that can be stored in the database and executed as a single unit. It can accept parameters and can contain complex logic.
sql
Copy code
CREATE PROCEDURE procedure_name (IN parameter_name data_type)
BEGIN
-- procedure body
END;
How do you call a stored procedure in MySQL?
Use the CALL statement:
sql
Copy code
CALL procedure_name(parameter_value);
What is the purpose of the SHOW WARNINGS statement?
The SHOW WARNINGS statement is used to display warnings generated by the last SQL statement, which can help identify issues without failing the execution.
What are user-defined functions in MySQL?
User-defined functions (UDFs) allow users to create custom functions that can be used in SQL statements. They can return a single value and can accept multiple parameters.
What is the difference between the TRUNCATE and DELETE commands?
- TRUNCATE: Removes all rows from a table quickly and cannot be rolled back. It resets auto-increment counters. - DELETE: Removes rows based on a condition and can be rolled back. It logs individual row deletions.
How do you ensure database security in MySQL?
- Use strong passwords for MySQL users. - Limit user permissions based on roles. - Use SSL for secure connections. - Regularly update MySQL to patch vulnerabilities. - Regularly backup the database.
What is data encryption, and how is it implemented in MySQL?
Data encryption protects sensitive data by converting it into a format that cannot be read without a decryption key. MySQL supports data encryption through various methods, including column-level encryption and using SSL connections.
How do you create a backup of a MySQL database?
Use the mysqldump utility to create a backup: bash mysqldump -u username -p database_name > backup_file.sql
How do you restore a MySQL database from a backup?
Use the mysql command to restore a backup: bash mysql -u username -p database_name < backup_file.sql
What is the purpose of the MySQL error log?
The MySQL error log records information about errors that occur while the server is running, including startup and shutdown events, which helps diagnose issues.
What are the different types of MySQL backups?
- Full Backup: A complete copy of the database. - Incremental Backup: Only the data that has changed since the last backup is copied. - Differential Backup: Copies all changes made since the last full backup.
What is the purpose of the MySQL general log?
The general log records all SQL queries received by the server, useful for debugging and monitoring database activity.
What is a binary log in MySQL?
The binary log records all changes made to the database, including both data changes and schema changes. It is used for replication and recovery purposes.
How do you enable the binary log in MySQL?
You can enable the binary log by adding the following line to the MySQL configuration file (my.cnf or my.ini): ini log-bin=mysql-bin
What is MySQL performance tuning?
MySQL performance tuning involves optimizing database settings and queries to improve performance, including adjusting buffer sizes, optimizing queries, and using appropriate indexing.
What is the MySQL architecture?
MySQL architecture consists of several components: - Client Layer: The interface for users and applications to interact with MySQL. - SQL Layer: Processes SQL queries and translates them into internal commands. - Storage Engine Layer: Manages how data is stored, retrieved, and updated.
What is a storage engine in MySQL?
A storage engine is the component of MySQL that handles the storage and retrieval of data. Each storage engine has different features and capabilities. Common storage engines include InnoDB and MyISAM.
What is the InnoDB storage engine?
InnoDB is a MySQL storage engine that supports transactions, foreign keys, and row-level locking, making it suitable for high-concurrency applications.
What is the MyISAM storage engine?
MyISAM is a MySQL storage engine that is optimized for read-heavy workloads. It supports table-level locking but does not support transactions or foreign keys.
What are the advantages of using InnoDB over MyISAM?
- InnoDB supports transactions and ACID compliance. - InnoDB provides foreign key constraints. - InnoDB offers better crash recovery and data integrity.
What are the disadvantages of using MyISAM?
- MyISAM does not support transactions or foreign keys. - MyISAM can suffer from table-level locking, leading to concurrency issues. - MyISAM is less reliable in terms of data integrity in case of crashes.
How does MySQL handle concurrency?
MySQL uses different locking mechanisms, such as row-level locking in InnoDB, to manage concurrent access to data. It also implements multi-version concurrency control (MVCC) to allow transactions to read data without locking it.
What is a deadlock in MySQL?
A deadlock occurs when two or more transactions are waiting for each other to release locks, resulting in a standstill. MySQL detects deadlocks and automatically resolves them by rolling back one of the transactions.
How do you prevent deadlocks in MySQL?
- Access tables and rows in a consistent order across transactions. - Keep transactions short and reduce the time locks are held. - Use lower isolation levels where possible.
What is the difference between a primary key and a unique key in MySQL?
- Primary Key: Uniquely identifies each record in a table, cannot be NULL, and there can only be one primary key per table. - Unique Key: Ensures all values in a column are unique, can contain NULL values, and a table can have multiple unique keys.
What are the different data types available in MySQL?
MySQL supports several data types, including: - Numeric Types: INT, FLOAT, DOUBLE, DECIMAL. - String Types: CHAR, VARCHAR, TEXT, BLOB. - Date and Time Types: DATE, TIME, DATETIME, TIMESTAMP.
What is the difference between VARCHAR and CHAR?
- CHAR: A fixed-length string; if the string is shorter than the defined length, it is padded with spaces. - VARCHAR: A variable-length string; it uses only the space needed for the actual string, plus one or two bytes for length storage.
What is the difference between TIMESTAMP and DATETIME?
- TIMESTAMP: Automatically updates to the current date and time when a row is created or updated. It has a range from 1970 to 2038. - DATETIME: Stores date and time without automatic updates, with a range from 1000 to 9999.
What are aggregate functions in MySQL?
Aggregate functions perform calculations on a set of values and return a single value. Common aggregate functions include: - COUNT(): Counts the number of rows. - SUM(): Calculates the total of a numeric column. - AVG(): Computes the average of a numeric column. - MAX(): Returns the maximum value. - MIN(): Returns the minimum value.
What is the purpose of the GROUP BY clause?
The GROUP BY clause groups rows that have the same values in specified columns into summary rows, often used with aggregate functions to produce summary statistics.
How do you use the HAVING clause in MySQL?
The HAVING clause is used to filter records that work on summarized GROUP BY results, allowing you to set conditions on aggregate functions. sql SELECT department, COUNT(*) FROM employees GROUP BY department HAVING COUNT(*) > 5;
What is the COALESCE function in MySQL?
The COALESCE function returns the first non-NULL value in a list of arguments. sql SELECT COALESCE(column1, column2, 'Default Value') AS result FROM table_name;
What is the purpose of the CONCAT function in MySQL?
The CONCAT function is used to concatenate two or more strings together. sql SELECT CONCAT(first_name, ' ', last_name) AS full_name FROM users;
How do you find the length of a string in MySQL?
Use the LENGTH function to find the length of a string: sql SELECT LENGTH(column_name) AS string_length FROM table_name;
What is the purpose of the SUBSTRING function in MySQL?
The SUBSTRING function extracts a substring from a string, starting from a specified position. sql SELECT SUBSTRING(column_name, start_position, length) AS substring FROM table_name;
What is a self-join in MySQL?
A self-join is a regular join that joins a table with itself, allowing you to compare rows within the same table. sql SELECT a.name AS employee, b.name AS manager FROM employees a JOIN employees b ON a.manager_id = b.id;
What is the use of the LIMIT clause in MySQL?
The LIMIT clause is used to specify the maximum number of records to return from a query. sql SELECT * FROM table_name LIMIT 10;
What is the purpose of the ORDER BY clause?
The ORDER BY clause is used to sort the result set of a query by one or more columns, either in ascending or descending order. sql SELECT * FROM table_name ORDER BY column_name ASC;
How do you perform a left join in MySQL?
A left join returns all records from the left table and matched records from the right table. If there is no match, NULL values are returned for columns from the right table. sql SELECT a.*, b.* FROM table_a a LEFT JOIN table_b b ON a.id = b.id;
What is a cross join in MySQL?
A cross join returns the Cartesian product of two tables, meaning every row in the first table is combined with every row in the second table. sql SELECT * FROM table_a CROSS JOIN table_b;
What is the purpose of the UNION operator?
The UNION operator combines the results of two or more SELECT statements into a single result set, removing duplicates. To include duplicates, use UNION ALL.
What is a subquery in MySQL?
A subquery is a query nested inside another SQL query, often used to return data for the main query's conditions. sql SELECT * FROM employees WHERE department_id IN (SELECT id FROM departments WHERE name = 'Sales');
What is a common table expression (CTE)?
A CTE is a temporary result set defined within the execution scope of a single SELECT, INSERT, UPDATE, or DELETE statement. It improves readability and organization of complex queries. sql WITH department_counts AS ( SELECT department_id, COUNT(*) AS employee_count FROM employees GROUP BY department_id ) SELECT * FROM department_counts;
How do you use the CASE statement in MySQL?
The CASE statement allows you to perform conditional logic in SQL queries. sql SELECT name, CASE WHEN age < 18 THEN 'Minor' ELSE 'Adult' END AS age_group FROM users;
What is a temporary table in MySQL?
A temporary table is a table that is created temporarily and exists only for the duration of a session. It is automatically dropped when the session ends. sql CREATE TEMPORARY TABLE temp_table (id INT, name VARCHAR(100));
What are triggers used for in MySQL?
Triggers are used to automatically execute a specified action in response to certain events on a particular table, such as INSERT, UPDATE, or DELETE operations.
How can you import a CSV file into MySQL?
Use the LOAD DATA INFILE command to import a CSV file into a MySQL table: sql LOAD DATA INFILE '/path/to/file.csv' INTO TABLE table_name FIELDS TERMINATED BY ',' ENCLOSED BY '"' LINES TERMINATED BY '\n' IGNORE 1 ROWS;
What is the difference between a view and a table?
- View: A virtual table based on the result of a SELECT query; it does not store data physically. - Table: A physical storage structure that holds data.
How do you remove a view in MySQL?
Use the DROP VIEW statement: sql DROP VIEW view_name;
What is the purpose of the INFORMATION_SCHEMA database?
The INFORMATION_SCHEMA is a virtual database that provides access to database metadata, including information about tables, columns, constraints, and other objects.
How can you check the current version of MySQL?
Use the SELECT VERSION(); statement or check the MySQL server status: sql SHOW VARIABLES LIKE 'version';
What are the types of joins in MySQL?
The main types of joins include: - INNER JOIN - LEFT JOIN - RIGHT JOIN - FULL OUTER JOIN - CROSS JOIN
How do you optimize a MySQL query?
- Use appropriate indexes. - Analyze the query execution plan with EXPLAIN. - Avoid unnecessary columns in SELECT statements. - Limit the result set using LIMIT. - Optimize JOIN operations.
What is the difference between SQL and MySQL?
- SQL: A standard language used for managing and manipulating databases. - MySQL: An open-source relational database management system (RDBMS) that uses SQL as its query language.
What is the purpose of the SET NAMES command in MySQL?
The SET NAMES command is used to specify the character set for the client connection, ensuring proper encoding for data being transmitted between the client and server. sql SET NAMES 'utf8';