0% found this document useful (0 votes)
5 views9 pages

Data Definition Language (DDL) Data Manipulation Language (DML)

The document provides an overview of SQL commands categorized into Data Definition Language (DDL) and Data Manipulation Language (DML), detailing essential commands like SELECT, INSERT, UPDATE, DELETE, CREATE, ALTER, DROP, and TRUNCATE. It also covers advanced SQL topics such as joins (INNER, LEFT, RIGHT, FULL, SELF), window functions, subqueries, and query optimization techniques. Additionally, it explains how to execute SQL commands on Windows using command-line clients and graphical user interfaces.

Uploaded by

faavend2815
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views9 pages

Data Definition Language (DDL) Data Manipulation Language (DML)

The document provides an overview of SQL commands categorized into Data Definition Language (DDL) and Data Manipulation Language (DML), detailing essential commands like SELECT, INSERT, UPDATE, DELETE, CREATE, ALTER, DROP, and TRUNCATE. It also covers advanced SQL topics such as joins (INNER, LEFT, RIGHT, FULL, SELF), window functions, subqueries, and query optimization techniques. Additionally, it explains how to execute SQL commands on Windows using command-line clients and graphical user interfaces.

Uploaded by

faavend2815
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 9

SQL

The most important SQL commands fall into two main categories: Data Definition
Language (DDL), for managing the database structure, and Data Manipulation
Language (DML), for handling the data itself.

Data Manipulation Language (DML)


These commands are used to work with the data within your tables. They are the most
frequently used commands for developers and data analysts.

SELECT

This is the most fundamental command, used to retrieve data from one or more tables. It's
the "read" operation of SQL.

 Syntax: SELECT column1, column2 FROM table_name WHERE condition;


 Example: SELECT first_name, last_name FROM employees WHERE
department = 'Sales';
 Purpose: To get specific columns (first_name, last_name) from a table
(employees) and filter the results based on a condition (department = 'Sales').

INSERT

This command is used to add new rows (records) to a table.

 Syntax: INSERT INTO table_name (column1, column2) VALUES (value1,


value2);
 Example: INSERT INTO employees (first_name, last_name) VALUES
('Jane', 'Doe');
 Purpose: To add a new employee named 'Jane Doe' to the employees table.

UPDATE

This command is used to modify existing data in a table.

 Syntax: UPDATE table_name SET column1 = value1 WHERE condition;


 Example: UPDATE employees SET department = 'Marketing' WHERE
first_name = 'Jane';
 Purpose: To change the department for all employees named 'Jane' to 'Marketing'.
Caution: Without a WHERE clause, this command will update all rows in the table.

DELETE
This command is used to remove one or more rows from a table.

 Syntax: DELETE FROM table_name WHERE condition;


 Example: DELETE FROM employees WHERE employee_id = 123;
 Purpose: To delete the record for the employee with an employee_id of 123.
Caution: Like UPDATE, omitting the WHERE clause will delete all data from the table.

Data Definition Language (DDL)


These commands are used to define, modify, or delete the structure of your database
objects, such as tables.

CREATE

This command is used to create a new database object, most commonly a table.

 Syntax: CREATE TABLE table_name (column1 datatype, column2


datatype);
 Example: CREATE TABLE products (product_id INT, product_name
VARCHAR(50), price DECIMAL);
 Purpose: To create a new table called products with three columns: product_id,
product_name, and price.

ALTER

This command is used to modify the structure of an existing table. This can include adding,
deleting, or modifying columns.

 Syntax: ALTER TABLE table_name ADD column_name datatype;


 Example: ALTER TABLE products ADD stock_quantity INT;
 Purpose: To add a new column named stock_quantity to the products table.

DROP

This is a powerful command that permanently deletes an entire database object, including
all its data, indexes, and other related elements.

 Syntax: DROP TABLE table_name;


 Example: DROP TABLE products;
 Purpose: To completely and irreversibly remove the products table and all the
data it contains.

TRUNCATE
This command is similar to DELETE without a WHERE clause, as it removes all rows from a
table. However, it is a DDL command, making it faster and non-transactional, meaning the
deletion cannot be rolled back.

 Syntax: TRUNCATE TABLE table_name;


 Example: TRUNCATE TABLE old_logs;
 Purpose: To quickly and efficiently delete all records from the old_logs table
while keeping the table structure intact.

