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

SQL

SQL is a standard programming language for managing relational databases, allowing users to create, read, update, and delete data. It includes various commands for data manipulation, definition, and control, as well as concepts like normalization and NULL values. The document also covers SQL syntax, functions, and practical examples for querying and managing data effectively.

Uploaded by

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

SQL

SQL is a standard programming language for managing relational databases, allowing users to create, read, update, and delete data. It includes various commands for data manipulation, definition, and control, as well as concepts like normalization and NULL values. The document also covers SQL syntax, functions, and practical examples for querying and managing data effectively.

Uploaded by

kateri.louka
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 9

SQL (Structured Query Language)

SQL Exercises : SQL Practice with Solution for Beginners and Experienced | GeeksforGeeks
SQL Cheat Sheet ( Basic to Advanced) | GeeksforGeeks
SQL Interview Questions | GeeksforGeeks
SQL Query Interview Questions | GeeksforGeeks

SQL is a standard programming language used to communicate


with relational databases. It allows users to create, read, update, and
delete data, and provides commands to define database schema and
manage database security

Normalization is the process of organizing data in a database to reduce


redundancy and improve data integrity. This involves dividing large
tables into smaller, related tables and defining relationships between them
to ensure consistency and avoid anomalies.

NULL represents 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.

 SQL is used as a Data Definition Language(DDL) in which we can


independently create a database, define the structure, use it, and discard
it when its work is done.
 SQL is used as a Data Manipulation Language(DML) in which we can
enter data, modify data, and extract data.
 SQL is used as a Data Control Language(DCL) it specifies how we can
protect our database against corruption and misuse.

 RANK(): Assigns a rank to each row, with gaps if there are ties.
 DENSE_RANK(): Assigns consecutive ranks without any gaps.
 ROW_NUMBER(): Assigns a unique number to each row regardless of ties.
 RANK(): Assigns the same number to tied rows and leaves gaps for
subsequent ranks.

 composite primary key is a primary key made up of two or more


columns.

 SQL keywords are NOT case sensitive: select is the same as SELECT
 Semicolon is the standard way to separate each SQL statement in
database systems that allow more than one SQL statement to be
executed in the same call to the server.
 Single line comments start with --
 Multi-line comments start with /* and end with */
 PRIMARY KEY - A combination of a NOT NULL and UNIQUE. Uniquely
identifies each row in a table
 FOREIGN KEY - Prevents actions that would destroy links between tables

SQL can:
 Execute queries, retrieve data
 Insert, update, delete records from a database
 Create new databases
 Create new tables in a database
 Create stored procedures in a database
 Create views in a database
 Set permissions on tables, procedures, and views

RDBMS (Relational Database Management System) database program (i.e.


MS Access, SQL Server, MySQL)
 RDBMS is the basis for SQL
 Data in RDBMS is stored in database objects called tables. A table is a
collection of related data entries and it consists of columns and rows.
o Every table is broken up into smaller entities called fields.
o A field is a column in a table that is designed to maintain specific
information about every record/row in the table.

 SELECT - extracts data from a database


 UPDATE - updates data in a database
 DELETE - deletes data from a database
 INSERT INTO - inserts new data into a database
 CREATE DATABASE - creates a new database
 ALTER DATABASE - modifies a database
 CREATE TABLE - creates a new table
 ALTER TABLE - modifies a table
 DROP TABLE - deletes a table
 CREATE INDEX - creates an index (search key)
 DROP INDEX - deletes an index

SELECT TOP 50 PERCENT * ,


CASE
WHEN condition1 THEN result1
WHEN condition2 THEN result2
ELSE result
END AS column3
INTO temp
FROM Customers
INNER JOIN Customers ON Orders.CustomerID=Customers.CustomerID; or
JOIN
ORDER BY Price DESC;
WHERE NOT Country = 'Spain' AND CustomerName LIKE 'G%' , <> not equal,
BETWEEN 10 AND 60, IN ('Paris', 'London'), IS NULL
GROUP BY column_name(s)
HAVING condition
LIMIT 50
ORDER BY

LIKE 'L_nd__' _ represents one, and only one, character.


LIKE 'b%s' starts with "b" and ends with "s"
LIKE '[bsp]% starting with either "b", "s", or "p"

SELECT DISTINCT Country FROM Customers;


SELECT COUNT(DISTINCT Country) FROM Customers;

SELECT Count(*) AS DistinctCountries


FROM (SELECT DISTINCT Country FROM Customers);

INSERT INTO Customers (CustomerName, PostalCode, Country)


VALUES ('Cardinal', '4006', 'Norway'), ('Greasy Burger', '4306', 'Norway')

UPDATE Customers
SET ContactName = 'Alfred Schmidt', City= 'Frankfurt'
WHERE CustomerID = 1;

All record will be updated


UPDATE Customers
SET ContactName='Juan';

DELETE FROM table_name WHERE condition;

DELETE FROM table_name; delete all records

DROP TABLE Customers; delete the table completely


SELECT MIN(Price) AS SmallestPrice
FROM Products;

SELECT MIN(Price) AS SmallestPrice, CategoryID


FROM Products
GROUP BY CategoryID;

 MIN(), MAX(), COUNT(), SUM(), AVG()


 Aggregate functions ignore null values (except for COUNT())

 SELECT COUNT(*) NULL values will be counted


FROM Products;

 SELECT * FROM Products


WHERE price > (SELECT AVG(price) FROM Products);

SELECT CONCAT(Address,', ',PostalCode,', ',City,', ',Country) AS Address

SQL Self Join Example


matches customers that are from the same city:

SELECT A.CustomerName AS CustomerName1,


B.CustomerName AS CustomerName2, A.City
FROM Customers A, Customers B
WHERE A.CustomerID <> B.CustomerID
AND A.City = B.City
ORDER BY A.City;

SELECT column_name(s) FROM table1


UNION
SELECT column_name(s) FROM table2;

The UNION operator selects only distinct values by default. To allow duplicate
values, use UNION ALL:

SELECT column_name(s) FROM table1


UNION ALL
SELECT column_name(s) FROM table2;
SELECT Employees.LastName, COUNT(Orders.OrderID) AS NumberOfOrders
FROM (Orders
INNER JOIN Employees ON Orders.EmployeeID = Employees.EmployeeID)
GROUP BY LastName
HAVING COUNT(Orders.OrderID) > 10;

The EXISTS operator is used to test for the existence of any record in a
subquery.
The EXISTS operator returns TRUE if the subquery returns one or more
records.

SELECT column_name(s)
FROM table_name
WHERE EXISTS
(SELECT column_name FROM table_name WHERE condition);

SELECT ProductName
FROM Products
WHERE ProductID = ANY ALL
(SELECT ProductID
FROM OrderDetails
WHERE Quantity > 1000);

SELECT *
INTO temp IN 'Backup.mdb' IN clause copy table into a new table in another
database
FROM Customers;

Copy "table1" into "table2" (the columns that are not filled with data, will
contain NULL):
INSERT INTO table2 (CustomerName, City, Country)
SELECT SupplierName, City, Country FROM table1;

SELECT ProductName, IFNULL(UnitsOnOrder, 0) return an alternative value


if an expression is NULL ISNULL()
SELECT ProductName, COALESCE (UnitsOnOrder, 0)
SELECT COALESCE(NULL, 1, 2, 'W3Schools.com') Return the first non-null
value
creates a stored procedure named "SelectAllCustomers"
CREATE PROCEDURE SelectAllCustomers @City nvarchar(30)
AS
SELECT * FROM Customers WHERE City = @City
GO;
Execute the stored procedure above as follows:
EXEC SelectAllCustomers @City = 'London';

CREATE DATABASE databasename;


DROP DATABASE databasename;
CREATE TABLE Persons (
PersonID int,
LastName varchar(255),
City varchar(255)
);
CREATE TABLE new_table_name AS
SELECT column1, column2,...
FROM existing_table_name
WHERE ....;
DROP TABLE table_name;
TRUNCATE TABLE table_name; delete the data inside a table, but not the
table itself.

View is a virtual table, shows up-to-date data! The database engine recreates
the view, every time a user queries it.
CREATE VIEW view_name AS
SELECT column1, column2, ...
FROM table_name
WHERE condition;
DROP VIEW view_name;

A CTE is a temporary result set defined within a query. It improves query


readability and can be referenced multiple times.
Example:
WITH TopSalaries AS (
SELECT Name, Salary
FROM Employees
WHERE Salary > 50000)
SELECT * FROM TopSalaries
Window functions perform calculations across a set of rows that are
related to the current row. Unlike aggregate functions, they don’t collapse
the result set.
Example: Calculating a running total
SELECT Name, Salary, SUM(Salary) OVER (Partition By id ORDER BY Salary)
AS RunningTotal
FROM Employees;
How can you handle duplicates in a query without using DISTINCT?
1. GROUP BY: Aggregate rows to eliminate duplicates
2. ROW_NUMBER(): Assign a unique number to each row and filter by that
=1

Write a query to find the second-highest salary of an employee in a


table.
SELECT MAX(Salary) AS SecondHighestSalary
FROM Employee
WHERE Salary < (SELECT MAX(Salary) FROM Employee);

Write a query to retrieve employees who earn more than the


average salary.
SELECT *
FROM Employee
WHERE Salary > (SELECT AVG(Salary) FROM Employee);

Write a query to fetch the duplicate values from a column in a table.


SELECT ColumnName, COUNT(*)
FROM TableName
GROUP BY ColumnName
HAVING COUNT(*) > 1;

Write a query to find the employees who joined in the last 30 days.
SELECT *
FROM Employee
WHERE JoiningDate > DATE_SUB(CURDATE(), INTERVAL 30 DAY);

Write a query to fetch top 3 earning employees.


SELECT *
FROM Employee
ORDER BY Salary DESC
LIMIT 3;

Write a query to fetch common records from two tables.


SELECT *
FROM TableA
INNER JOIN TableB ON TableA.ID = TableB.ID;

Write a query to fetch employees whose names start and end with
‘A’.
SELECT *
FROM Employee
WHERE Name LIKE 'A%' AND Name LIKE '%A';

Write a query to display all departments along with the number of


employees in each.
SELECT DepartmentID, COUNT(*) AS EmployeeCount
FROM Employee
GROUP BY DepartmentID;

Write a query to find employees who do not have managers.


SELECT *
FROM Employee
WHERE ManagerID IS NULL;

Write a query to list employees in departments that have fewer than


5 employees.
SELECT *
FROM Employee
WHERE DepartmentID IN (
SELECT DepartmentID
FROM Employee
GROUP BY DepartmentID
HAVING COUNT(*) < 5);

Write a query to find departments with the highest average salary.


SELECT DepartmentID
FROM Employee
GROUP BY DepartmentID
ORDER BY AVG(Salary) DESC
LIMIT 1;

Write a query to find employees hired in the same month of any


year.
SELECT *
FROM Employee
WHERE MONTH(JoiningDate) = MONTH(CURDATE());

You might also like