Showing posts with label SQL References. Show all posts
Showing posts with label SQL References. Show all posts

Thursday, December 19, 2024

SQL WHERE Keyword

 The WHERE keyword in SQL is used to filter records based on specific conditions. It is typically used in a SELECT, UPDATE, DELETE, or INSERT statement to specify which rows should be affected by the query.

Syntax:

SELECT column1, column2, ...
FROM table_name
WHERE condition;

Example:

  1. Selecting specific rows:
SELECT * FROM Employees
WHERE Age > 30;

This will return all columns from the Employees table where the Age is greater than 30.

  1. Using multiple conditions with AND/OR:
SELECT * FROM Employees
WHERE Age > 30 AND Department = 'HR';

This will return all employees who are older than 30 and belong to the HR department.

  1. Using operators like =, >, <, BETWEEN, LIKE, etc.
SELECT * FROM Employees
WHERE Salary BETWEEN 40000 AND 60000;

This returns employees with a salary between 40,000 and 60,000.

  1. Using LIKE for pattern matching:
SELECT * FROM Employees
WHERE Name LIKE 'John%';

This returns employees whose name starts with "John."

  1. Using IN for matching a list of values:
SELECT * FROM Employees
WHERE Department IN ('HR', 'Finance', 'Sales');

This returns employees who work in the HR, Finance, or Sales departments.

  1. Using IS NULL to check for null values:
SELECT * FROM Employees
WHERE ManagerID IS NULL;

This returns employees who do not have a manager (i.e., their ManagerID is NULL).

The WHERE clause helps in filtering the data as per the specified condition.

SQL VIEW Keyword

 The VIEW keyword in SQL is used to create a virtual table based on the result of a query. A view does not store the data physically but rather presents data from one or more underlying tables or other views. This can simplify complex queries and enhance security by restricting access to certain data.

Syntax:

CREATE VIEW view_name AS
SELECT column1, column2, ...
FROM table_name
WHERE condition;
  • view_name: The name of the view you want to create.
  • SELECT statement: The query that defines the content of the view.

Example:

CREATE VIEW EmployeeView AS
SELECT EmployeeID, FirstName, LastName, Department
FROM Employees
WHERE Department = 'Sales';

This will create a view called EmployeeView, showing only the employees from the Sales department. You can now query EmployeeView just like a regular table:

SELECT * FROM EmployeeView;

Key Points:

  1. Virtual Table: A view behaves like a table but doesn't store data.
  2. Read-Only or Updatable: Views can be either read-only or updatable, depending on the query used to create them and the database system.
  3. Security: Views can be used to restrict access to sensitive data by showing only specific columns or rows from underlying tables.
  4. Performance: Although views can simplify complex queries, excessive use of views or complex nested views may affect performance.

Altering or Dropping Views:

  • Modify View:

    CREATE OR REPLACE VIEW view_name AS
    SELECT new_column1, new_column2
    FROM new_table;
    
  • Drop View:

    DROP VIEW view_name;
    

Views are a powerful tool in SQL to abstract complexity and improve data security and management.

SQL VALUES Keyword

 The VALUES keyword in SQL is used to insert data into a table. It is typically used with the INSERT INTO statement to specify the data that you want to insert into a table.

Syntax:

INSERT INTO table_name (column1, column2, column3, ...)
VALUES (value1, value2, value3, ...);

Example:

Suppose you have a table called employees with the columns id, name, and age.

INSERT INTO employees (id, name, age)
VALUES (1, 'John Doe', 30);

You can also insert multiple rows in one query:

INSERT INTO employees (id, name, age)
VALUES 
    (2, 'Jane Smith', 28),
    (3, 'Samuel Adams', 35);

Important Notes:

  1. The number of values in the VALUES clause must match the number of columns specified in the INSERT INTO clause.

  2. You can omit the column names if you're providing values for all columns in the same order as they are defined in the table:

    INSERT INTO employees 
    VALUES (4, 'Alice Brown', 25);
    
  3. Some SQL databases allow you to use the DEFAULT keyword to insert default values for certain columns:

    INSERT INTO employees (id, name)
    VALUES (5, 'Bob Green');
    

In this case, if the age column has a default value or is nullable, it will be automatically handled by the database.

SQL UPDATE Keyword

 The SQL UPDATE statement is used to modify the existing records in a table. You can update one or more columns in one or more rows based on a specified condition.

