0% found this document useful (0 votes)
23 views

AIS SQL Final

SQL is a programming language used to manage and query relational database management systems. It can retrieve, modify, define and manipulate data within databases. Common DBMS include MySQL, Oracle Database, Microsoft SQL Server, and PostgreSQL. A RDBMS like these uses SQL and stores data in tables with rows and columns to define relationships. Key aspects of SQL include joins, data types, constraints, and clauses that are executed in a specific order like FROM, WHERE, and SELECT.

Uploaded by

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

AIS SQL Final

SQL is a programming language used to manage and query relational database management systems. It can retrieve, modify, define and manipulate data within databases. Common DBMS include MySQL, Oracle Database, Microsoft SQL Server, and PostgreSQL. A RDBMS like these uses SQL and stores data in tables with rows and columns to define relationships. Key aspects of SQL include joins, data types, constraints, and clauses that are executed in a specific order like FROM, WHERE, and SELECT.

Uploaded by

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

Accurate Info Solution

SQL Theory

For Online Editor Use SQLfiddle

1. What can SQL do?

SQL (Structured Query Language) is a programming language


specifically designed for managing,
querying, and manipulating data within relational database
management systems (RDBMS).

SQL can:

Retrieve Data: Select and retrieve specific information from


databases.

Modify Data: Insert, update, or delete records within tables.

Define and Manipulate Structure: Create, alter, and drop tables and
views.

Control Access: Set permissions, grant or revoke access to databases


and tables.

Maintain Data Integrity: Implement constraints, such as primary


keys, foreign keys, and unique constraints.

2. What is a Database?

A database is an organized collection of structured data stored


electronically in a computer system.
It's designed to manage, store, and retrieve data efficiently.
Databases typically consist of tables that hold related information.
They offer functionalities to ensure data integrity, security, and
ease of access.

3. Understanding File System:


a. It is a software that manages the storage medium within the
computer.

b. Redundant Can be present in file system.

c. Does not provide backup or recovery.

d. Less secured.

e. Only one use can access data at a time.

EX: NTFS,FAT

4. What is DBMS?

DBMS (Database Management System) is software that allows users to


interact with databases.
It facilitates the creation, maintenance, and usage of databases by
providing an interface
for users and applications to interact with the stored data.
DBMS handles tasks such as data retrieval,manipulation, security,
and data integrity enforcement.

a. It is a software that manages the Database.

b. Redundant Can't be present in Database.

c. provide backup or recovery.

d. More cost and more secured.

e. Multiple user can access data at a time.

EX: MySQL.Oracal

5. Most commonly used DBMS?

Some of the most commonly used DBMS are:

MySQL: An open-source relational database often used in web


applications.

Oracle Database: Known for its scalability and performance, widely


used in enterprise environments.

Microsoft SQL Server: A robust RDBMS developed by Microsoft,


suitable for various applications.

PostgreSQL: An open-source RDBMS known for its extensibility and


compliance with SQL standards.

MongoDB: A popular NoSQL database, offering flexibility with schema


and designed for handling unstructured data.

6. What is RDBMS?

RDBMS (Relational Database Management System) is a type of DBMS that


stores data in a tabular form,
where data is organized in tables with rows and columns.
It enforces relationships between tables through primary and foreign
keys, ensuring data integrity.
SQL is commonly used to manage RDBMS databases.

7. Difference between DBMS and RDBMS:

+-------------------------------------
+-------------------------------------+
| DBMS | RDBMS
|
+-------------------------------------
+-------------------------------------+
| - DBMS stores data as file. | - RDBMS stores data in
tabular |
| - Data elements need to access | form.
|
| individually. | - Multiple data elements
can be |
| - No relationship between data. | accessed at the same
time. |
| - Normalization is not present. | - Data is stored in the
form of |
| | tables which are related
to |
| | each other.
|
| - DBMS does not support | - Normalization is present.
|
| distributed database. | - RDBMS supports
distributed |
| | database.
|
| - It stores data in either a | - It uses a tabular
structure |
| navigational or hierarchical | where the headers are the
|
| form. | column names, and the
rows |
| | contain corresponding
values. |
| - It deals with small quantity | - It deals with large
amount |
| of data. | of data.
|
| - Data redundancy is common in | - Keys and indexes do not
allow |
| this model. | data redundancy.
|
| - It is used for small | - It is used to handle
large |
| organization and deals with | amount of data.
|
| small data. | - All 12 Codd rules are
satisfied. |
| - Not all Codd rules are | - More security measures
provided. |
| satisfied. | - It supports multiple
users. |
| - Security is less. | - Data fetching is fast
because |
| - It supports single user. | of the relational
approach. |
| - Data fetching is slower for | - There exists multiple
levels |
| the large amount of data. | of data security in an
RDBMS. |
| - The data in a DBMS is subject |
|
| to low security levels with |
|
| regards to data manipulation. |
|
| - Low software and hardware |
|
| necessities. |
|
| - Examples: XML, Window Registry, | - Higher software and
hardware |
| Forxpro, dbaseIIIplus etc. | necessities.
|
| | - Examples: MySQL,
PostgreSQL, |
| | SQL Server, Oracle,
Microsoft |
| | Access etc.
|
+-------------------------------------
+-------------------------------------+

