SQL Flashcards
What are aggregate functions in SQL?
Aggregate functions perform calculations on a set of values and return a single value. Common aggregate functions include:
- COUNT(): Returns the number of rows.
- SUM(): Returns the total sum of values.
- AVG(): Returns the average of values.
- MIN(): Returns the smallest value.
- MAX(): Returns the largest value.
What is a subquery?
Asubqueryis a query nested within another query. It is often used in theWHERE clauseto filter data based on the results of another query, making it easier to handle complex conditions.
What is the difference between the WHERE and HAVING clauses?
- WHERE:Filters rows before any grouping takes place.
- HAVING:Filters grouped data after the GROUP BY clause has been applied.In short, WHERE applies to individual rows, while HAVING applies to groups.
What are indexes, and why are they used?
Indexesaredatabase objectsthat improve query performance by allowingfaster retrieval of rows. They function like a book’s index, making it quicker to find specific data without scanning the entire table. However, indexes requireadditional storageand can slightly slow downdata modificationoperations.
What is the difference between DELETE and TRUNCATE commands?
- DELETE:Removes rows one at a time and records each deletion in the transaction log, allowing rollback. It can have a WHERE clause.
- TRUNCATE:Removes all rows at once without logging individual row deletions. It cannot have a WHERE clause and is faster than DELETE for large data sets.
What is the purpose of the SQL ORDER BY clause?
TheORDER BYclause sorts the result set of a query in eitherascending(default) ordescending order, based on one or more columns. This helps present the data in a more meaningful or readable sequence.
What are the differences between SQL and NoSQL databases?
-
SQL Databases:
- Use structured tables with rows and columns.
- Rely on a fixed schema.
- OfferACIDproperties.
-
NoSQL Databases:
- Use flexible, schema-less structures (e.g., key-value pairs, document stores).
- Are designed for horizontal scaling.
- Often focus on performance and scalability over strict consistency.
What are the types of constraints in SQL?
Common constraints include:
- NOT NULL:Ensures a column cannot have NULL values.
- UNIQUE:Ensures all values in a column are distinct.
- PRIMARY KEY:Uniquely identifies each row in a table.
- FOREIGN KEY:Ensures referential integrity by linking to a primary key in another table.
- CHECK:Ensures that all values in a column satisfy a specific condition.
- DEFAULT:Sets a default value for a column when no value is specified.
What is a cursor in SQL?
Acursoris a database object used toretrieve,manipulate, and traverse through rows in a result set one row at a time. Cursors are helpful when performing operations that must be processed sequentially rather than in a set-based manner.
What is a trigger in SQL?
Atriggeris a set of SQL statements that automatically execute in response to certain events on a table, such asINSERT,UPDATE, orDELETE. Triggers help maintaindata consistency, enforce business rules, and implement complex integrity constraints.
What are NULL values in SQL?
NULLrepresents a missing or unknown value. It is different from zero or an empty string. NULL values indicate that the data is not available or applicable
What is a stored procedure?
Astored procedureis a precompiled set of SQL statements stored in thedatabase. It can take input parameters, perform logic and queries, and return output values or result sets. Stored procedures improveperformanceandmaintainabilityby centralizing business logic.
What are the main types of SQL commands?
SQL commands are broadly classified into:
- DDL (Data Definition Language):CREATE, ALTER, DROP, TRUNCATE.
- DML (Data Manipulation Language):SELECT, INSERT, UPDATE, DELETE.
- DCL (Data Control Language):GRANT, REVOKE.
What is the difference between DDL and DML commands?
1. DDL (Data Definition Language):
These commands are used todefineandmodify the structure of databaseobjects such astables,indexes, andviews. For example, theCREATE
commandcreates a new table, theALTER
commandmodifies an existing table, and theDROP
commandremoves a table entirely.DDLcommands primarily focus on the schema or structure of the database.
Example:
CREATE TABLE Employees ( ID INT PRIMARY KEY, Name VARCHAR(50) );
2. DML (Data Manipulation Language):
These commands deal with theactual data storedwithin database objects. For instance, theINSERT
commandadds rows of data to a table, theUPDATE
command modifies existing data, and theDELETE
command removes rows from a table. In short,DMLcommands allow you to query and manipulate the data itself rather than the structure.
Example:
INSERT INTO Employees (ID, Name) VALUES (1, 'Alice');
What is the purpose of the ALTER command in SQL?
TheALTER
command is used tomodify the structureof an existing database object. This command is essential for adapting ourdatabase schemaas requirements evolve.
- Add or drop a column in a table.
- Change a column’s data type.
- Add or remove constraints.
- Rename columns or tables.
- Adjust indexing or storage settings.
What is a composite primary key?
A composite primary keyis a primary key made up of two or more columns. Together, these columns must form a unique combination for each row in the table. It’s used when a single column isn’t sufficient to uniquely identify a record.
Example:
Consider an Orders table whereOrderID
andProductID
together uniquely identify each record because multiple orders might include the same product, but not within the same order.
CREATE TABLE OrderDetails ( OrderID INT, ProductID INT, Quantity INT, PRIMARY KEY (OrderID, ProductID) );
How is data integrity maintained in SQL databases?
Data integrity refers to theaccuracy,consistency, andreliabilityof the data stored in the database. SQL databases maintain data integrity through several mechanisms:
-
Constraints:Ensuring that certain conditions are always met. For example,
NOT NULL
ensures a column cannot have missing values,FOREIGN KEY
ensures a valid relationship between tables, andUNIQUE
ensures no duplicate values. - Transactions:Ensuring that a series of operations either all succeed or all fail, preserving data consistency.
- Triggers:Automatically enforcing rules or validations before or after changes to data.
- Normalization:Organizing data into multiple related tables to minimize redundancy and prevent anomalies.These measures collectively ensure that the data remains reliable and meaningful over time.
What are the advantages of using stored procedures?
- Improved Performance:Stored procedures are precompiled and cached in the database, making their execution faster than sending multiple individual queries.
- Reduced Network Traffic:By executing complex logic on the server, fewer round trips between the application and database are needed.
- Enhanced Security:Stored procedures can restrict direct access to underlying tables, allowing users to execute only authorized operations.
- Reusability and Maintenance:Once a procedure is written, it can be reused across multiple applications. If business logic changes, you only need to update the stored procedure, not every application that uses it.
What is a UNION operation, and how is it used?
TheUNION
operator combines the result sets of two or moreSELECT
queriesinto a single result set, removing duplicate rows. This is useful when we need aconsolidated viewof data from multiple tables or queries that have similar structure.
Example:
SELECT Name FROM Customers UNION SELECT Name FROM Employees;
What is the difference between UNION and UNION ALL?
- UNION:Removes duplicate rows from the result set, ensuring only unique rows are returned.
- UNION ALL:Includes all rows from each query, including duplicates.
- Performance-wise,
UNION ALL
is faster because it doesn’t require an additional step to remove duplicates.
Example:
SELECT Name FROM Customers UNION ALL SELECT Name FROM Employees;
How does the CASE statement work in SQL?
TheCASE
statement is SQL’s way of implementingconditional logicin queries. It evaluates conditions and returns a value based on the first condition that evaluates to true. If no condition is met, it can return a default value using theELSE
clause.
Example:
SELECT ID, CASE WHEN Salary > 100000 THEN 'High' WHEN Salary BETWEEN 50000 AND 100000 THEN 'Medium' ELSE 'Low' END AS SalaryLevel FROM Employees;
What are scalar functions in SQL?
Scalar functionsoperate on individual values and return a single value as a result. They are often used for formatting or converting data. Common examples include:
- LEN():Returns the length of a string.
- ROUND():Rounds a numeric value.
- CONVERT():Converts a value from one data type to another.
Example:
SELECT LEN('Example') AS StringLength;
What is the purpose of the COALESCE function?
TheCOALESCE
functionreturns the first non-NULL value from a list of expressions. It’s commonly used to provide default values or handle missing data gracefully.
Example:
SELECT COALESCE(NULL, NULL, 'Default Value') AS Result;
What are the differences between SQL’s COUNT() and SUM() functions?
1. COUNT():Counts the number of rows or non-NULL values in a column.
Example:
SELECT COUNT(*) FROM Orders;
2. SUM():Adds up all numeric values in a column.
Example:
SELECT SUM(TotalAmount) FROM Orders;