Basic Syntax:

UPDATE table_name
SET column1 = value1, column2 = value2, ...
WHERE condition;
  • table_name: The name of the table where the records need to be updated.
  • column1, column2, ...: The columns to update.
  • value1, value2, ...: The new values that will replace the existing values in those columns.
  • WHERE condition: This specifies which rows should be updated. If omitted, all rows in the table will be updated.

Example 1: Update a single column

UPDATE employees
SET salary = 60000
WHERE employee_id = 101;

This will update the salary column of the employee with employee_id 101 to 60000.

Example 2: Update multiple columns

UPDATE employees
SET salary = 70000, department = 'Marketing'
WHERE employee_id = 102;

This will update both the salary and department columns for the employee with employee_id 102.

Example 3: Update all rows (no WHERE clause)

UPDATE employees
SET department = 'HR';

This will set the department of all employees to 'HR'.

Important Notes:

  • Be careful when using the UPDATE statement without a WHERE clause as it will update all rows in the table.
  • To ensure you are updating the correct rows, always use the WHERE clause to specify the condition.

If you need help with any specific UPDATE query, feel free to ask!

SQL UNIQUE Keyword

 The UNIQUE keyword in SQL is used to ensure that all values in a column or a set of columns are distinct. When a column is defined with the UNIQUE constraint, it enforces that no two rows can have the same value for that column (or combination of columns).

Syntax:

CREATE TABLE table_name (
    column1 datatype UNIQUE,
    column2 datatype,
    ...
);

Or, for multiple columns:

CREATE TABLE table_name (
    column1 datatype,
    column2 datatype,
    UNIQUE (column1, column2)
);

Example 1: Single column with UNIQUE

CREATE TABLE Employees (
    ID INT PRIMARY KEY,
    Name VARCHAR(100),
    Email VARCHAR(100) UNIQUE
);

In this example, the Email column must have unique values for each row in the Employees table.

Example 2: Multiple columns with UNIQUE

CREATE TABLE Orders (
    OrderID INT,
    CustomerID INT,
    ProductID INT,
    UNIQUE (CustomerID, ProductID)
);

In this example, the combination of CustomerID and ProductID must be unique, but each column individually can have duplicate values.

Key Points:

  • A table can have multiple UNIQUE constraints, but each constraint applies to different columns or sets of columns.
  • UNIQUE constraints allow NULL values unless the column is defined as NOT NULL. However, the NULL values are treated as distinct, so you can have multiple rows with NULL values in a column with a UNIQUE constraint.

SQL UNION ALL Keyword

 The UNION ALL keyword in SQL is used to combine the results of two or more SELECT statements. Unlike UNION, which removes duplicate rows, UNION ALL includes all rows from each SELECT statement, even if they are duplicates.

Syntax:

SELECT column1, column2, ...
FROM table1
WHERE condition
UNION ALL
SELECT column1, column2, ...
FROM table2
WHERE condition;

Key Points:

  1. Combines Results: UNION ALL combines the result sets from two or more SELECT queries.
  2. Includes Duplicates: It includes all records, even if some of them are duplicated across the different SELECT queries.
  3. Column Matching: The number and data types of the columns in each SELECT statement must match.
  4. Performance: UNION ALL is generally faster than UNION because it does not have to remove duplicates.

Example:

SELECT name FROM employees
WHERE department = 'Sales'
UNION ALL
SELECT name FROM employees
WHERE department = 'Marketing';

This query combines the list of employees from the 'Sales' and 'Marketing' departments, including any duplicate names that might appear in both departments.

The UNION ALL keyword in SQL is used to combine the results of two or more SELECT queries. Unlike the UNION keyword, which eliminates duplicate rows from the result set, UNION ALL includes all rows, even duplicates.

Here is a basic example:

SELECT column1, column2 FROM table1
UNION ALL
SELECT column1, column2 FROM table2;

This will return all rows from both table1 and table2, including any duplicates that may exist between the two tables.

SQL UNION Keyword

 The UNION keyword in SQL is used to combine the results of two or more SELECT queries into a single result set. It eliminates duplicate records, returning only distinct rows from the combined queries.

Syntax:

SELECT column1, column2, ...
FROM table1
WHERE condition
UNION
SELECT column1, column2, ...
FROM table2
WHERE condition;