Operations in SQL:

1. Arithmetic Operations:
Addition (+), Subtraction (-), Multiplication (*), Division (/)
Modulo (%), Exponentiation (**)
String Concatenation:

2. Concatenation of strings using the

CONCAT() function or || operator (in some databases).

3. Relational Operations:

Equal to (=), Not equal to (!= or <>), Greater than (>), Less than
(<)
Greater than or equal to (>=), Less than or equal to (<=)

4. Comparison Operators:

IN, NOT IN: Tests whether a value matches any value in a list.

BETWEEN ... AND: Checks if a value lies within a range.

LIKE: Matches patterns using wildcards (% for multiple characters, _


for a single character).

IS NULL, IS NOT NULL: Checks for NULL values.

5. Logical Operations:

AND, OR, NOT: Combines conditions to form complex expressions.


Special Operators:

EXISTS: Checks for existence of rows in a subquery.

ALL, ANY/SOME: Compares a value to a set of values.

CASE: Performs conditional operations.

6. Subqueries:

Queries nested within other queries to retrieve data.


Can be used in SELECT, WHERE, FROM, or other clauses.
Multiple Row Functions:

7. Aggregate functions like COUNT, SUM, AVG, MIN, MAX that operate
on multiple rows and return a single result.

8. Types of Joins:

INNER JOIN: Retrieves records that have matching values in both


tables.
LEFT (OUTER) JOIN: Retrieves all records from the left table and
matched records from the right.
RIGHT (OUTER) JOIN: Retrieves all records from the right table and
matched records from the left.
FULL (OUTER) JOIN: Retrieves all records when there is a match in
either left or right table.

9. Data Types:

Numeric (INT, FLOAT, DECIMAL), Character (VARCHAR, CHAR), Date and


Time (DATE, TIMESTAMP), etc.

10. Constraints:

Books Table Authors Table


+--------+--------------+ +-----------+--------------+
| BookID | Title | | AuthorID | AuthorName |
+--------+--------------+ +-----------+--------------+
| 1 | Book A | | 1 | Author X |
| 2 | Book B | | 2 | Author Y |
| 3 | Book C | | 3 | Author Z |
+--------+--------------+ +-----------+--------------+

Primary Key (PK):

In the Books table, the BookID column serves as the primary key. It
uniquely identifies
each book in the table. A primary key ensures that each entry in a
table is unique and cannot be null.
It helps in indexing and efficiently retrieving specific records.

Foreign Key (FK):

The AuthorID column in the Books table is a foreign key. It refers


to the AuthorID column
in the Authors table. A foreign key establishes a link between two
tables. In this case,
it connects books to their respective authors. The foreign key
ensures referential integrity,
meaning that a book can only have an AuthorID that exists in the
Authors table.

Unique: Ensures uniqueness of values in a column.

NOT NULL: Ensures a column does not contain NULL values.

# 𝗦𝗤𝗟 𝗾𝘂𝗲𝗿𝗶𝗲𝘀 𝗿𝘂𝗻 𝗶𝗻 𝘁𝗵𝗶𝘀 𝗼𝗿𝗱𝗲𝗿

We utilize SQL queries to access a collection of records that are


stored in our database tables.
Clauses are the building blocks of SQL queries. To get the right
outcomes, these clauses must be
executed in a specific order. SQL query execution order is the name
given to this sequence of operations.
𝗦𝗤𝗟 𝗾𝘂𝗲𝗿𝘆 𝗲𝘅𝗲𝗰𝘂𝘁𝗶𝗼𝗻 𝗼𝗿𝗱𝗲𝗿 refers to how the query clauses are evaluated
in accordance with the requirements
or how to optimize database search results. We use clauses in a
specific order known as the SQL
query execution order, similar to how we plan something step by step
and arrive at the end result.

