0% found this document useful (0 votes)
35 views4 pages

SQL Commands and Techniques Overview

This document contains examples of SQL queries that demonstrate various SQL concepts and techniques. The examples select data from tables to return aggregate statistics, filter for specific countries or date ranges, join multiple tables, use subqueries and common table expressions (CTE) to break queries into logical parts, and more. The document is intended as a tutorial or reference for the SQL language.
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
35 views4 pages

SQL Commands and Techniques Overview

This document contains examples of SQL queries that demonstrate various SQL concepts and techniques. The examples select data from tables to return aggregate statistics, filter for specific countries or date ranges, join multiple tables, use subqueries and common table expressions (CTE) to break queries into logical parts, and more. The document is intended as a tutorial or reference for the SQL language.
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

SQL Live 05

SQL Code

SELECT
invoicedate,
-- STRing Format (Date)Time
STRFTIME("%Y", invoicedate) AS year,
STRFTIME("%m", invoicedate) AS month,
STRFTIME("%d", invoicedate) AS day,
STRFTIME("%Y-%m", invoicedate) AS monthid
FROM invoices
WHERE monthid = "2009-09"

Create table eu_customers

CREATE TABLE eu_customers AS


SELECT firstname, country, email
FROM customers
WHERE country IN ('Belgium','France','Italy');

DROP TABLE eu_customers;

Aggregate Functions

-- aggregate functions
SELECT
COUNT(*) AS total_songs,
ROUND(AVG(bytes),2) AS avg_bytes,
ROUND(SUM(bytes/(1024*1024)),2) AS sum_mb,
MIN(bytes) AS min_bytes,
MAX(bytes) AS max_bytes
FROM tracks;

Clean NULL values

SELECT
company,
COALESCE(company, "B2C") AS clean_company,

SQL Live 05 1
CASE
WHEN company IS NULL THEN "B2C"
ELSE "B2B"
END AS segment
FROM customers;

Having vs. Where

SELECT
CASE
WHEN company IS NULL THEN "B2C"
ELSE "B2B"
END AS segment,
country,
COUNT(*) AS num_customers
FROM customers
WHERE country IN ("Belgium", "France", "Italy")
GROUP BY 1,2
HAVING num_customers > 1

JOIN Tables

-- join syntax
SELECT
[Link] AS artist_name,
[Link] AS album_name,
[Link] AS track_name
FROM artists AS ar
INNER JOIN albums AS al
ON [Link] = [Link] -- pk=fk
INNER JOIN tracks AS tr
ON [Link] = [Link];

Aggregate + JOIN

-- join syntax
-- virtual table (VIEW)
CREATE VIEW genre_stats AS
SELECT
[Link],
COUNT(*) as count_tracks,
AVG(milliseconds) AS avg_milliseconds

SQL Live 05 2
FROM artists AS ar
JOIN albums AS al ON [Link] = [Link]
JOIN tracks AS tr ON [Link] = [Link]
JOIN genres AS ge ON [Link] = [Link]
GROUP BY 1
ORDER BY 3 DESC
LIMIT 5;

Subqueries (Select ซ้อน Select)


breakdown our long query into steps

-- subqueries
SELECT firstname, country
FROM (SELECT * FROM customers) AS sub
WHERE country = 'United Kingdom';

-- WITH : common table expression


WITH sub AS (SELECT * FROM customers)

SELECT firstname, country


FROM sub
WHERE country = 'United Kingdom';

Example subqueries + with clause

😛 Query American customers who purchase our products in 2009-10 (invoices)

-- basic query
SELECT
firstname,
lastname,
email,
COUNT(*) count_order
FROM customers c
JOIN invoices i ON [Link] = [Link]
WHERE [Link] = 'USA' AND STRFTIME("%Y-%m",[Link]) = "2009-10"
GROUP BY 1,2,3;

-- with clauses
WITH usa_customers AS (
SELECT * FROM customers

SQL Live 05 3
WHERE country = 'USA'
), invoice_2009 AS (
SELECT * FROM invoices
WHERE STRFTIME("%Y-%m",invoicedate) = "2009-10"
)

SELECT firstname, lastname, email, COUNT(*)


FROM usa_customers t1
JOIN invoice_2009 t2
ON [Link] = [Link]
GROUP BY 1,2,3;

-- standard subqueries
SELECT firstname, lastname, email, COUNT(*)
FROM (
SELECT * FROM customers
WHERE country = 'USA'
) AS t1
JOIN (
SELECT * FROM invoices
WHERE STRFTIME("%Y-%m",invoicedate) = "2009-10"
) AS t2
ON [Link] = [Link]
GROUP BY 1,2,3;