Important Points:

  1. Number of Columns: The SELECT statements combined with UNION must have the same number of columns, and the columns must have compatible data types.
  2. Order of Columns: The order of columns in each SELECT statement should be the same.
  3. Distinct Values: By default, UNION removes duplicate rows. If you want to include duplicates, use UNION ALL.
  4. Column Names: The column names in the result set will be taken from the first SELECT statement.

Example:

Suppose you have two tables, employees and contractors, with the same structure (columns for id, name, and role).

SELECT id, name, role
FROM employees
UNION
SELECT id, name, role
FROM contractors;

This query combines employees and contractors into a single result set without duplicates.

If you want to include duplicates, you can use UNION ALL:

SELECT id, name, role
FROM employees
UNION ALL
SELECT id, name, role
FROM contractors;

This query will include all rows from both employees and contractors, including any duplicates.

SQL DROP TABLE and TRUNCATE TABLE Keywords

 In SQL, the DROP TABLE and TRUNCATE TABLE commands are used to remove data or tables from a database, but they work differently. Here's an explanation of each:

1. DROP TABLE:

  • Purpose: The DROP TABLE command is used to completely remove a table from the database, including its structure, data, and associated indexes, constraints, and triggers.

  • Effect: When a table is dropped, it cannot be recovered (unless there is a backup).

  • Syntax:

    DROP TABLE table_name;
    
  • Example:

    DROP TABLE employees;
    
  • Key Points:

    • The table and all its data are permanently removed.
    • This operation cannot be rolled back unless you have a backup or use transactions.
    • Any relationships or foreign keys involving the table will be affected.
    • The table's definition is completely erased from the schema.

2. TRUNCATE TABLE:

  • Purpose: The TRUNCATE TABLE command is used to remove all rows from a table, but it keeps the table structure intact. This means the table still exists in the database, and you can continue using it for future operations.

  • Effect: This operation is faster than DELETE because it doesn't log individual row deletions.

  • Syntax:

    TRUNCATE TABLE table_name;
    
  • Example:

    TRUNCATE TABLE employees;
    
  • Key Points:

    • Only the data is removed, not the table structure.
    • It is usually faster than DELETE because it doesn't generate individual row delete logs.
    • You cannot use TRUNCATE with tables that are referenced by foreign keys.
    • This operation cannot be rolled back if done outside of a transaction (in most databases).
    • In some databases, TRUNCATE might reset auto-increment counters (e.g., the primary key sequence).

Key Differences:

Feature DROP TABLE TRUNCATE TABLE
Effect Removes both data and table structure. Removes only the data, not the structure.
Reversibility Cannot be undone without a backup. Cannot be undone if not in a transaction.
Performance Slower (due to removing the table structure). Faster (due to bulk removal of data).
Dependencies Affects foreign keys and relationships. Cannot be used if foreign keys are present.
Reset of Auto-increment No reset of auto-increment field. Often resets auto-increment counters.

In summary:

  • Use DROP TABLE when you want to completely remove a table.
  • Use TRUNCATE TABLE when you want to delete all rows but keep the table structure intact for future use.

SQL SELECT TOP, LIMIT and ROWNUM Keywords

 In SQL, the SELECT statement is used to query data from a database, and keywords like TOP, LIMIT, and ROWNUM are used to restrict the number of rows returned by the query. However, they are used differently depending on the database system you are working with.

1. SELECT TOP (SQL Server, MS Access)

The TOP keyword is used in SQL Server (and MS Access) to limit the number of rows returned by a query.

Syntax:

SELECT TOP (number) column1, column2, ...
FROM table_name
ORDER BY column_name;
  • number: The number of rows to return.
  • column_name: The column used to order the rows.

Example:

SELECT TOP 5 * 
FROM Employees
ORDER BY HireDate;

This query will return the first 5 rows ordered by the HireDate.

2. LIMIT (MySQL, PostgreSQL, SQLite)

The LIMIT keyword is used in databases like MySQL, PostgreSQL, and SQLite to limit the number of rows returned by a query.

Syntax:

SELECT column1, column2, ...
FROM table_name
ORDER BY column_name
LIMIT number;
  • number: The number of rows to return.

Example:

SELECT * 
FROM Employees
ORDER BY HireDate
LIMIT 5;