# Here is the 𝗼𝗿𝗱𝗲𝗿 𝗶𝗻 𝘄𝗵𝗶𝗰𝗵 𝘁𝗵𝗲 𝗦𝗤𝗟 𝗰𝗹𝗮𝘂𝘀𝗲𝘀 𝗮𝗿𝗲 𝗲𝘅𝗲𝗰𝘂𝘁𝗲𝗱:

𝟭. 𝗙𝗥𝗢𝗠 - tables are joined to get the base data.


𝟮. 𝗪𝗛𝗘𝗥𝗘 - the base data is filtered.
𝟯. 𝗚𝗥𝗢𝗨𝗣 𝗕𝗬 - the filtered base data is grouped.
𝟰. 𝗛𝗔𝗩𝗜𝗡𝗚 - the grouped base data is filtered.
𝟱. 𝗦𝗘𝗟𝗘𝗖𝗧 - the final data is returned.
𝟲. 𝗢𝗥𝗗𝗘𝗥 𝗕𝗬 - the final data is sorted.
𝟳. 𝗟𝗜𝗠𝗜𝗧 - the returned data is limited to row count.

SQL PRACTICALS

-- Creating a Database for Students:

CREATE DATABASE Students;

-- Using the Created Database:

USE Student;

CREATE TABLE IF NOT EXISTS students (


student_id INT AUTO_INCREMENT PRIMARY KEY,
first_name VARCHAR(50) NOT NULL,
last_name VARCHAR(50) NOT NULL,
age INT,
gender ENUM('Male', 'Female', 'Other'),
email VARCHAR(100) UNIQUE
);

-----------------------------------------------------------------
DML (manipulate data present in the DB)

-- Inserting data into the students table


INSERT INTO students (first_name, last_name, age, gender, email)
VALUES ('John', 'Doe', 20, 'Male', '[email protected]');

INSERT INTO students (first_name, last_name, age, gender, email)


VALUES ('Jane', 'Smith', 22, 'Female', '[email protected]');
-- Inserting data into the students table
INSERT INTO students (first_name, last_name, age, gender, email)
VALUES ('sham', 'kumar', 20, 'Male', '[email protected]');

INSERT INTO students (first_name, last_name, age, gender, email)


VALUES ('ram', 'kumar', 29, 'Male', '[email protected]');

-- Inserting data into the students table


INSERT INTO students (first_name, last_name, age, gender, email)
VALUES ('adi', 'c r', 20, 'Male', '[email protected]');

INSERT INTO students (first_name, last_name, age, gender, email)


VALUES ('sneha', 'N', 22, 'Female', '[email protected]');

-- Inserting data into the students table


INSERT INTO students (first_name, last_name, age, gender, email)
VALUES ('pooja', 'G N', 20, 'Female', '[email protected]');

INSERT INTO students (first_name, last_name, age, gender, email)


VALUES ('sumanth', 'K', 29, 'Male', '[email protected]');

-- Inserting data into the students table


INSERT INTO students (first_name, last_name, age, gender, email)
VALUES ('pooja c', 'v n', 20, 'Female', '[email protected]');

INSERT INTO students (first_name, last_name, age, gender, email)


VALUES ('charan', 'C', 22, 'Female', '[email protected]');

-- Updating Data:

UPDATE students
SET age = 21
WHERE first_name = 'Sumanth';

UPDATE students
SET email = '[email protected]'
WHERE student_id = 2;

-- Deleting Data:

DELETE FROM students


WHERE student_id = 1;

-- 5. Delete Record
DELETE FROM students WHERE first_name = 'Jane';
-- Deletes all records of students named 'Jane'.

-----------------------------------------------------------------
DDL : Data Definition Language
-- DROP TABLE
-- Explanation: Drops (deletes) the entire table from the database.

DROP TABLE IF EXISTS students;

-- ALTER TABLE
-- Explanation: Modifies the table structure, like adding or
dropping columns.
-- Example (Adding a new column named city):
ALTER TABLE students ADD COLUMN city VARCHAR(50);

-- TRUNCATE TABLE
-- Explanation: Removes all the records/data from the table while
keeping the table structure intact.

TRUNCATE TABLE students;

-----------------------------------------------------------------
DCL : Data Control Language

