Docsity

THE DEFINITIVE GUIDE TO SQL FUNDAMENTALS, Appunti di Database Relazionali

Toggle sidebar
bg1
THE DEFINITIVE GUIDE TO SQL
FUNDAMENTALS
Part 1: Core Concepts and Architecture
What is SQL?
SQL (Structured Query Language) is the standard programming language used to
communicate with Relational Database Management Systems (RDBMS). It is the
mechanism by which software applications, data analysts, and administrators interact with
stored data. Unlike general-purpose programming languages like Python or Java, which are
imperative (telling the computer how to do something), SQL is declarative. You tell the
database what you want, and the database engine decides the most efficient way to retrieve
it.
The Relational Model
To understand SQL, one must understand the structure it interacts with.
● The Database: A container that holds a collection of organized data.
● The Table (Relation): The primary unit of storage. It is a grid of rows and columns,
similar to a spreadsheet.
● The Column (Attribute): A vertical entity in a table that contains all information
associated with a specific field. Every column has a defined data type (e.g., Integer,
Text, Date).
● The Row (Tuple): A horizontal entity in a table. It represents a single, unique data
record.
SQL Sub-Languages
SQL is not just one command set; it is divided into distinct subsets based on function:
1. DDL (Data Definition Language): Defines the structure of the database (CREATE,
ALTER, DROP).
2. DML (Data Manipulation Language): Manages the data within the structures
(INSERT, UPDATE, DELETE).
3. DQL (Data Query Language): Retrieves data (SELECT).
4. DCL (Data Control Language): Manages access and permissions (GRANT,
REVOKE).
5. TCL (Transaction Control Language): Manages changes saved by DML (COMMIT,
ROLLBACK).
pf3
pf4
pf5

Anteprima parziale del testo

Scarica THE DEFINITIVE GUIDE TO SQL FUNDAMENTALS e più Appunti in PDF di Database Relazionali solo su Docsity!

THE DEFINITIVE GUIDE TO SQL

FUNDAMENTALS

Part 1: Core Concepts and Architecture

What is SQL?

SQL (Structured Query Language) is the standard programming language used to communicate with Relational Database Management Systems (RDBMS). It is the mechanism by which software applications, data analysts, and administrators interact with stored data. Unlike general-purpose programming languages like Python or Java, which are imperative (telling the computer how to do something), SQL is declarative. You tell the database what you want, and the database engine decides the most efficient way to retrieve it.

The Relational Model

To understand SQL, one must understand the structure it interacts with.

● The Database: A container that holds a collection of organized data. ● The Table (Relation): The primary unit of storage. It is a grid of rows and columns, similar to a spreadsheet. ● The Column (Attribute): A vertical entity in a table that contains all information associated with a specific field. Every column has a defined data type (e.g., Integer, Text, Date). ● The Row (Tuple): A horizontal entity in a table. It represents a single, unique data record.

SQL Sub-Languages

SQL is not just one command set; it is divided into distinct subsets based on function:

  1. DDL (Data Definition Language): Defines the structure of the database (CREATE, ALTER, DROP).
  2. DML (Data Manipulation Language): Manages the data within the structures (INSERT, UPDATE, DELETE).
  3. DQL (Data Query Language): Retrieves data (SELECT).
  4. DCL (Data Control Language): Manages access and permissions (GRANT, REVOKE).
  5. TCL (Transaction Control Language): Manages changes saved by DML (COMMIT, ROLLBACK).

Part 2: Defining the Structure (DDL)

Data Definition Language is used to build the skeleton of your database.

CREATE: Building Objects

The CREATE command is used to establish new databases, tables, or views. When creating a table, you must define the column names and their specific data types.

● VARCHAR vs. CHAR: One common distinction is between variable and fixed text. VARCHAR(50) allocates only as much space as the text needs (efficient). CHAR(50) always allocates space for 50 characters, padding with spaces if necessary (rigid but faster for fixed-length codes).

ALTER: Modifying Structure

Requirements change. The ALTER command allows you to modify an existing table without deleting it.

● ADD: Adds a new column to the table. ● DROP COLUMN: Removes a column and all data stored within that specific column. ● MODIFY/ALTER COLUMN: Changes the data type of a column (e.g., changing a field from Integer to Decimal).

DROP and TRUNCATE: Removing Objects