This query will return the first 5 rows ordered by HireDate.

3. ROWNUM (Oracle)

The ROWNUM pseudo-column is used in Oracle to return a unique number for each row in the result set. You can use ROWNUM to limit the number of rows returned.

Syntax:

SELECT column1, column2, ...
FROM (SELECT column1, column2, ...
      FROM table_name
      ORDER BY column_name)
WHERE ROWNUM <= number;
  • ROWNUM: Represents the row number for each row in the result set.
  • number: The number of rows to return.

Example:

SELECT * 
FROM Employees 
WHERE ROWNUM <= 5
ORDER BY HireDate;

This query returns the first 5 rows ordered by HireDate. However, note that the ORDER BY clause should be used inside a subquery when working with ROWNUM to get the correct order.

Comparison:

  • SQL Server: Use TOP.
  • MySQL, PostgreSQL, SQLite: Use LIMIT.
  • Oracle: Use ROWNUM with a subquery to limit the result set after applying sorting.

SQL TABLE Keyword

 In SQL, the TABLE keyword is commonly used in various contexts, typically in relation to defining, querying, and modifying tables. Here are some key ways the TABLE keyword is used:

1. CREATE TABLE:

Used to create a new table in a database.

CREATE TABLE table_name (
    column1 datatype constraints,
    column2 datatype constraints,
    column3 datatype constraints
);

2. DROP TABLE:

Used to delete an existing table and all of its data.

DROP TABLE table_name;

3. ALTER TABLE:

Used to modify an existing table, such as adding, deleting, or modifying columns.

ALTER TABLE table_name
ADD column_name datatype;
ALTER TABLE table_name
DROP COLUMN column_name;
ALTER TABLE table_name
MODIFY COLUMN column_name datatype;

4. SELECT FROM:

Used to query data from a table.

SELECT * FROM table_name;

5. DESCRIBE (or EXPLAIN) TABLE:

This command shows the structure of a table, including columns, data types, and constraints.

DESCRIBE table_name;

6. TEMPORARY TABLE:

In some databases, you can create temporary tables that only exist during the session.

CREATE TEMPORARY TABLE temp_table_name (
    column1 datatype,
    column2 datatype
);

7. INSERT INTO TABLE:

Used to insert data into a table.

INSERT INTO table_name (column1, column2) VALUES (value1, value2);

8. SELECT INTO:

Creates a new table and inserts data into it from another table.

SELECT * INTO new_table FROM existing_table;

9. REFERENCES (Foreign Key):

Used in the context of defining foreign keys that reference another table.

CREATE TABLE child_table (
    id INT,
    parent_id INT,
    FOREIGN KEY (parent_id) REFERENCES parent_table(id)
);

In summary, the TABLE keyword is mainly associated with creating, altering, and querying tables in a database.

SQL SET Keyword

 The SET keyword in SQL is used to assign values to variables or change the configuration of the database session. It has several uses, depending on the context in which it is applied. Here are the main uses of the SET keyword in SQL:

1. Assigning Values to Variables

You can use SET to assign values to user-defined variables in SQL.

Example:

DECLARE @TotalSales INT;
SET @TotalSales = 1000;
SELECT @TotalSales;

2. Modifying Session Settings

The SET keyword is often used to configure session-level settings like language, date format, and transaction isolation level.

Example:

SET DATEFORMAT dmy;
SET TRANSACTION ISOLATION LEVEL SERIALIZABLE;

3. Updating Data in a Table

The SET keyword is used in UPDATE statements to modify column values in a table.

Example:

UPDATE Employees
SET Salary = 50000
WHERE EmployeeID = 123;

4. Setting Database Options

Some databases allow you to configure session options or properties using the SET keyword.

Example in MySQL (enabling autocommit):

SET autocommit = 1;

5. Changing System Variables (MySQL)

You can modify system variables (like connection settings) in MySQL using the SET keyword.

Example:

SET GLOBAL max_connections = 200;

6. Assigning Multiple Variables

In SQL Server, you can assign multiple variables in a single SET statement.

Example:

DECLARE @FirstName VARCHAR(50), @LastName VARCHAR(50);
SET @FirstName = 'John', @LastName = 'Doe';

The specific behavior of SET can vary slightly between different database systems (e.g., MySQL, SQL Server, PostgreSQL), but these are the common uses of the SET keyword.