SQL Live 05 4

Common questions

Powered by AI

To clean NULL values in a customer data table, you can employ the COALESCE function. This function replaces NULL values with a specified default value, ensuring consistency in the dataset. For example, `COALESCE(company, "B2C") AS clean_company` will replace NULLs in the 'company' column with the string 'B2C', making the data more reliable for analysis .

Creating views in SQL abstracts complex queries into a simplified representation that can be treated like a regular table. This utility is beneficial for performance because the view can encapsulate and reuse sophisticated logic while allowing SQL optimizers to better manage query execution plans. For example, a view such as `CREATE VIEW genre_stats AS SELECT ge.name, COUNT(*) as count_tracks, AVG(milliseconds) AS avg_milliseconds FROM... ORDER BY 3 DESC LIMIT 5` streamlines access to frequently-needed aggregated data, ensuring improved query efficiency and simplicity in repeated operations .

The STRFTIME function can be used to extract date components from a datetime column, allowing for precise querying by year and month. For example, in a query like `SELECT * FROM invoices WHERE STRFTIME("%Y-%m", invoicedate) = "2009-10"`, STRFTIME is used to match invoices from October 2009. This method is beneficial because it enables temporal data slicing with simple string matching, which can optimize and simplify the querying of datasets for specific periods without necessitating a breakdown of date elements into separate fields .

SQL join operations, such as INNER JOIN, allow you to retrieve data from multiple tables by linking them on a common field. A typical use case is joining the 'artists', 'albums', and 'tracks' tables to display track information along with its artist and album details. This can be done with statements like `INNER JOIN albums AS al ON ar.artistid = al.artistid` and subsequently joining 'tracks' to 'albums' using `INNER JOIN tracks AS tr ON tr.albumid = al.albumid` .

Aggregate functions in SQL, such as COUNT, AVG, SUM, MIN, and MAX, are used to perform calculations on a set of values, allowing for data summarization and analysis. For instance, `SELECT COUNT(*) AS total_songs, ROUND(AVG(bytes),2) AS avg_bytes, ROUND(SUM(bytes/(1024*1024)),2) AS sum_mb, MIN(bytes) AS min_bytes, MAX(bytes) AS max_bytes FROM tracks` showcases how these functions can provide insights on the number of songs, average size, total size in megabytes, and find the smallest and largest track size .

The WHERE clause is used to filter rows before any groupings are made, thus it applies to individual records. For example, filtering customers by country occurs with WHERE. HAVING, on the other hand, is used after the rows are grouped, to filter based on conditions related to aggregates, like filtering groups of customers that have more than one entry. For instance, `HAVING num_customers > 1` filters out groups where the count of customers is more than one after Gיצוב by country and company type .

SQL can segment customers based on their company type using conditional operations such as CASE statements or the COALESCE function. The statement `CASE WHEN company IS NULL THEN "B2C" ELSE "B2B" END AS segment` assigns customers to 'B2C' if their company value is NULL, otherwise they're categorized as 'B2B'. Similarly, COALESCE can be used to replace NULL values with a default, such as 'B2C' .

SQL subqueries allow the nesting of queries to be executed as part of a larger query. When combined with the WITH clause, also known as a Common Table Expression (CTE), they enhance readability by structuring complex queries into reusable components. This approach makes the SQL code easier to follow and maintain. For example, defining `WITH usa_customers AS (SELECT * FROM customers WHERE country = 'USA')` allows this subset to be used more intuitively in subsequent operations like joins. This not only streamlines the primary query logic but also localizes changes to a specific part of the query structure, improving maintainability .

CTEs simplify and optimize complex queries by breaking down the SQL code into modular parts that can be reused in broader queries. For instance, a CTE can collect all American customers and their invoices from a specific month in a structured manner allowing the main query to focus on summarizing and analyzing this subset. A CTE such as `WITH usa_customers AS (SELECT * FROM customers WHERE country = 'USA')` helps isolate a subset, which can be efficiently joined with another CTE like `WITH invoice_2009 AS (SELECT * FROM invoices WHERE STRFTIME("%Y-%m",invoicedate) = "2009-10")`, streamlining data processing specific to October 2009 purchases .

Utilizing subqueries to target specific subpopulations within a database is crucial for isolating and analyzing subsets of data without affecting the entire dataset. This targeted approach allows for precise operations, such as analysis or reporting focused on a particular group. For instance, querying American customers who purchased products in October 2009 can be efficiently handled by employing subqueries for customers and invoices, ensuring that calculations or summaries are accurately scoped to the desired population. This method retains the integrity and granularity of the data while allowing for highly targeted insights .

You might also like