SQL Constraints and Schema
SQL Constraints and Schema
#### Basics:
1. What are constraints in SQL (e.g., unique key, primary key, foreign key)?
2. What is a schema?
1. Constraints in SQL
2. Schema in SQL
A schema is a structure that organizes database objects like tables, views, and procedures.
Example: `CREATE SCHEMA Sales AUTHORIZATION Manager;`
grant and revoke explain in short 2 lines in simple language. give one example of each
Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 1/24
Grant
The GRANT command is used to give specific permissions to a user for database actions like SELECT, INSERT, or DELETE.
Example: `GRANT SELECT ON Employees TO User1;` (Allows User1 to view the Employees table).
Revoke
start transaction, commit, rollback explain in short 2 lines in simple language. give one example of each
Start Transaction
Marks the beginning of a group of SQL operations that will be treated as a single unit.
Example: `START TRANSACTION;`
Commit
Saves all changes made during the transaction permanently to the database.
Example: `COMMIT;`
Rollback
Reverts all changes made during the transaction if something goes wrong.
Example: `ROLLBACK;`
Full Example:
Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 2/24
sql
START TRANSACTION;
UPDATE Accounts SET Balance = Balance - 100 WHERE AccountID = 1;
UPDATE Accounts SET Balance = Balance + 100 WHERE AccountID = 2;
COMMIT; -- Saves the changes
-- Or ROLLBACK; -- Cancels the changes if needed
Transactions in SQL
A transaction is a sequence of operations performed as a single unit of work. It ensures data integrity, meaning all operations succeed or none are applied.
Example:
sql
START TRANSACTION;
UPDATE Accounts SET Balance = Balance - 100 WHERE AccountID = 1;
UPDATE Accounts SET Balance = Balance + 100 WHERE AccountID = 2;
COMMIT; -- Completes the transaction
define each key in sql in one line and give example of each
Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 3/24
Keys in SQL
1. Primary Key
A unique identifier for each row in a table; cannot have NULL values.
Example:
sql
2. Foreign Key
Links a column in one table to the primary key in another, ensuring referential integrity.
Example:
sql
CREATE TABLE Orders (OrderID INT, CustomerID INT, FOREIGN KEY (CustomerID) REFERENCES Customers(CustomerID));
3. Unique Key
Ensures all values in a column are unique but allows a single NULL.
Example:
sql
4. Candidate Key
Any column(s) that can uniquely identify rows in a table; one is chosen as the primary key.
Example:
Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 4/24
sql
5. Composite Key
A key made of two or more columns to uniquely identify rows.
Example:
sql
CREATE TABLE Enrollments (StudentID INT, CourseID INT, PRIMARY KEY (StudentID, CourseID));
6. Alternate Key
A candidate key not chosen as the primary key.
Example:
sql
7. Super Key
A set of one or more columns that can uniquely identify rows (may include extra attributes).
Example:
sql
Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 5/24
Types of SQL Commands:
1) DDL (Data Definition Language): create, alter, rename, truncate & drop.
2) DML (Data Manipulation Language): select, insert, update & delete.
3) DCL (Data Control Language): grant & revoke permission to users.
4) DQL (Data Query Language): select.
5) TCL (Transaction Control Language): start transaction, commit, rollback etc.
give as it is
Examples: `select`
Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 6/24
Examples: `start transaction`, `commit`, `rollback`
What is clause in sql. give clauses with example each in one line
Clause in SQL
A clause is a part of an SQL statement that specifies conditions or actions, used to filter, modify, or control the query.
1. WHERE Clause
Filters rows based on a condition.
Example:
sql
2. GROUP BY Clause
Groups rows that have the same values into summary rows.
Example:
sql
3. HAVING Clause
Filters grouped records based on a condition.
Example:
Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 7/24
sql
SELECT Department, AVG(Salary) FROM Employees GROUP BY Department HAVING AVG(Salary) > 50000;
4. ORDER BY Clause
Sorts the result set by a specified column.
Example:
sql
5. JOIN Clause
Combines rows from two or more tables based on a related column.
Example:
sql
6. ON Clause
Specifies the condition for the `JOIN` operation.
Example:
sql
Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 8/24
Limit clause in one line with example
LIMIT Clause
The `LIMIT` clause is used to restrict the number of rows returned by a query.
Example:
sql
This returns only the first 10 rows from the `Products` table.
difference between where and having clause in one line with example difference
WHERE filters rows before grouping, while HAVING filters grouped results.
Example:
sql
Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 9/24
-- HAVING (filters after grouping)
SELECT Department, AVG(Salary) FROM Employees GROUP BY Department HAVING AVG(Salary) > 50000;
GROUP BY groups rows that have the same values, while ORDER BY sorts the result set.
Example:
sql
Aggregate Function
Aggregate functions perform calculations on a set of values and return a single value.
Types & Examples:
Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 10/24
COUNT: Counts the number of rows.
Example: `SELECT COUNT(*) FROM Employees;`
SUM: Sums the values of a column.
Example: `SELECT SUM(Salary) FROM Employees;`
AVG: Calculates the average value of a column.
Example: `SELECT AVG(Salary) FROM Employees;`
MAX: Returns the highest value in a column.
Example: `SELECT MAX(Salary) FROM Employees;`
MIN: Returns the lowest value in a column.
Example: `SELECT MIN(Salary) FROM Employees;`
Joins in SQL
Joins are used to combine rows from two or more tables based on a related column.
3. Inner Join
The INNER JOIN returns rows that have matching values in both tables.
Example:
Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 11/24
sql
SELECT Orders.OrderID, Customers.CustomerName FROM Orders INNER JOIN Customers ON Orders.CustomerID = Customers.CustomerID;
4. Outer Join
The OUTER JOIN returns all rows from one table and the matching rows from another table, plus any unmatched rows from one table.
LEFT OUTER JOIN: Returns all rows from the left table and matched rows from the right table.
Example:
sql
SELECT Orders.OrderID, Customers.CustomerName FROM Orders LEFT OUTER JOIN Customers ON Orders.CustomerID = Customers.CustomerID;
RIGHT OUTER JOIN: Returns all rows from the right table and matched rows from the left table. Example:
sql
SELECT Orders.OrderID, Customers.CustomerName FROM Orders RIGHT OUTER JOIN Customers ON Orders.CustomerID = Customers.CustomerID;
FULL OUTER JOIN: Returns all rows when there is a match in either left or right table. Example:
sql
SELECT Orders.OrderID, Customers.CustomerName FROM Orders FULL OUTER JOIN Customers ON Orders.CustomerID = Customers.CustomerID;
5. Types of Joins
Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 12/24
Joins are used to link tables based on related columns. The main types include:
INNER JOIN: Only returns rows with matching values in both tables.
OUTER JOIN: Includes unmatched rows from one or both tables (LEFT, RIGHT, FULL).
CROSS JOIN: Returns the Cartesian product of both tables (all combinations of rows).
6. Types of Joins
Subquery
A subquery is a query nested inside another SQL query. It is used to perform calculations, retrieve data, or filter results from the main query.
When is it used?
To filter data: Subqueries are commonly used to filter rows based on conditions.
To perform calculations: Subqueries can help perform calculations within queries, such as finding maximum, minimum, or averages.
To retrieve related data: Used to retrieve data that depends on other data in the table.
Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 13/24
Example of Subquery
sql
-- Example: Find employees whose salary is higher than the average salary in the department.
SELECT Name, Salary FROM Employees WHERE Salary > (SELECT AVG(Salary) FROM Employees WHERE Department = 'Sales');
In this example:
The subquery `(SELECT AVG(Salary) FROM Employees WHERE Department = 'Sales')` calculates the average salary in the 'Sales' department.
The main query retrieves employees with a salary greater than that average.
explain in short
Set Operators
Set operators combine the results of two or more SELECT queries into a single result set. They operate on sets of rows, not individual rows, and remove
duplicate values by default.
1. UNION: Combines the result sets of two SELECT queries and removes duplicate rows.
Example:
Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 14/24
sql
2. INTERSECT: Returns rows that are common between the two SELECT queries (matches in both).
Example:
sql
3. EXCEPT (or MINUS in some SQL dialects): Returns rows from the first query that do not exist in the second query.
Example:
sql
4. UNION ALL: Combines the results of two SELECT queries and includes all rows, even duplicates.
Example:
sql
Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 15/24
explain views in simple words in short give simple example student
Views in SQL
A view is a virtual table created by querying data from one or more tables. It doesn’t store the data itself, but it displays the results of a query.
Purpose of Views:
Simplifies complex queries: A view can hide complexity by creating a simplified interface to your data.
Restricts access: Views can limit access to specific rows or columns of data.
Reusable queries: Once defined, views can be used in multiple queries without rewriting the same SQL.
Example of a View:
sql
-- Create a view to show only the names and grades of students in a specific course.
CREATE VIEW StudentGrades AS
SELECT StudentName, Grade
FROM Students
WHERE Course = 'Mathematics';
Explanation:
The view `StudentGrades` shows the `StudentName` and `Grade` from the `Students` table, filtered for those enrolled in the 'Mathematics' course.
When querying `StudentGrades`, it acts like a table, but it’s based on the original data in the `Students` table.
Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 16/24
sql
This would return only the student names and grades for those in the Mathematics course.
Indexes in SQL
An index is a database structure that improves the speed of data retrieval operations on a table, by creating a fast lookup path to access data.
Purpose of Indexes:
Speed up query performance: Indexes allow faster retrieval of rows, especially for large tables.
Optimize sorting: Helps in quickly sorting data based on certain columns.
Reduce I/O operations: Reduces the time it takes to search for rows by minimizing disk I/O operations.
Example:
sql
This creates an index on the `Salary` column in the `Employees` table, speeding up queries that filter or sort by salary.
Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 17/24
25. What is a trigger in SQL?
define triggers in short and give ans with example
Triggers in SQL
A trigger is a special kind of stored procedure that automatically executes in response to specific events (INSERT, UPDATE, DELETE) on a table.
Purpose of Triggers:
Enforce business rules: Triggers help maintain data integrity by automatically performing actions when certain changes occur.
Automate tasks: Triggers can automate tasks like updating other tables, sending notifications, or logging changes.
Example of a Trigger:
sql
This trigger automatically logs any new employee insertions into the `AuditLog` table.
Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 18/24
24. What is a sequence in SQL?
12. What is auto-incrementing in SQL?
20. What are scalar functions?18. Explain isolation levels in transactions.
An alias is a temporary name used to rename a table, column, or function in a SQL query for clarity or convenience.
Example:
sql
A sequence is a special database object used to automatically generate unique numbers for primary keys or other purposes.
Example:
sql
Auto-incrementing automatically generates unique values for a column, usually used for primary keys.
Example:
Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 19/24
sql
Scalar functions perform operations on single values and return a single value.
Example:
sql
Isolation levels define the degree to which transactions can see each other’s data. Common isolation levels are:
Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 20/24
explain above
Data Modeling
Data modeling is the process of defining how data is structured, stored, and managed in a database. It involves creating models (like ER diagrams) to
represent relationships between different data entities.
An ERD is a visual representation of entities (objects) and the relationships between them in a database. It helps to model the logical structure of data.
Multiplicity in Relationships
Multiplicity defines how many instances of one entity can be associated with instances of another entity. Common types are:
One-to-One: A single entity in one table is related to only one entity in another.
Example: `Customer` → `Address`
One-to-Many: One entity in one table is related to many entities in another.
Example: `Order` → `OrderDetails`
Many-to-Many: Many entities in one table are related to many entities in another.
Example: `Student` → `Course`
Normalization
Normalization is the process of organizing data to minimize redundancy and dependency by dividing large tables into smaller, related tables.
The most common stages of normalization are:
1NF (First Normal Form): Ensures all columns have atomic values (no repeating groups).
2NF (Second Normal Form): Removes partial dependency by ensuring all non-key attributes are fully dependent on the primary key.
3NF (Third Normal Form): Removes transitive dependency by ensuring no non-key attribute is dependent on another non-key attribute.
Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 21/24
BCNF (Boyce-Codd Normal Form): Further removes redundancy by making sure every determinant is a candidate key.
ACID refers to the properties that ensure database transactions are reliable and consistent:
Atomicity: Ensures all operations in a transaction are completed successfully, or the entire transaction is rolled back.
Consistency: Ensures a transaction takes the database from one valid state to another.
Isolation: Ensures transactions do not interfere with each other. Different isolation levels include `READ UNCOMMITTED`, `READ COMMITTED`, `REPEATABLE
READ`, and `SERIALIZABLE`.
Durability: Ensures once a transaction is committed, it will remain so, even in the event of a system crash.
database consistency
cascade
explain with example
Database Consistency
Database consistency refers to the condition where all data in a database adheres to defined rules and constraints, ensuring the database remains in a valid
state after every operation. It guarantees that data integrity rules (like primary keys, foreign keys, and unique constraints) are always maintained.
Cascade
Cascade is a feature in database relationships that automatically propagates changes from one table to other related tables. It is often used with foreign
keys to ensure data consistency.
Example:
Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 22/24
1. Database Consistency Example: Suppose we have a `Customers` table with a primary key `CustomerID`, and a `Orders` table that references
`CustomerID` as a foreign key.
sql
Consistency Rule: If you delete a customer, the database should automatically ensure that any related orders are also deleted to maintain data
integrity.
2. Cascade Example: You can set up a `CASCADE` action when defining the foreign key relationship:
sql
Explanation:
Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 23/24
When you delete a `Customer`, the `CASCADE` option ensures that all orders related to that customer in the `Orders` table are automatically deleted.
Example:
sql
DELETE FROM Customers WHERE CustomerID = 1; -- This will delete all orders for CustomerID = 1 in the Orders table.
This ensures that database consistency is maintained across tables, avoiding orphaned records.
Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 24/24