SQL SELECT TOP, LIMIT and ROWNUM Keywords

 In SQL, the keywords SELECT TOP, LIMIT, and ROWNUM are used to limit the number of rows returned in a query. However, their usage depends on the SQL database management system (DBMS) you're working with. Here's an overview of each one:

1. SELECT TOP (SQL Server, MS Access)

The SELECT TOP keyword is used to specify the number of rows to return from the query result. It is commonly used in Microsoft SQL Server and MS Access.

Syntax:

SELECT TOP (n) column1, column2, ...
FROM table_name
ORDER BY column1;
  • n specifies the number of rows to return.
  • ORDER BY is optional but often used to determine the order of rows.

Example:

SELECT TOP 5 Name, Age
FROM Employees
ORDER BY Age DESC;

This query retrieves the top 5 employees with the highest age.

2. LIMIT (MySQL, PostgreSQL, SQLite, MariaDB)

The LIMIT keyword is used in MySQL, PostgreSQL, and other relational databases to limit the number of rows returned by a query.

Syntax:

SELECT column1, column2, ...
FROM table_name
ORDER BY column1
LIMIT n;
  • n specifies the number of rows to return.

Example:

SELECT Name, Age
FROM Employees
ORDER BY Age DESC
LIMIT 5;

This query retrieves the top 5 employees with the highest age in MySQL or PostgreSQL.

3. ROWNUM (Oracle)

In Oracle, the ROWNUM keyword is used to limit the number of rows returned. ROWNUM is a pseudo-column that assigns a unique number to each row returned by a query.

Syntax:

SELECT column1, column2, ...
FROM table_name
WHERE ROWNUM <= n;
  • ROWNUM is assigned incrementally starting at 1 for the first row.
  • n specifies the maximum number of rows to return.

Example:

SELECT Name, Age
FROM Employees
WHERE ROWNUM <= 5
ORDER BY Age DESC;

This query retrieves the top 5 employees based on age, but note that ROWNUM is applied before sorting. For correctly ordered results, you need to wrap the query in a subquery:

SELECT Name, Age
FROM (
    SELECT Name, Age
    FROM Employees
    ORDER BY Age DESC
)
WHERE ROWNUM <= 5;

Summary:

  • SQL Server/MS Access: Use SELECT TOP (n).
  • MySQL/PostgreSQL/SQLite/MariaDB: Use LIMIT n.
  • Oracle: Use ROWNUM with a subquery for ordered results.

Each of these keywords helps to control the amount of data retrieved in a query, making it useful for performance optimization or when working with large datasets.

SQL SELECT INTO Keyword

 The SELECT INTO statement in SQL is used to select data from one table and insert it into a new table. It allows you to create a new table and populate it with the result set of a query.

Syntax:

SELECT column1, column2, ...
INTO new_table
FROM existing_table
WHERE condition;

Example:

  1. Create a new table and insert data from an existing table:
SELECT first_name, last_name
INTO new_employees
FROM employees
WHERE department = 'Sales';

This creates a new table new_employees and copies the first_name and last_name columns from the employees table where the department is 'Sales'.

  1. Create a new table with all rows from the existing table:
SELECT *
INTO new_table
FROM old_table;

This copies all rows and columns from old_table to new_table.

Notes:

  • The SELECT INTO statement creates a new table with the structure defined by the columns selected in the query.
  • The new table is populated with the data from the selected query result.
  • In some databases (like SQL Server), SELECT INTO may also create a new table in the specified schema.

If you need to select data into an already existing table, you should use the INSERT INTO statement instead.

SQL SELECT DISTINCT Keyword

 The SELECT DISTINCT keyword in SQL is used to retrieve unique (non-duplicate) values from a column or a combination of columns. When you use DISTINCT, it ensures that the result set will only contain distinct (unique) records, eliminating duplicates.

Syntax:

SELECT DISTINCT column1, column2, ...
FROM table_name;

Example:

Consider a table named Employees with the following data:

ID Name Department
1 John HR
2 Jane IT
3 John IT
4 Alice HR
5 Jane HR

Query:

SELECT DISTINCT Name, Department
FROM Employees;

Result:

Name Department
John HR
Jane IT
John IT
Alice HR
Jane HR

