Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
2 views

SQL Constraints and Schema

Uploaded by

arulnithish91
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views

SQL Constraints and Schema

Uploaded by

arulnithish91
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 24

SQL Constraints and Schema

#### Basics:
1. What are constraints in SQL (e.g., unique key, primary key, foreign key)?
2. What is a schema?

explain in short 2 lines in simple language. give one example of each

1. Constraints in SQL

Constraints ensure rules for data in a database table. Examples:

Unique Key: Ensures all values in a column are different.


Example: `CREATE TABLE Users (Email VARCHAR(50) UNIQUE);`
Primary Key: Uniquely identifies each row; combines UNIQUE and NOT NULL.
Example: `CREATE TABLE Users (UserID INT PRIMARY KEY);`
Foreign Key: Links a column to a primary key in another table.
Example: `CREATE TABLE Orders (UserID INT, FOREIGN KEY (UserID) REFERENCES Users(UserID));`

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

The REVOKE command removes previously granted permissions from a user.


Example: `REVOKE SELECT ON Employees FROM User1;` (Stops User1 from viewing the Employees table).

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

What are transactions in SQL? give in 2 line with example

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

This ensures money is transferred only if both updates succeed.

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

CREATE TABLE Students (StudentID INT PRIMARY KEY, Name VARCHAR(50));

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

CREATE TABLE Users (Email VARCHAR(100) UNIQUE, Name VARCHAR(50));

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

CREATE TABLE Employees (EmpID INT, EmpEmail VARCHAR(100), UNIQUE (EmpEmail));

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

-- EmpEmail is an alternate key if EmpID is the primary key


CREATE TABLE Employees (EmpID INT PRIMARY KEY, EmpEmail VARCHAR(100) UNIQUE);

7. Super Key
A set of one or more columns that can uniquely identify rows (may include extra attributes).
Example:

sql

-- (EmpID, EmpEmail) is a super key if EmpID is already unique


CREATE TABLE Employees (EmpID INT PRIMARY KEY, EmpEmail VARCHAR(100));

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

Sure! Here's the breakdown of SQL commands as you described:

1. DDL (Data Definition Language):


Commands used to define and modify the structure of database objects like tables and schemas.

Examples: `create`, `alter`, `rename`, `truncate`, `drop`

2. DML (Data Manipulation Language):


Commands used to manipulate and manage data within the database.

Examples: `select`, `insert`, `update`, `delete`

3. DCL (Data Control Language):


Commands used to control access and permissions for users on the database.

Examples: `grant`, `revoke`

4. DQL (Data Query Language):


Commands used specifically for querying and retrieving data from the database.

Examples: `select`

5. TCL (Transaction Control Language):


Commands used to manage transactions, ensuring data integrity and consistency.

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

SELECT * FROM Employees WHERE Department = 'Sales';

2. GROUP BY Clause
Groups rows that have the same values into summary rows.
Example:

sql

SELECT Department, COUNT(*) FROM Employees GROUP BY Department;

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

SELECT Name, Salary FROM Employees ORDER BY Salary DESC;

5. JOIN Clause
Combines rows from two or more tables based on a related column.
Example:

sql

SELECT Employees.Name, Departments.DepartmentName FROM Employees JOIN Departments ON Employees.DepartmentID = Departments.DepartmentID;

6. ON Clause
Specifies the condition for the `JOIN` operation.
Example:

sql

SELECT Orders.OrderID, Customers.CustomerName FROM Orders JOIN Customers ON Orders.CustomerID = Customers.CustomerID;

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

SELECT * FROM Products LIMIT 10;

This returns only the first 10 rows from the `Products` table.

difference between where and having clause in one line with example difference

Difference between WHERE and HAVING Clause

WHERE filters rows before grouping, while HAVING filters grouped results.

Example:

sql

-- WHERE (filters before grouping)


SELECT Department, AVG(Salary) FROM Employees WHERE Department = 'Sales';

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;

between groupby and orderby clause in one line with example

Difference between GROUP BY and ORDER BY

GROUP BY groups rows that have the same values, while ORDER BY sorts the result set.

Example:

sql

-- GROUP BY (groups rows by a column)


SELECT Department, COUNT(*) FROM Employees GROUP BY Department;

-- ORDER BY (sorts the result set)


SELECT Name, Salary FROM Employees ORDER BY Salary DESC;

Aggregate Function explain in one line with example with types

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 and Clauses:


3. What is an inner join?
4. What is an outer join?
5. Explain joins and their types.
6.equi-join, theta-join, cross-join, and self-join.

considering above questions explain joins topic in short in simple language

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