—In MySQL, the GRANT and REVOKE statements are used to manage user
privileges or permissions within the database.
—Let's assume you want to grant or revoke certain privileges for a
specific user on the students table.
—For instance, granting SELECT, INSERT, UPDATE, and DELETE
privileges for a user named my_user to the students table:

— Grant privileges to a user

GRANT SELECT, INSERT, UPDATE, DELETE ON database_name.students TO


'my_user'@'localhost';

— Revoke privileges from a user

REVOKE SELECT, INSERT, UPDATE, DELETE ON database_name.students FROM


'my_user'@'localhost';

—REVOKE: Removes previously granted privileges from the user.


database_name.students: Specifies the table
- from which the privileges are revoked. 'my_user'@'localhost':
— Indicates the user and their location ('my_user' accessing from
'localhost'). These commands can
- be executed to grant or revoke specific privileges
— (such as SELECT, INSERT, UPDATE, DELETE, etc.) on the students
table for a particular user.
-----------------------------------------------------------------
TCL : Transaction Control Language

— In MySQL, transactions can be used to ensure the atomicity,


consistency, isolation, and
-- durability of operations performed on the database.

START TRANSACTION;

-- Inserting data into the students table

INSERT INTO students (first_name, last_name, age, gender, email)


VALUES ('John', 'Doe', 20, 'Male', '[email protected]'); I

NSERT INTO students (first_name, last_name, age, gender, email)


VALUES ('Jane', 'Smith', 22, 'Female', '[email protected]');

-- Commit the transaction


COMMIT;

— Explanation:
— START TRANSACTION: Begins a new transaction.
— COMMIT: Saves the changes made during the transaction to the
database permanently.

— If you want to roll back changes made during a transaction, use


ROLLBACK:

-- Start a transaction

START TRANSACTION;

-- Inserting data into the students table

INSERT INTO students (first_name, last_name, age, gender, email)


VALUES ('sham', 'kumar', 20, 'Male', '[email protected]');

INSERT INTO students (first_name, last_name, age, gender, email)


VALUES ('ram', 'kumar', 29, 'Male', '[email protected]');

-- Rollback the transaction


ROLLBACK;

— Explanation:
— ROLLBACK: Reverts the changes made during the transaction,
restoring the database to its
-- state before the transaction began.

-----------------------------------------------------------------
Querying Data
-- 1. Select All Records
SELECT * FROM students;
-- Retrieves all records from the students table.

-- 2. Select Specific Columns


SELECT first_name, last_name, age FROM students;
-- Retrieves specific columns (first_name, last_name, age) from the
students table.

-- 3. Filter by Condition
SELECT * FROM students WHERE age > 25;
-- Retrieves records where the age is greater than 25.

-- 4. Order by Ascending
SELECT * FROM students ORDER BY age ASC;
-- Retrieves all records, sorted by age in ascending order.

-- 5. Order by Descending
SELECT * FROM students ORDER BY age DESC;
-- Retrieves all records, sorted by age in descending order.

-- 6. Count Records
SELECT COUNT(*) FROM students;
-- Counts the total number of records in the students table.

-- 7. Average Age
SELECT AVG(age) FROM students;
-- Calculates the average age of all students.

-- 8. Maximum Age
SELECT MAX(age) FROM students;
-- Retrieves the maximum age among the students.

-- 9. Minimum Age
SELECT MIN(age) FROM students;
-- Retrieves the minimum age among the students.

-- 10. Distinct Values


SELECT DISTINCT gender FROM students;
-- Retrieves distinct values from the gender column.
-- 11. Group by Gender
SELECT gender, COUNT(*) FROM students GROUP BY gender;
-- Counts the number of students for each gender.

SELECT * FROM students WHERE email LIKE '%@example.com';


-- Retrieves students with email addresses from 'example.com'.

-- 12. Limit Results

SELECT * FROM students LIMIT 5;

-- 13. GROUP BY
-- Example 1: Group students by gender and count the number of
students in each gender group.

SELECT gender, COUNT(*) AS total_students


FROM students
GROUP BY gender;

-- Example 2: Group students by age and calculate the average age in


each age group.
--
SELECT CASE
WHEN age BETWEEN 20 AND 25 THEN '20-25'
WHEN age BETWEEN 26 AND 30 THEN '26-30'
ELSE 'Other'
END AS age_group,
AVG(age) AS avg_age
FROM students
GROUP BY age_group;

-- 14. View Specific Row (TOP)


-- Example 1: Display the top 3 records from the students table.

SELECT *
FROM students
LIMIT 3;