Here, the DISTINCT keyword ensures that you get unique combinations of Name and Department. Notice that even though there are duplicate names (John and Jane), the query will return distinct rows based on both Name and Department.

Notes:

  • If you use DISTINCT with multiple columns, it considers the combination of all specified columns.
  • If only one column is specified, it will return unique values for that column, eliminating any duplicate entries.

SQL SELECT Keyword

 The SQL SELECT keyword is used to retrieve data from a database. It is one of the most fundamental and widely used commands in SQL (Structured Query Language). The SELECT statement allows you to query and extract specific information from a table or multiple tables, based on certain conditions.

Basic Syntax:

SELECT column1, column2, ...
FROM table_name;
  • column1, column2, ...: The columns you want to retrieve from the table. You can list specific columns, or use * to select all columns.
  • table_name: The name of the table from which you want to retrieve data.

Examples:

  1. Select all columns from a table:

    SELECT * FROM employees;
    

    This retrieves all columns and rows from the employees table.

  2. Select specific columns from a table:

    SELECT first_name, last_name FROM employees;
    

    This retrieves the first_name and last_name columns from the employees table.

  3. Select distinct (unique) values:

    SELECT DISTINCT department FROM employees;
    

    This retrieves a list of unique departments from the employees table, removing duplicates.

  4. Select with a condition (using WHERE clause):

    SELECT first_name, last_name FROM employees WHERE department = 'HR';
    

    This retrieves the first_name and last_name of employees who work in the 'HR' department.

  5. Order the results (using ORDER BY clause):

    SELECT first_name, last_name FROM employees ORDER BY last_name;
    

    This retrieves employee names and orders the results alphabetically by last_name.

  6. Limit the number of results (using LIMIT or FETCH clause):

    SELECT first_name, last_name FROM employees LIMIT 5;
    

    This retrieves only the first 5 rows from the employees table.

Combining with Other Clauses:

You can also combine the SELECT statement with other SQL clauses like:

  • WHERE: Filters rows based on a condition.
  • ORDER BY: Sorts the results.
  • GROUP BY: Groups rows based on column values, often used with aggregate functions.
  • JOIN: Combines rows from two or more tables based on a related column.

Example with multiple clauses:

SELECT first_name, last_name, department
FROM employees
WHERE department = 'IT'
ORDER BY last_name ASC;

This retrieves the first_name, last_name, and department of employees in the 'IT' department, ordered by last_name in ascending order.

In short, the SELECT keyword is essential for querying and extracting data from a database in SQL.

SQL SELECT TOP, LIMIT and ROWNUM Keywords

 In SQL, TOP, LIMIT, and ROWNUM are used to restrict the number of rows returned by a query. However, they are used differently across different SQL database systems. Here's a breakdown of how they work:

1. TOP (SQL Server, MS Access)

In SQL Server and MS Access, the TOP keyword is used to limit the number of rows returned in a result set.

Syntax:

SELECT TOP n column1, column2, ...
FROM table_name
WHERE condition;
  • n: The number of rows to return.
  • This can be a constant or a percentage.

Example:

SELECT TOP 5 * FROM Employees;

This query will return the first 5 rows from the Employees table.

2. LIMIT (MySQL, PostgreSQL, SQLite)

In MySQL, PostgreSQL, and SQLite, LIMIT is used to restrict the number of rows returned.

Syntax:

SELECT column1, column2, ...
FROM table_name
WHERE condition
LIMIT n;
  • n: The number of rows to return.
  • In PostgreSQL, you can also use LIMIT with an OFFSET to control the starting row.

Example:

SELECT * FROM Employees
LIMIT 5;

This query will return the first 5 rows from the Employees table.

3. ROWNUM (Oracle)

In Oracle, ROWNUM is a pseudo-column that is assigned to rows in the order in which they are retrieved from the database. It can be used to limit the number of rows returned by a query.

Syntax:

SELECT column1, column2, ...
FROM (SELECT column1, column2, ...
      FROM table_name
      WHERE condition)
WHERE ROWNUM <= n;
  • ROWNUM is assigned before ORDER BY is applied, so it's important to be cautious when using it with an ORDER BY clause.

Example:

SELECT * FROM Employees
WHERE ROWNUM <= 5;

This query will return the first 5 rows from the Employees table based on the order in which they are retrieved by the query. To apply ROWNUM after sorting, use a subquery:

SELECT * FROM (
    SELECT * FROM Employees ORDER BY hire_date DESC
) WHERE ROWNUM <= 5;

This will return the first 5 rows after sorting the Employees table by the hire_date in descending order.

Summary:

  • SQL Server uses TOP to limit rows.
  • MySQL, PostgreSQL, and SQLite use LIMIT.
  • Oracle uses ROWNUM, often requiring a subquery when combined with ORDER BY.

Different SQL databases have different methods of achieving the same goal, and it's important to use the correct one depending on the database you're working with.

SQL RIGHT JOIN Keyword

 The SQL RIGHT JOIN (also known as RIGHT OUTER JOIN) is used to combine rows from two tables based on a related column between them, but it returns all rows from the right table (the second table) and the matching rows from the left table (the first table). If there is no match, the result is NULL for the columns from the left table.

Syntax:

SELECT column1, column2, ...
FROM table1
RIGHT JOIN table2
ON table1.column = table2.column;

Explanation:

  • RIGHT JOIN: Ensures that all rows from the second (right) table are returned.
  • table1.column and table2.column: Specifies the columns used to match rows from both tables.
  • If a row from table2 has no corresponding match in table1, the result will contain NULL for the columns of table1.

Example:

Consider two tables:

employees:

employee_id name department_id
1 John 10
2 Alice 20
3 Bob 30

departments:

department_id department_name
10 HR
20 IT
30 Marketing
40 Sales

A RIGHT JOIN query would look like this:

SELECT employees.name, departments.department_name
FROM employees
RIGHT JOIN departments
ON employees.department_id = departments.department_id;

Result:

name department_name
John HR
Alice IT
Bob Marketing
NULL Sales

Key Points:

  1. All rows from the departments table are returned, even if there's no matching row in employees.
  2. The name column is NULL for the Sales department since there is no corresponding employee in that department.
  3. If a department had no employees, the result would still include the department with NULL in the employee-related columns.

Use Cases:

  • When you want to include all records from the right table and only the matching records from the left table.
  • For example, finding all departments and the employees working in them, even if some departments don't have employees.

SQL CREATE PROCEDURE Keyword

 The CREATE PROCEDURE keyword in SQL is used to define a stored procedure, which is a set of SQL statements that can be executed on demand. A stored procedure allows you to encapsulate logic and perform operations like data retrieval, updates, or other complex SQL queries in a reusable and efficient way.

Basic Syntax

CREATE PROCEDURE procedure_name
    [parameter1 datatype [IN | OUT | INOUT], 
     parameter2 datatype [IN | OUT | INOUT], 
     ...]
AS
BEGIN
    -- SQL statements to be executed
END;

Explanation:

  • procedure_name: The name of the stored procedure.
  • parameter1, parameter2, ...: These are optional input (IN), output (OUT), or input/output (INOUT) parameters that the procedure accepts. The parameter type can be any valid SQL datatype like INT, VARCHAR, DATE, etc.
  • BEGIN ... END: The block where the SQL statements are written.

Example of a simple stored procedure:

CREATE PROCEDURE GetEmployeeDetails (IN employee_id INT)
BEGIN
    SELECT * FROM Employees
    WHERE EmployeeID = employee_id;
END;
  • This procedure, named GetEmployeeDetails, accepts one input parameter employee_id and retrieves the details of the employee with that ID from the Employees table.

Example of a stored procedure with multiple parameters:

CREATE PROCEDURE AddEmployee (IN first_name VARCHAR(100), IN last_name VARCHAR(100), IN hire_date DATE)
BEGIN
    INSERT INTO Employees (FirstName, LastName, HireDate)
    VALUES (first_name, last_name, hire_date);
END;
  • This procedure inserts a new employee into the Employees table with the FirstName, LastName, and HireDate values provided as input parameters.

Calling a Stored Procedure:

To execute a stored procedure after it's created, you use the CALL statement:

CALL GetEmployeeDetails(123);
  • This will call the GetEmployeeDetails procedure and pass 123 as the employee_id parameter.

Notes:

  • The IN parameter is the default, meaning it is used to pass values into the procedure.
  • The OUT parameter is used to pass values from the procedure back to the calling environment.
  • The INOUT parameter is used to both pass a value into the procedure and receive a value back from the procedure.
  • The stored procedure can contain any valid SQL operations, including SELECT, INSERT, UPDATE, and DELETE.