There is a critical distinction between deleting data and deleting structure.

● DROP TABLE: This is the nuclear option. It removes the table structure and all data inside it permanently. The table ceases to exist. ● TRUNCATE TABLE: This empties the table. It removes all rows but keeps the table structure (columns and constraints) intact. It is much faster than deleting rows one by one because it simply deallocates the data pages.

Part 3: Manipulating Data (DML)

Data Manipulation Language is how you perform "CRUD" operations (Create, Read, Update, Delete) on the actual records.

INSERT: Adding Data

The INSERT INTO command adds new rows. You can specify columns explicitly or insert values for all columns.

● SELECT DISTINCT: Removes duplicate rows from the result set. If you select a list of cities from a Customer table, you will get "New York" 500 times. Adding DISTINCT returns "New York" once.

ORDER BY

Data in a database is not stored in any specific order; it is a heap. If you need data sorted, you must explicitly ask for it using ORDER BY.

● ASC: Ascending order (Default). A to Z, 0 to 9. ● DESC: Descending order. Z to A, 9 to 0.

Part 5: Filtering and Logic

The real power of SQL lies in its ability to filter vast datasets down to relevant information using the WHERE clause.

Comparison Operators

Standard math comparisons apply: Equal (=), Not Equal (<> or !=), Greater Than (>), Less

Than (<).

Logical Operators

● AND: Both conditions must be true. ● OR: At least one condition must be true. ● NOT: Inverses the condition. ● Priority: AND is processed before OR. Always use parentheses ( ) when mixing them to ensure the logic executes as intended.

Special Operators

● BETWEEN: Selects values within a given range (inclusive). It works for numbers, text, and dates. ● IN: Checks if a value matches any value in a list. It is a shorthand for multiple OR conditions. ● LIKE: Used for pattern matching with wildcards. ○ % (Percent): Represents zero, one, or multiple characters. LIKE 'A%' finds anything starting with A. ○ _ (Underscore): Represents a single character. LIKE '_a%' finds anything where the second letter is 'a'. ● IS NULL: NULL represents missing or unknown data. You cannot use = or != with NULL because "unknown" does not equal "unknown." You must use IS NULL or IS NOT NULL.

Part 6: Joining Tables (Relational Power)

In a relational database, data is split across multiple tables to reduce redundancy (Normalization). Joins are used to reconstruct this data into a single view.

Inner Join

This is the most common join. It returns only the rows where there is a match in both tables.

● Scenario: A List of Customers who have placed Orders. ● Result: If a Customer has never placed an order, they do not appear in the results.

Left Join (Left Outer Join)

This returns all rows from the left table, and the matching rows from the right table. If there is no match, the right side will contain NULL values.

● Scenario: A report of All Customers, showing their orders if they have any. ● Result: Customers with no orders still appear, but their "Order Date" column will be NULL. This is essential for finding "missing" data (e.g., "Show me customers who have bought nothing").

Right Join (Right Outer Join)

The reverse of the Left Join. It returns all rows from the right table and matching rows from the left. It is rarely used in practice because you can simply flip the tables in a Left Join to achieve the same result.

Full Outer Join

Returns all rows when there is a match in either the left or right table. It combines the results of both Left and Right joins.

● Result: You get all Customers and all Orders, regardless of whether they match.

Part 7: Aggregation and Grouping

Raw data is often too granular. SQL provides aggregation functions to summarize data.

Aggregate Functions

These functions take multiple rows and return a single value.

● It enforces referential integrity: you cannot insert a value in the Child table (Foreign Key) if it doesn't exist in the Parent table (Primary Key).

Unique

Ensures that all values in a column are different. Unlike the Primary Key, you can usually have one NULL value, and you can have multiple Unique constraints per table (e.g., an Email Address column).

Not Null

Enforces that a column cannot accept NULL values. The record will be rejected if this field is left empty.

Check

Ensures that the values in a column satisfy a specific condition.

● Example: A "Age" column must be greater than 18. If someone tries to insert 17, the database rejects the entry.

Summary

SQL is the language of data. By mastering DDL (Structure), DML (Data), and DQL (Querying), you gain control over how information is stored, secured, and retrieved. Whether you are building a simple web application or analyzing millions of financial records, these fundamental blocks—tables, joins, and aggregates—remain the constant tools of the trade.