-- Example 2: Retrieve the top 5 youngest students ordered by age.

SELECT *
FROM students
ORDER BY age
LIMIT 5;

-- 15. View Specific Column (Sort Result)


-- Example 1: Display student first names in descending order.

SELECT first_name
FROM students
ORDER BY first_name DESC;
-- Example 2: Display last names and ages, sorted by age in
ascending order.

SELECT last_name, age


FROM students
ORDER BY age;

-- 16. Like (Search)


-- Example 1: Find students with 'oo' in their first names.

SELECT *
FROM students
WHERE first_name LIKE '%oo%';

-- Example 2: Retrieve students with 'j' as the second letter in


their last names.

SELECT *
FROM students
WHERE last_name LIKE '_j%';

-- 17. IN (Search)
-- Example 1: Retrieve students whose ages are 20, 22, or 29.

SELECT *
FROM students
WHERE age IN (20, 22, 29);

-- Example 18: Get students whose first names are either 'John' or
'Jane'.

SELECT *
FROM students
WHERE first_name IN ('John', 'Jane');

-- 19. > (Search)


-- Example 1: Find students older than 25 years.

SELECT *
FROM students
WHERE age > 25;

-- Example 2: Retrieve students whose last names come after 'D'


alphabetically.

SELECT *
FROM students
WHERE last_name > 'D';
-- 20. <> (Not Equal)
-- Example 1: Get students whose age is not 20.

SELECT *
FROM students
WHERE age <> 20;

-- Example 2: Retrieve students who are not male.

SELECT *
FROM students
WHERE gender <> 'Male';

-- 21. IS NULL
-- Example 1: Find students without an email address.

SELECT *
FROM students
WHERE email IS NULL;

-- Example 2: Retrieve students with NULL last names.

SELECT *
FROM students
WHERE last_name IS NULL;

-- 22. IS NOT NULL


-- Example 1: Get students with valid email addresses.

SELECT *
FROM students
WHERE email IS NOT NULL;
-- Example 2: Retrieve students with non-NULL first names.

SELECT *
FROM students
WHERE first_name IS NOT NULL;

-- 23. BETWEEN
-- Example 1: Retrieve students aged between 20 and 25.

SELECT *
FROM students
WHERE age BETWEEN 20 AND 25;
-- Example 2: Find students with IDs between 3 and 7.

SELECT *
FROM students
WHERE student_id BETWEEN 3 AND 7;
-- 24. SUM
-- Example 1: Calculate the total age of all students.

SELECT SUM(age) AS total_age


FROM students;

-- Example 2: Sum up the ages of male students.

SELECT SUM(age) AS total_male_age


FROM students
WHERE gender = 'Male';

-- 25. COUNT
-- Example 1: Count the total number of students.

SELECT COUNT(*) AS total_students


FROM students;

-- Example 2: Count the number of female students.

SELECT COUNT(*) AS total_female_students


FROM students
WHERE gender = 'Female';

-- 26. MAX
-- Example 1: Find the maximum age among students.

SELECT MAX(age) AS max_age


FROM students;

-- Example 2: Retrieve the oldest male student's age.

SELECT MAX(age) AS max_male_age


FROM students
WHERE gender = 'Male';

-- 27. MIN
-- Example 1: Find the minimum age among students.

SELECT MIN(age) AS min_age


FROM students;

-- Example 2: Retrieve the youngest female student's age.

SELECT MIN(age) AS min_female_age


FROM students
WHERE gender = 'Female';

-- 28. AVERAGE
-- Example 1: Calculate the average age of all students.

SELECT AVG(age) AS average_age


FROM students;

-- Example 2: Find the average age of male students.

SELECT AVG(age) AS average_male_age


FROM students
WHERE gender = 'Male';

-- 29. HAVING
-- Example 1: Get genders having more than two occurrences.

SELECT gender, COUNT(*) AS gender_count


FROM students
GROUP BY gender
HAVING COUNT(*) > 2;

-- Example 2: Retrieve ages where the count of students is greater


than 1.

SELECT age, COUNT(*) AS age_count


FROM students
GROUP BY age
HAVING COUNT(*) > 1;

-- 30. Change Data Type


-- Example 1: Convert a string to a date using the STR_TO_DATE
function.
SELECT STR_TO_DATE('2023-11-17', '%Y-%m-%d') AS formatted_date;

-- Example 2: Convert a string to an integer using CAST.


SELECT CAST('25' AS SIGNED) AS integer_value;

You might also like