Different database systems (e.g., MySQL, SQL Server, PostgreSQL, etc.) may have variations in syntax, but the general concept is the same across most platforms.

SQL PRIMARY KEY Keyword

 In SQL, the PRIMARY KEY keyword is used to define a column (or a combination of columns) in a table that uniquely identifies each row in that table. The PRIMARY KEY ensures that the values in these columns are unique and not NULL, enforcing entity integrity in the database.

Key points about PRIMARY KEY:

  1. Uniqueness: Each value in the PRIMARY KEY must be unique. This means no two rows can have the same value in the primary key column(s).
  2. Non-NULL: A PRIMARY KEY column cannot contain NULL values. Every row must have a valid, non-NULL value in the primary key.
  3. Single or Composite Key: A primary key can be a single column or a combination of columns. When multiple columns are used together, it's called a composite primary key.
  4. Automatically Indexed: Most database systems automatically create a unique index for the primary key, which speeds up query performance.

Syntax

Single Column Primary Key:

CREATE TABLE table_name (
    column1 datatype PRIMARY KEY,
    column2 datatype,
    column3 datatype
);

Composite Primary Key (Multiple Columns):

CREATE TABLE table_name (
    column1 datatype,
    column2 datatype,
    column3 datatype,
    PRIMARY KEY (column1, column2)
);

Example:

CREATE TABLE Employees (
    EmployeeID INT PRIMARY KEY,
    FirstName VARCHAR(100),
    LastName VARCHAR(100),
    BirthDate DATE
);

In this example:

  • The EmployeeID column is the primary key.
  • Every employee must have a unique EmployeeID, and this column cannot contain NULL values.

Altering an Existing Table to Add a Primary Key:

ALTER TABLE Employees
ADD PRIMARY KEY (EmployeeID);

If the table already has data, the values in the EmployeeID column must be unique and non-NULL before the primary key constraint can be added.

Primary Key Constraints:

  • If the PRIMARY KEY is defined on multiple columns (composite), the combination of values in those columns must be unique.
  • It automatically creates a unique constraint, so there is no need to separately define a UNIQUE constraint on a primary key column.

Primary Key vs Unique Key:

  • Primary Key: Cannot have NULL values and guarantees uniqueness.
  • Unique Key: Can allow NULL values (depending on the database), but still enforces uniqueness across the column(s).

Conclusion:

The PRIMARY KEY is a fundamental concept in relational databases, ensuring data integrity and uniqueness. It is commonly used in defining the identity of records and optimizing data retrieval.

SQL FULL OUTER JOIN Keyword

 In SQL, the FULL OUTER JOIN keyword is used to combine the results of both LEFT OUTER JOIN and RIGHT OUTER JOIN. It returns all rows from both tables, matching rows where possible. If there is no match, the result will contain NULL values for the columns of the table that does not have a matching row.

Syntax:

SELECT column1, column2, ...
FROM table1
FULL OUTER JOIN table2
ON table1.common_column = table2.common_column;

Explanation:

  • table1 and table2 are the two tables to be joined.
  • common_column is the column that both tables share (the one used for comparison).
  • FULL OUTER JOIN ensures that all records from both tables are included in the result set. If a record from table1 does not have a matching record in table2, NULL values will be placed for the columns of table2, and vice versa.

Example:

Suppose you have two tables, employees and departments:

Table 1: employees

emp_id emp_name dept_id
1 Alice 101
2 Bob 102
3 Charlie 103
4 David NULL

Table 2: departments

dept_id dept_name
101 HR
102 IT
104 Finance

Query:

SELECT employees.emp_id, employees.emp_name, departments.dept_name
FROM employees
FULL OUTER JOIN departments
ON employees.dept_id = departments.dept_id;

Result:

emp_id emp_name dept_name
1 Alice HR
2 Bob IT
3 Charlie NULL
4 David NULL
NULL NULL Finance

Key Points:

  • Rows from employees with no matching rows in departments will show NULL in the dept_name column.
  • Rows from departments with no matching rows in employees will show NULL in the emp_id and emp_name columns.
  • The result contains all rows from both tables, even when there is no match.

When to Use:

  • When you want to ensure that no data is excluded from either table, even if there is no corresponding match.