Equi-join: Matches rows based on equality (e.g., `=`).


Example: `SELECT * FROM Orders JOIN Customers ON Orders.CustomerID = Customers.CustomerID;`
Theta-join: Matches rows based on a condition using comparison operators like `<`, `>`, `<=`, `>=`, etc. Example: `SELECT * FROM Orders JOIN Customers
ON Orders.CustomerID > Customers.CustomerID;`
Cross-join: Produces the Cartesian product of the tables, combining all rows from one table with all rows from another. Example: `SELECT * FROM Orders
CROSS JOIN Customers;`
Self-join: A join where a table is joined with itself based on some condition. Example: `SELECT e1.Name, e2.Name FROM Employees e1 JOIN Employees e2 ON
e1.ManagerID = e2.EmployeeID;`

14. What is a subquery, and when is it used?

explain subquery in short with example

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.

21. What are set operators (e.g., UNION, INTERSECT)?

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.

Types of Set Operators:

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

SELECT Name FROM Employees WHERE Department = 'Sales'


UNION
SELECT Name FROM Employees WHERE Department = 'Marketing';

2. INTERSECT: Returns rows that are common between the two SELECT queries (matches in both).
Example:

sql

SELECT Name FROM Employees WHERE Department = 'Sales'


INTERSECT
SELECT Name FROM Employees WHERE Department = 'Marketing';

3. EXCEPT (or MINUS in some SQL dialects): Returns rows from the first query that do not exist in the second query.
Example:

sql

SELECT Name FROM Employees WHERE Department = 'Sales'


EXCEPT
SELECT Name FROM Employees WHERE Department = 'Marketing';

4. UNION ALL: Combines the results of two SELECT queries and includes all rows, even duplicates.
Example:

sql

SELECT Name FROM Employees WHERE Department = 'Sales'


UNION ALL
SELECT Name FROM Employees WHERE Department = 'Marketing';

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.

Using the View:

Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 16/24
sql

SELECT * FROM StudentGrades;

This would return only the student names and grades for those in the Mathematics course.

22. What is the purpose of indexes in SQL?


define index in short and give ans

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

CREATE INDEX idx_employee_salary ON Employees(Salary);

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

CREATE TRIGGER after_employee_insert


AFTER INSERT ON Employees
FOR EACH ROW
BEGIN
INSERT INTO AuditLog (Action, TableName, RowData) VALUES ('INSERT', 'Employees', NEW);
END;

This trigger automatically logs any new employee insertions into the `AuditLog` table.

15. Explain aliases in SQL.

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.

explain above in short

15. Aliases in SQL

An alias is a temporary name used to rename a table, column, or function in a SQL query for clarity or convenience.
Example:

sql

SELECT Name AS EmployeeName FROM Employees;

24. Sequence in SQL

A sequence is a special database object used to automatically generate unique numbers for primary keys or other purposes.
Example:

sql

CREATE SEQUENCE seq_emp_id START WITH 1 INCREMENT BY 1;

12. Auto-incrementing in 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

CREATE TABLE Employees (


EmpID INT PRIMARY KEY AUTO_INCREMENT,
Name VARCHAR(100)
);

20. Scalar Functions

Scalar functions perform operations on single values and return a single value.
Example:

sql

SELECT UPPER(Name) FROM Employees;

18. Isolation Levels in Transactions

Isolation levels define the degree to which transactions can see each other’s data. Common isolation levels are:

READ UNCOMMITTED: Allows dirty reads.


READ COMMITTED: Prevents dirty reads.
REPEATABLE READ: Ensures no dirty reads or non-repeatable reads.
SERIALIZABLE: The highest level, ensuring full isolation from other transactions.

What is data modeling and an ERD?


Explain multiplicity in relationships
What is normalization?
What are ACID properties in a transaction?

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.

ERD (Entity-Relationship Diagram)

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 Properties in Transactions

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

CREATE TABLE Customers (


CustomerID INT PRIMARY KEY,
Name VARCHAR(100)
);

CREATE TABLE Orders (


OrderID INT PRIMARY KEY,
CustomerID INT,
Amount DECIMAL(10, 2),
FOREIGN KEY (CustomerID) REFERENCES Customers(CustomerID)
);

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

CREATE TABLE Customers (


CustomerID INT PRIMARY KEY,
Name VARCHAR(100)
);

CREATE TABLE Orders (


OrderID INT PRIMARY KEY,
CustomerID INT,
Amount DECIMAL(10, 2),
FOREIGN KEY (CustomerID) REFERENCES Customers(CustomerID) ON DELETE CASCADE
);

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

You might also like