There are no Windows-specific commands in SQL. SQL is a standard query language used
to communicate with databases, regardless of the operating system they run on. The
commands you use—like SELECT, INSERT, UPDATE, and DELETE—are part of the SQL
standard itself, not tied to Windows, macOS, or Linux.

Windows does have its own command-line interface, such as Command Prompt (cmd) or
PowerShell, which you use to execute programs. To run SQL commands on Windows, you
typically connect to a database server (like SQL Server, MySQL, or PostgreSQL) using a
client program.

Here is a common process and example for how you would use SQL on a Windows
machine:

1. Using a Command-Line Client


This method involves using a terminal program to connect to a database server. For this
example, let's use SQL Server, which is popular on Windows. You would use a client like
sqlcmd.

 Step 1: Open the Windows Command Prompt or PowerShell.


 Step 2: Connect to your SQL Server instance using sqlcmd.
 sqlcmd -S your_server_name -U your_username -P your_password
 Step 3: Once connected, you can type and execute your standard SQL commands.

Example SQL Commands in sqlcmd

The commands below are standard SQL, but you'd be typing them within the sqlcmd
client on your Windows machine.

 Create a database:

SQL

CREATE DATABASE MyNewDatabase;


GO
(The GO command is specific to SQL Server and tells the client to execute the
previous batch of commands.)

 Switch to the new database and create a table:

SQL

USE MyNewDatabase;
GO
CREATE TABLE Users (
UserID INT PRIMARY KEY,
UserName VARCHAR(50)
);
GO

 Insert data into the table:

SQL

INSERT INTO Users (UserID, UserName) VALUES (1, 'Alice');


INSERT INTO Users (UserID, UserName) VALUES (2, 'Bob');
GO

 Select and view the data:

SQL

SELECT * FROM Users;


GO

Output:

UserID UserName
----------- --------------------------------------------------
1 Alice
2 Bob

2. Using a Graphical User Interface (GUI)


Most developers use a GUI tool on Windows, such as SQL Server Management Studio
(SSMS) or Azure Data Studio. These applications provide a graphical interface to connect
to databases and run SQL commands.

The process is similar: you connect to a server, open a new query window, and type the
same standard SQL commands shown above. The tool then sends these commands to the
database server for execution.

You are given two sets.


Set A = {1,2,3,4,5,6}

Set B = {2,3,4,5,6,7,8}

How many elements are present in ?

Only enter the correct integer in the editor below. Do not include any extra spaces, tabs or
newlines.

give me an explanation and examples about advanced sql with the following topics: joins,
windows functions, subqueries and query optimization

SQL, or Structured Query Language, is a powerful tool for managing and manipulating
data in relational databases. While basic commands like SELECT and INSERT are essential,
advanced techniques such as Joins, Window Functions, Subqueries, and Query
Optimization are crucial for complex data analysis and efficient database management.

Joins

Joins are used to combine rows from two or more tables based on a related column between
them. This is fundamental for working with normalized databases where data is spread
across multiple tables to reduce redundancy.

 INNER JOIN:Returns rows when there is a match in both tables. It's the most
common type of join.

Example: Find all orders with customer names.

SQL

SELECT Orders.OrderID, Customers.CustomerName


FROM Orders
INNER JOIN Customers ON Orders.CustomerID = Customers.CustomerID;

 LEFT JOIN (or LEFT OUTER JOIN): Returns all rows from the left table, and the
matched rows from the right table. If there's no match, the columns from the right
table will be NULL.

Example: List all customers and any orders they have placed.

SQL

SELECT Customers.CustomerName, Orders.OrderID


FROM Customers
LEFT JOIN Orders ON Customers.CustomerID = Orders.CustomerID;

 RIGHT JOIN (or RIGHT OUTER JOIN): Returns all rows from the right table, and the
matched rows from the left table. It's the inverse of a LEFT JOIN.

Example: List all orders and the customers who placed them (useful if some orders
might have a missing CustomerID).

SQL

SELECT Customers.CustomerName, Orders.OrderID


FROM Customers
RIGHT JOIN Orders ON Customers.CustomerID = Orders.CustomerID;

 FULL JOIN (or FULL OUTER JOIN): Returns all rows from both tables, combining
rows where a match is found and including unmatched rows from either side with
NULL values.

Example: Show all customers and all orders, regardless of a match.

SQL

SELECT Customers.CustomerName, Orders.OrderID


FROM Customers
FULL JOIN Orders ON Customers.CustomerID = Orders.CustomerID;

 SELF JOIN: A table is joined to itself. This is useful for comparing rows within the
same table.

Example: Find all employees who report to the same manager.

SQL

SELECT A.EmployeeName, B.EmployeeName, A.ManagerID


FROM Employees A, Employees B
WHERE A.ManagerID = B.ManagerID AND A.EmployeeID <> B.EmployeeID;

Window Functions

Window functions perform a calculation across a set of table rows that are somehow related
to the current row. Unlike a GROUP BY clause, a window function does not collapse the
rows of the result set. It operates on a "window" of rows and returns an aggregated value
for each row.

 PARTITION BY: Divides the query result set into partitions (groups) and the window
function is applied to each partition separately.
 ROW_NUMBER(): Assigns a unique, sequential integer to each row within its partition.

Example: Rank employees by salary within each department.

SQL

SELECT
EmployeeName,
Department,
Salary,
ROW_NUMBER() OVER (PARTITION BY Department ORDER BY Salary
DESC) AS DeptRank
FROM Employees;

 RANK() and DENSE_RANK(): Assign a rank to each row within a partition. RANK()
leaves gaps in the ranking after ties, while DENSE_RANK() does not.

Example: Rank products within each category based on sales.

SQL

SELECT
ProductName,
Category,
Sales,
RANK() OVER (PARTITION BY Category ORDER BY Sales DESC) AS
SalesRank
FROM Products;

 SUM(), AVG(), COUNT(): These aggregate functions can be used as window


functions to calculate running totals or moving averages.

Example: Calculate a running total of sales.

SQL

SELECT
SaleDate,
SaleAmount,
SUM(SaleAmount) OVER (ORDER BY SaleDate) AS RunningTotal
FROM Sales;

Subqueries

A subquery is a query nested inside another SQL query. They are also known as inner
queries or nested queries. Subqueries can return a single value (scalar), a single row, a
single column, or a table.

 WHERE clause subquery: Used to filter data based on the result of another query.
Example: Find employees who have a salary greater than the average salary of all
employees.

SQL

SELECT EmployeeName, Salary


FROM Employees
WHERE Salary > (SELECT AVG(Salary) FROM Employees);

 FROM clause subquery (Derived Table): The subquery acts as a temporary table.
This is useful for breaking down complex queries.

Example: Get the average sales for each product category.

SQL

SELECT T1.Category, T1.AvgSales


FROM (
SELECT Category, AVG(Sales) AS AvgSales
FROM Products
GROUP BY Category
) AS T1;

 IN or EXISTS subquery: Used to check for the existence of rows returned by the
subquery. EXISTS is often more performant as it stops as soon as it finds a matching
row.

Example: Find customers who have placed at least one order.

SQL

SELECT CustomerName
FROM Customers
WHERE EXISTS (SELECT 1 FROM Orders WHERE Orders.CustomerID =
Customers.CustomerID);

Query Optimization

Query optimization is the process of writing SQL queries to ensure they execute as quickly
and efficiently as possible. A well-optimized query reduces server load and execution time,
which is critical for large databases.

 Use EXPLAIN or EXPLAIN ANALYZE: This command (syntax may vary by database)
shows the query execution plan, revealing how the database engine will retrieve the
data. This helps you identify bottlenecks.
 Create Indexes: Indexes are used to speed up data retrieval. They are like a book's
index, providing a quick way for the database to find specific rows. Create indexes
on columns used in WHERE, JOIN, and ORDER BY clauses.

Example: Create an index on the CustomerID column to speed up joins and


lookups.

SQL

CREATE INDEX idx_customer_id ON Customers (CustomerID);

 Avoid SELECT *: Instead of selecting all columns, only select the columns you
need. This reduces the amount of data transferred and processed.
 Use LIMIT for pagination: When retrieving a large number of rows, use LIMIT to
get a manageable subset.
 Avoid OR in WHERE clauses: The OR operator can be slow, as it can prevent the use
of indexes. Consider using a UNION or IN clause instead.

Example: Instead of SELECT * FROM Orders WHERE status = 'shipped' OR


status = 'delivered';, consider SELECT * FROM Orders WHERE status IN
('shipped', 'delivered');.

You might also like