4.1 SQL Basics (173m) Flashcards

1
Q

What is SQL? Can you explain each of the SQL databases below: 1.MySQL, 2.PostgreSQL, 3.Microsoft SQL, 4.Oracle, 5.SQLite? And also can you explain other databases (NoSQL databases) including 1.MongoDB, 2.CouchBase, 3.Redis.

A

SQL (Structured Query Language) is a programming language used for managing relational databases. It provides a standardized way to interact with databases, allowing users to create, manipulate, and query data stored in the database.

Let’s explore each of the SQL databases you mentioned:

  1. MySQL: MySQL is an open-source relational database management system (RDBMS). It is widely used and known for its speed, reliability, and ease of use. MySQL supports various operating systems and is commonly used for web applications.
  2. PostgreSQL: PostgreSQL is also an open-source RDBMS known for its robustness, scalability, and advanced features. It provides support for complex queries, transactions, and concurrency control. PostgreSQL is highly extensible and offers a wide range of data types and indexing capabilities.
  3. Microsoft SQL Server: Microsoft SQL Server is a relational database management system developed by Microsoft. It is primarily used on Windows platforms and offers a comprehensive set of tools for database management, reporting, and analysis. SQL Server supports enterprise-level applications and provides features like data warehousing, replication, and high availability.
  4. Oracle: Oracle Database is a widely used RDBMS developed by Oracle Corporation. It is known for its scalability, security, and reliability. Oracle offers advanced features such as partitioning, clustering, and automatic storage management. It is commonly used in large enterprise applications that require high performance and data integrity.
  5. SQLite: SQLite is a lightweight and embedded RDBMS. It is serverless and operates directly on the local device, making it suitable for mobile and desktop applications. SQLite stores the entire database in a single file, making it easy to manage and deploy. It is widely adopted for small-scale applications and has a small footprint.

Now, let’s move on to the NoSQL databases you mentioned:

  1. MongoDB: MongoDB is a document-oriented NoSQL database. It stores data in flexible, JSON-like documents, allowing for dynamic schemas. MongoDB is scalable, provides high performance, and supports rich querying capabilities. It is commonly used in scenarios where flexibility and scalability are important, such as web applications and big data environments.
  2. Couchbase: Couchbase is a distributed NoSQL database designed for high availability and scalability. It combines key-value and document-oriented data models. Couchbase supports a flexible schema and provides features like caching, indexing, and full-text search. It is often used in use cases that require fast data access, real-time analytics, and mobile synchronization.
  3. Redis: Redis is an in-memory data structure store that can function as a NoSQL database, cache, or message broker. It supports various data structures like strings, lists, sets, and hashes. Redis is known for its high performance, low latency, and advanced data manipulation capabilities. It is frequently used for real-time applications, caching, and session management.

Each of these databases has its strengths and is suitable for different use cases. The choice of a database depends on factors like the nature of data, scalability requirements, performance needs, and specific features required by the application.

Here are examples of popular companies and the databases they use, along with the corresponding backend and frontend technologies they employ:

  1. MySQL:
    • Airbnb: Airbnb, a popular online marketplace for accommodations, uses MySQL as its primary database. They also use a combination of Python and JavaScript for their backend, and React.js for the frontend.
    • Pinterest: Pinterest, a visual discovery platform, relies on MySQL for data storage. They utilize Python and Django for their backend, and React.js for the frontend.
  2. PostgreSQL:
    • Apple: Apple, a renowned technology company, utilizes PostgreSQL for various purposes, including storing data for their iTunes and iCloud services. They have a proprietary backend technology stack and use various frontend frameworks depending on the product.
    • Instagram: Instagram, a widely-used social media platform, uses PostgreSQL as their primary database for storing user data, posts, and interactions. They employ Python and Django for their backend, and React.js for the frontend.
  3. Microsoft SQL Server:
    • Stack Overflow: Stack Overflow, a popular question-and-answer platform for programmers, relies on Microsoft SQL Server as its backend database. They use C# and .NET for their backend, and JavaScript (with jQuery) for the frontend.
    • Expedia: Expedia, an online travel agency, employs Microsoft SQL Server for their data storage needs. They use a combination of Java and .NET for their backend, and JavaScript (with React.js) for the frontend.
  4. Oracle:
    • Amazon: Amazon, a multinational technology company, uses Oracle databases for some of their critical systems, including the order management system. They have a proprietary backend technology stack and use various frontend frameworks depending on the product.
    • Bank of America: Bank of America, a leading financial institution, utilizes Oracle databases for managing their banking systems. They have a custom-built backend system and use various frontend technologies for different applications.
  5. SQLite:
    • WhatsApp: WhatsApp, a popular messaging application, utilizes SQLite for storing message data on users’ devices. They use Erlang for their backend and React Native for the frontend.
    • Firefox: Mozilla Firefox, a widely-used web browser, employs SQLite for various purposes, including storing browser history and bookmarks. They use a combination of C++ and JavaScript for their backend, and HTML, CSS, and JavaScript for the frontend.

Moving on to NoSQL databases:

  1. MongoDB:
    • Airbnb: In addition to MySQL, Airbnb also uses MongoDB for certain use cases, such as logging and user activity tracking. They primarily employ Python and JavaScript for their backend, and React.js for the frontend.
    • The New York Times: The New York Times, a prominent media company, uses MongoDB to store and manage article metadata, including tags and annotations. They have a custom-built backend system and use various frontend technologies for different applications.
  2. Couchbase:
    • LinkedIn: LinkedIn, a professional networking platform, uses Couchbase for its distributed data caching layer. They primarily use Java and Scala for their backend, and JavaScript (with React.js) for the frontend.
    • Verizon: Verizon, a telecommunications company, employs Couchbase for caching and high-performance data storage. They have a custom-built backend system and use various frontend technologies for different applications.
  3. Redis:
    • Twitter: Twitter, a popular social media platform, uses Redis for caching and managing real-time data, such as tweets and user timelines. They primarily use Scala and Java for their backend, and JavaScript (with React.js) for the frontend.
    • Pinterest: Alongside MySQL, Pinterest also uses Redis for various caching needs, including caching user feeds and search results. They utilize Python and Django for their backend, and React.js for the frontend.

It’s worth noting that the technology stacks and databases used by

these companies may evolve over time, and they may employ a combination of other technologies based on their specific requirements.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q

What is database Schema?

A

A database schema is a logical structure or blueprint that defines how data is organized, stored, and related within a database. It represents the overall design and organization of the database and provides a framework for creating and managing tables, relationships, constraints, and other database objects.

A database schema typically includes the following components:

  1. Tables: A table represents a collection of related data and is the fundamental building block of a database schema. Tables consist of rows (records) and columns (fields) that define the structure and attributes of the data stored in the database.
  2. Columns: Columns define the individual data elements or attributes within a table. Each column has a name, data type, and optionally, constraints that enforce rules on the data stored in that column (e.g., uniqueness, data format, foreign key references).
  3. Relationships: Relationships establish connections between tables based on common data values. The most common type of relationship is a foreign key relationship, where a column in one table refers to the primary key column of another table, creating a link between the two tables.
  4. Constraints: Constraints define rules and restrictions on the data stored in the database. They ensure data integrity and enforce certain conditions, such as uniqueness, referential integrity, and data validation.
  5. Indexes: Indexes are data structures that enhance data retrieval performance by providing quick access to specific data within a table. They improve query performance by creating a sorted representation of the data based on one or more columns.
  6. Views: Views are virtual tables that are derived from the underlying tables in the database. They present a customized or filtered view of the data to users or applications, simplifying data access and providing an additional layer of security.

By defining a database schema, developers and database administrators establish the structure, relationships, and rules that govern how data is stored, organized, and accessed within the database system. The schema acts as a blueprint for creating and managing the database, ensuring consistency, data integrity, and efficient data retrieval.

Example:
Sure! Let’s consider an example of a simple database schema for a fictional e-commerce website.

  1. Tables:
    • Customers: This table stores information about the customers of the e-commerce website. It may include columns such as customer ID, name, email, address, and phone number.
    Example:
    \+----+--------------+-----------------+-------------------+--------------+
    | ID | Name         | Email           | Address           | Phone        |
    \+----+--------------+-----------------+-------------------+--------------+
    | 1  | John Doe     | john@example.com | 123 Main St       | 555-123-4567 |
    | 2  | Jane Smith   | jane@example.com | 456 Elm St        | 555-987-6543 |
    \+----+--------------+-----------------+-------------------+--------------+
    • Products: This table stores information about the products available on the website. It may include columns such as product ID, name, description, price, and quantity in stock.
    Example:
    \+----+-----------------+----------------------------------+-------+--------+
    | ID | Name            | Description                      | Price | Stock  |
    \+----+-----------------+----------------------------------+-------+--------+
    | 1  | T-shirt         | Soft cotton t-shirt               | 19.99 | 100    |
    | 2  | Jeans           | Slim-fit denim jeans              | 49.99 | 50     |
    \+----+-----------------+----------------------------------+-------+--------+
  2. Relationships:
    • Orders: This table represents customer orders and establishes a relationship with the Customers and Products tables. It may include columns such as order ID, customer ID (foreign key referencing the Customers table), product ID (foreign key referencing the Products table), quantity, and order date.
    Example:
    \+----+-------------+------------+----------+------------+
    | ID | Customer_ID | Product_ID | Quantity | Order_Date |
    \+----+-------------+------------+----------+------------+
    | 1  | 1           | 1          | 2        | 2023-06-01 |
    | 2  | 1           | 2          | 1        | 2023-06-05 |
    \+----+-------------+------------+----------+------------+
  3. Constraints:
    • Unique Constraint: The email column in the Customers table can have a unique constraint, ensuring that each customer has a unique email address.
    Example:
    \+----+--------------+-----------------+-------------------+--------------+
    | ID | Name         | Email           | Address           | Phone        |
    \+----+--------------+-----------------+-------------------+--------------+
    | 1  | John Doe     | john@example.com | 123 Main St       | 555-123-4567 |
    | 2  | Jane Smith   | jane@example.com | 456 Elm St        | 555-987-6543 |
    \+----+--------------+-----------------+-------------------+--------------+
    • Foreign Key Constraint: The Customer_ID column in the Orders table references the ID column in the Customers table, ensuring that only valid customer IDs can be inserted into the Orders table.
    Example:
    ```
    +—-+————-+————+———-+————+
    | ID | Customer_ID | Product_ID | Quantity | Order_Date |
    +—-+————-+————+———-+————+
    | 1 | 1 | 1 | 2 | 2023-06-01 |
    |

2 | 1 | 2 | 1 | 2023-06-05 |
+—-+————-+————+———-+————+
```

This is a simplified example of a database schema for an e-commerce website. The schema defines the structure and relationships between tables, allowing for efficient storage, retrieval, and management of data within the database.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q

Give a comprehensible list of data types and examples for each in SQL database?

A

Certainly! Here is a list of common data types used in SQL databases, along with examples for each type:

  • 1.Integer:
    1. Examples: 1, 10, -5, 1000
  • 2.Decimal/Numeric:
    1. Examples: 3.14, 2.5, -0.75, 100.99
  • 3.Char:
    1. Fixed-length character string.
    2. Examples: ‘Hello’, ‘OpenAI’, ‘SQL’
  • 4.Varchar:
    1. Variable-length character string.
    2. Examples: ‘John Doe’, ‘example@gmail.com’, ‘Product XYZ’
  • 5.Text:
    1. Variable-length character string for larger text blocks.
    2. Examples: ‘Lorem ipsum dolor sit amet…’, ‘Description of the article…’
  • 6.Date:
    1. Stores a date.
    2. Examples: ‘2023-06-25’, ‘1990-12-31’
  • 7.Time:
    1. Stores a time value.
    2. Examples: ‘10:30:00’, ‘18:45:23’
  • 8.DateTime/Timestamp:
    1. Stores both date and time.
    2. Examples: ‘2023-06-25 14:30:00’, ‘2022-01-01 00:00:00’
  • 9.Boolean:
    1. Represents true or false.
    2. Examples: true, false
  • 10.Binary:
    • Stores binary data, such as images or files.
    • Examples: 0x2550AABB, 0b11010101
  • 11.Float/Real:
    • Floating-point number with decimal precision.
    • Examples: 3.1415, 2.71828, -1.2345
  • 12.Double Precision:
    • Double-precision floating-point number.
    • Examples: 3.14159265359, 1.23456789012
  • 13.Enum:
    • A predefined set of values that can be chosen.
    • Examples: ‘Male’, ‘Female’, ‘Other’
  • 14.JSON:
    • Stores JSON (JavaScript Object Notation) data.
    • Examples: ‘{“name”: “John”, “age”: 30}’, ‘[1, 2, 3]’
  • 15.XML:
    • Stores XML (eXtensible Markup Language) data.
    • Examples: '<person><name>John</name><age>30</age></person>'

These are just some of the common data types used in SQL databases. Different database management systems may offer additional data types or variations of these types. It’s important to consult the documentation of the specific database system you are working with to understand the available data types and their specific characteristics and usage.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
4
Q

What does the following code do in SQL? Explain the code completely.

SELECT * FROM books;

A

The SQL code you provided, SELECT * FROM books;, is a query that retrieves all the data from the “books” table in a database.

Let’s break down the code and explain its components:

  • SELECT: This keyword is used to specify the columns or data that you want to retrieve from the database. In this case, the * (asterisk) is used as a shorthand notation to select all columns in the “books” table.
  • FROM: This keyword indicates the table from which you want to retrieve the data. In this case, the table is named “books”.
  • books: This is the name of the table from which the data will be fetched. It is the identifier that represents the specific table within the database.

Therefore, the code SELECT * FROM books; instructs the database management system to retrieve all the rows and columns from the “books” table and return the result set containing all the data stored in that table. The * in the SELECT clause denotes that all columns in the “books” table should be included in the query result.

Treehouse Notes:
Definitions
* Syntax: The vocabulary and grammatical rules surrounding the structure of your code.
* Keywords: The vocabulary words of a programming language used to issue commands to a computer.

SQL Used:
~~~
SELECT * FROM <table name>;
~~~
* The asterisk or star symbol (*) means all columns.
* The semi-colon (;) terminates the statement like a period in a sentence or a question mark in a question.

Examples:
~~~
SELECT * FROM books;
SELECT * FROM products;
SELECT * FROM users;
SELECT * FROM countries;
~~~

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
5
Q

Challenge 1/5: In this code challenge you have an eCommerce database full of tables that you might expect to see in a real database.

Write a SQL query to answer the following question. What are all the products in the products table?

Challenge 2/5: Write the SQL to retrieve all customer information from the users table.

Challenge 3/5: Select all addresses from the customer_addresses table.

Challenge 4/5: We’re using a different database now. Did you know mobile phones have databases? Find all the contacts in this smartphone database. All the contacts are in a table called phone_book.

Challenge 5/5: In the Yorkshire Division Four in Rugby, the team Hessle RUFC have a website that shows their latest matches. Their database holds a results table that stores their latest wins and losses. Why not have a look at their latest results yourself!?

A

Solution to Challenges:
~~~
SELECT * FROM products; # challenge 1
SELECT * FROM users; # challenge 2
SELECT * FROM customer_addresses; # challenge 3
SELECT * FROM phone_book; # challenge 4
SELECT * FROM results; # challenge 5
~~~

Select is a keyword; From is a keyword.
* indicates everything within the table.
; indicates closing of the command.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
6
Q

How will you select a column from a table in SQL?

A

Answer:

SELECT * FROM patrons;

* indicates to select all columns.

SELECT email FROM patrons;

If you want to select email or first_name column, you can simply put it instead of astericks.

You can also select two or more columns like this:
SELECT first_name, email FROM patrons;

Treehouse Notes:
SQL Used
Retrieving a single column:
~~~
SELECT <column> FROM <table name>;
~~~</column>

Examples:
~~~
SELECT email FROM users;
SELECT first_name FROM users;
SELECT name FROM products;
SELECT zip_code FROM addresses;
~~~

Retrieving multiple columns:
~~~
SELECT <column name 1>, <column name 2>, … FROM <table name>;
~~~

Examples:
~~~
SELECT first_name, last_name FROM customers;
SELECT name, description, price FROM products;
SELECT title, author, isbn, year_released FROM books;
SELECT name, species, legs FROM pets;
~~~

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
7
Q

Challenge 1: Here are the columns in a users table in an e-commerce site: id, username, password, first_name, last_name.

Run a SQL query to get the two columns you’d need to generate the full names of each customer.

Challenge 2: We’re still in the e-commerce database. This time, from the products table, get the name of every product.

Challenge 3: In the e-commerce database there’s a customer_addresses table with the following columns: id, nickname, street, city, state, zip, user_id.

Select all the columns that are to do with the address. For example, all columns except id, nickname and user_id.

Challenge 4: We’re using a database on a smartphone again. We have a phone_book table. In here there’s an id, first_name, last_name and phone.

As the user types the phone number in we want to show possible autocomplete values. Bring back only the phone numbers of each contact only. Our smartphone can work out which of the results to show.

Challenge 5: We’re still using the phone_book table. Remember it has the columns of id, first_name, last_name and phone.

Imagine a user is typing someone’s last name in a search facility on the phone. As the user types, suggestions will appear on the screen. Bring back both the first name and last name for every person in the phone book. The phone will filter the appropriate suggestions.

A

Answer to the challenges:

SELECT first_name, last_name FROM users; #challenge 1
SELECT name FROM products; #challenge 2
SELECT street, city, state, zip FROM customer_addresses; #challenge 3
SELECT phone FROM phone_book; #challenge 4
SELECT first_name, last_name FROM phone_book; #challenge 5
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
8
Q

From books database, using sql show only title and first_published. The title column should appear as “Title” and first_published column should appear as “First Published”.

A

It can be written as:
~~~
SELECT title AS Title, first_published AS “First Published” FROM books;
~~~

or can also be written as:
~~~
SELECT title Title, first_published “First Published” FROM books;
~~~

TreeHouse Notes:
SQL Used
~~~
SELECT <column> AS <alias> FROM <table name>;
SELECT <column> <alias> FROM <table name>;
~~~</alias></column></alias></column>

Examples:
~~~
SELECT username AS Username, first_name AS “First Name” FROM users;
SELECT title AS Title, year AS “Year Released” FROM movies;
SELECT name AS Name, description AS Description, price AS “Current Price” FROM products;
SELECT name Name, description Description, price “Current Price” FROM products;
~~~

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
9
Q

Challenge 1:
We’re back in our e-commerce database. There’s a products table with the columns id, name, description and price.

Can you retrieve both the name and description aliased as “Product Name” and “Product Description”.

Challenge 2:
In the users table we have columns of id, username, password, first_name and last_name.

Select the username and the first and last names and alias them as “Username”, “First Name” and “Last Name”.

Challenge 3:
We’re now back with the smartphone database. In the phone_book we have the columns id, first_name, last_name and phone.

Alias the first and last names and phone as “First Name”, “Last Name” and “Phone Number”.

Challenge 4:
In this sports team database there’s a results table with the columns of id, home_team, home_score, away_team, away_score and played_on.

Alias “Home Team”, “Home Score”, “Away Team”, “Away Score” and “Date Played” to the appropriate columns.

A

Challenge 1:
~~~
SELECT name AS “Product Name”, description AS “Product Description” FROM products;
~~~

Challenge 2:
~~~
SELECT username AS “Username”, first_name AS “First Name”, last_name AS “Last Name” FROM users;
~~~

Challenge 3:
~~~
SELECT first_name AS “First Name”, last_name AS “Last Name”, phone AS “Phone Number” FROM phone_book;
~~~

Challenge 4:
~~~
SELECT home_team AS “Home Team”, home_score AS “Home Score”, away_team AS “Away Team”, away_score AS “Away Score”, played_on AS “Date Played” FROM results;
~~~

Note: SELECT, FROM, AS all can be both lower or upper case, but to distinguish it from the other names we use Upper case as its industry best practice.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
10
Q

Explain the following SQL codes:

-- What are all the books authored by J.K. Rowling and what year were they first published?

--- SELECT <columns> FROM <table> WHERE <column> <operator> <value>;

SELECT title, author FROM books WHERE first_published = 1997;

SELECT title, author FROM books WHERE first_published = 1997 or first_published = 2003 ;

SELECT title, first_published FROM books WHERE author = "J.K. Rowling";

-- What books were not authored by J.K. Rowling?

--- SELECT <columns> FROM <table> WHERE <column> <operator> <value>;

SELECT title, author, first_published FROM books WHERE author != "J.K. Rowling";

-- What books were loaned on the 10th of December 2015?

SELECT book_id FROM loans WHERE loaned_on = "2015-12-10";

-- Which book is book 15?

SELECT title FROM books WHERE id = 15;

SELECT * FROM loans;

Note: = is case sensitive in SQL, in other coding languages instead of = they use ==.

CheatSheet:
~~~
— Syntax for finding or excluding exact matches
— SELECT <columns> FROM <table> WHERE <column> <operator> <value>;
SELECT title, author FROM books WHERE first_published = 1997;
SELECT title, first_published FROM books WHERE author = "J.K. Rowling";
SELECT title, author, first_published FROM books WHERE author != "J.K. Rowling";
SELECT book_id FROM loans WHERE loaned_on = "2015-12-10";
SELECT title FROM books WHERE id = 15;
~~~</value></operator></column></columns>

A

Certainly! Here’s a breakdown of the SQL codes with explanations included:

```sql
– What are all the books authored by J.K. Rowling and what year were they first published?

– SELECT <columns> FROM <table> WHERE <column> <operator> <value>;</value></operator></column></columns>

SELECT title, author FROM books WHERE first_published = 1997;
~~~
This code retrieves the titles and authors of books from the “books” table where the “first_published” column has a value of 1997. It will return all books authored by J.K. Rowling and published in 1997.

```sql
SELECT title, author FROM books WHERE first_published = 1997 or first_published = 2003 ;
~~~
This code is similar to the previous one, but it retrieves books that were first published either in 1997 or 2003. The “or” operator is used to combine multiple conditions.

```sql
SELECT title, first_published FROM books WHERE author = “J.K. Rowling”;
~~~
This code selects the title and first_published columns from the “books” table where the author is “J.K. Rowling”. It returns the titles and publication years of books authored by J.K. Rowling.

```sql
– What books were not authored by J.K. Rowling?

– SELECT <columns> FROM <table> WHERE <column> <operator> <value>;</value></operator></column></columns>

SELECT title, author, first_published FROM books WHERE author != “J.K. Rowling”;
~~~
This code selects the title, author, and first_published columns from the “books” table where the author is not equal to “J.K. Rowling”. The “!=” operator is used to denote inequality. It returns the books that were authored by someone other than J.K. Rowling.

```sql
– What books were loaned on the 10th of December 2015?

SELECT book_id FROM loans WHERE loaned_on = “2015-12-10”;
~~~
This code retrieves the book_id column from the “loans” table where the “loaned_on” column has a value of “2015-12-10”. It returns the book IDs of the books that were loaned on the 10th of December 2015.

```sql
– Which book is book 15?

SELECT title FROM books WHERE id = 15;
~~~
This code selects the title column from the “books” table where the “id” column has a value of 15. It returns the title of the book with the ID of 15.

```sql
SELECT * FROM loans;
~~~
This code selects all columns from the “loans” table. It retrieves all the loan records in the table, including information about the books loaned and the dates of the loans.

Note: In SQL, the equality operator is “=” and not “==”. The double equals sign (“==”) is typically used in programming languages like Python or JavaScript.

Treehouse Notes:
SQL Used
A WHERE Clause
~~~
SELECT <columns> FROM <table> WHERE <condition>;
~~~</condition></columns>

Equality Operator
Find all rows that a given value matches a column’s value.
~~~
SELECT <columns> FROM <table> WHERE <column> = <value>;
~~~</value></column></columns>

Examples:
~~~
SELECT * FROM contacts WHERE first_name = “Andrew”;
SELECT first_name, email FROM users WHERE last_name = “Chalkley”;
SELECT name AS “Product Name” FROM products WHERE stock_count = 0;
SELECT title “Book Title” FROM books WHERE year_published = 1999;
~~~

Inequality Operator
Find all rows that a given value doesn’t match a column’s value.
~~~
SELECT <columns> FROM <table> WHERE <column> != <value>;
SELECT <columns> FROM <table> WHERE <column> <> <value>;
~~~
The not equal to, or inequality operator, can be written in two ways != and <>. The latter is less common.</value></column></columns></value></column></columns>

Examples:
~~~
SELECT * FROM contacts WHERE first_name != “Kenneth”;
SELECT first_name, email FROM users WHERE last_name != “L:one”;
SELECT name AS “Product Name” FROM products WHERE stock_count != 0;
SELECT title “Book Title” FROM books WHERE year_published != 2015;
~~~
See all of the SQL used in SQL Basics in the SQL Basics Cheat Sheet.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
11
Q

Challenge 1: In our e-commerce database we have a users table with the columns id, username, password, first_name and last_name.

Write a SQL query that retrieves the first and last names only where the username is equal to “wig_lady”.

Challenge 2: In the products table we have the columns id, name, description and price.

Find all products that don’t have the price of 9.99. Include all columns.

Challenge 3: From the users table, find all the username fields with the last_name of “Chalkley”. Only return the usernames.

A

Challenge 1:
~~~
SELECT first_name, last_name FROM users WHERE username = “wig_lady”;
~~~

Challenge 2:
~~~
SELECT * FROM products WHERE price != 9.99;
~~~

Challenge 3:
~~~
SELECT username FROM users WHERE last_name = “Chalkley”;
~~~

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
12
Q

Explain the following code and also explain SQL operators:

--  What books are in the library that were first published after the year 2005?

SELECT * FROM books WHERE first_published >= "2005";
A

The given code is an SQL query that retrieves information from a table called “books” based on a specific condition. Let’s break it down step by step:

  1. SELECT *: This is the statement that indicates the query will retrieve all columns from the specified table.
  2. FROM books: This specifies the table name from which the data will be retrieved. In this case, the table is named “books”.
  3. WHERE first_published >= "2005": This is the condition applied to filter the rows in the result set. It specifies that only the rows where the value of the “first_published” column is greater than or equal to the year 2005 should be included in the result.

The code is querying the database to find all books in the library that were first published after the year 2005. It will return all the columns (denoted by “*”) from the “books” table where the “first_published” column has a value greater than or equal to “2005”.

SQL operators are used to perform various operations in SQL queries. Some common SQL operators include:

  1. Comparison Operators: These operators are used to compare values. Examples include:
    • = (equal to)
    • <> or != (not equal to)
    • < (less than)
    • > (greater than)
    • <= (less than or equal to)
    • >= (greater than or equal to)
  2. Logical Operators: These operators are used to combine conditions or negate them. Examples include:
    • AND (logical AND)
    • OR (logical OR)
    • NOT (logical NOT)
  3. Arithmetic Operators: These operators are used for mathematical calculations. Examples include:
    • + (addition)
    • - (subtraction)
    • * (multiplication)
    • / (division)
    • % (modulus)
  4. String Operators: These operators are used to manipulate strings. Examples include:
    • || (concatenation)
    • LIKE (pattern matching)

These operators allow you to perform a wide range of operations and conditions in SQL queries, enabling you to retrieve and manipulate data effectively.

Treehouse Notes:
Here are the relational operators as bullet points and the SQL code as code snippets with important words in bold:

Relational Operators:
- < less than
- <= less than or equal to
- > greater than
- >= greater than or equal to

SQL Used:
~~~
SELECT <columns> FROM <table> WHERE <column> < <value>;
SELECT <columns> FROM <table> WHERE <column> <= <value>;
SELECT <columns> FROM <table> WHERE <column> > <value>;
SELECT <columns> FROM <table> WHERE <column> >= <value>;
~~~</value></column></columns></value></column></columns></value></column></columns></value></column></columns>

Examples:

SELECT first_name, last_name FROM users WHERE date_of_birth < '1998-12-01';
SELECT title AS "Book Title", author AS Author FROM books WHERE year_released <= 2015;
SELECT name, description FROM products WHERE price > 9.99;
SELECT title FROM movies WHERE release_year >= 2000;

See all of the SQL used in SQL Basics in the SQL Basics Cheat Sheet.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
13
Q

Challenge 1: We have a database that runs a sports team’s website. In the results table we have the columns id, home_team, home_score, away_team, away_score, played_on.

Find all results where the home team’s score is above 12.

Challenge 2: We’re still using the sports team’s database. In the results table we have the columns id, home_team, home_score, away_team, away_score, played_on.

Find all results where the away team’s score is lower than 10.

Challenge 3: We’re back using the e-commerce database. I only have 10.99 left in my bank account. Write a query that will return all products from the products table that I can afford.

The columns in the products are id, name, description and price.

A

Challenge 1:
~~~
SELECT * FROM results WHERE home_score > 12;
~~~

Challenge 2:
~~~
SELECT * FROM results WHERE away_score < 10;
~~~

Challenge 3:
~~~
SELECT * FROM products WHERE price <= 10.99;
~~~

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
14
Q

Explain the following code:

-- SELECT <columns> FROM <table> WHERE <condition 1> AND/OR <condition 2>;

-- What books in our library were authored by J.K. Rowling before the year 2000?

SELECT title FROM books WHERE author = "J.K. Rowling" and first_published < "2000";

-- SELECT <columns> FROM <table> WHERE <condition 1> AND/OR <condition 2>;

-- What books were either authored by J.K. Rowling or published before thr year 2000?

SELECT title FROM books WHERE author = "J.K Rowling" OR first_published < "2000";

-- SELECT <columns> FROM <table> WHERE <condition 1> AND/OR <condition 2>;

-- What books do we have in the library authored by "Ernest Cline" or "Andy Weir"?

SELECT title, author FROM books WHERE author = "Ernest Cline" OR author = "Andy Weir";
A

The given code consists of multiple SQL queries with different conditions. Let’s break down each query step by step and explain its purpose:

  1. Query: What books in our library were authored by J.K. Rowling before the year 2000?
    sql
    SELECT title FROM books WHERE author = "J.K. Rowling" AND first_published < "2000";
    This query selects the “title” column from the “books” table. It specifies the condition that the author must be “J.K. Rowling” and the “first_published” year must be less than “2000”. The AND operator combines the two conditions, meaning both conditions must be true for a row to be included in the result set.
  2. Query: What books were either authored by J.K. Rowling or published before the year 2000?
    sql
    SELECT title FROM books WHERE author = "J.K Rowling" OR first_published < "2000";
    This query also selects the “title” column from the “books” table. It specifies two conditions. The first condition is that the author must be “J.K. Rowling”, and the second condition is that the “first_published” year must be less than “2000”. The OR operator combines the conditions, meaning a row will be included in the result set if either condition is true.
  3. Query: What books do we have in the library authored by “Ernest Cline” or “Andy Weir”?
    sql
    SELECT title, author FROM books WHERE author = "Ernest Cline" OR author = "Andy Weir";
    This query selects both the “title” and “author” columns from the “books” table. It specifies two conditions using the OR operator. It searches for rows where the author is either “Ernest Cline” or “Andy Weir”. If either condition is true, the row will be included in the result set.

In summary, these queries demonstrate the usage of conditions in SQL queries. They allow you to filter data based on specific criteria using logical operators such as AND and OR.

CHEATSHEETS:
~~~
– Syntact for multiple conditions
– SELECT <columns> FROM <table> WHERE <condition 1> AND/OR <condition 2>;</columns>

SELECT title FROM books WHERE author = “J.K. Rowling” AND first_published < 2000;
SELECT title FROM books WHERE author = “J.K. Rowling” OR first_published < 2000;
SELECT title FROM books WHERE author = “Ernest Cline” OR author = “Andy Weir”;
SELECT title FROM books WHERE author = “Ernest Cline” AND author = “Andy Weir”; – No results
~~~

Treehouse Notes:
SQL Used:
- You can compare multiple values in a WHERE condition. If you want to test that both conditions are true, use the AND keyword, or if you want to test that either condition is true, use the OR keyword.

```sql
SELECT <columns> FROM <table> WHERE <condition 1> AND <condition 2> ...;
SELECT <columns> FROM <table> WHERE <condition 1> OR <condition 2> ...;
~~~</columns></columns>

Examples:

```sql
SELECT username FROM users WHERE last_name = “Chalkley” AND first_name = “Andrew”;

SELECT * FROM products WHERE category = “Games Consoles” AND price < 400;

SELECT * FROM movies WHERE title = “The Matrix” OR title = “The Matrix Reloaded” OR title = “The Matrix Revolutions”;

SELECT country FROM countries WHERE population < 1000000 OR population > 100000000;
~~~

See all of the SQL used in SQL Basics in the SQL Basics Cheat Sheet.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
15
Q

Challenge 1: We’re back in the sports team database. There’s a results table with the columns id, home_team, home_score, away_team, away_score and played_on .

Find all the matches in the results table where “Hessle” was playing away as the away team and their score was above 18 points.

Challenge 2: Now we’re in the e-commerce database. In the users table we have the columns id, username, password, first_name and last_name.

Find all users with either the last name “Hinkley” or “Pettit”

A

Challenge 1:
~~~
SELECT * FROM results WHERE away_team = “Hessle” AND away_score > 18;
~~~

Challenge 2:
~~~
SELECT * FROM users WHERE last_name = “Hinkley” OR last_name = “Pettit”;
~~~

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
16
Q

Explain the following SQL codes:

1:
~~~
– SELECT * FROM <table> WHERE <column> <operator> <value>;</value></operator></column>

– What are all the loans that happened before December 13th 2015?

SELECT * FROM loans WHERE loaned_on < “2015-12-13”;
~~~

2:
~~~
– SELECT * FROM <table> WHERE <column> <operator> <value>;</value></operator></column>

– Imagine today is December 18th 2015. Which books are due back soon?

SELECT * FROM loans WHERE return_by > “2015-12-18”;

– Which users have the id of 1 or 3?

SELECT first_name, email FROM patrons WHERE id = 1 OR id = 3;
~~~

A

1:
The SQL code is querying a table named “loans” to retrieve all the rows (represented by *) where the value in the “loaned_on” column is earlier (before) than the date “2015-12-13”. This code is used to find all the loans that occurred prior to December 13th, 2015.

2:
The first part of the code is querying a table named “loans” to retrieve all the rows (*) where the value in the “return_by” column is greater (later) than the date “2015-12-18”. This code is used to find books that are due back soon, assuming the current date is December 18th, 2015.

The second part of the code is querying a table named “patrons” to retrieve the values in the “first_name” and “email” columns. It selects only the rows where the value in the “id” column is either 1 or 3. This code is used to find the first names and email addresses of the users who have the ID of 1 or 3.

Cheatsheet:
~~~
– Syntax for using conidtions
– SELECT * FROM <table> WHERE <column> <operator> <value>;
-- SELECT * FROM <table> WHERE <condition 1> OR <condition 2>;</value></operator></column>

SELECT * FROM loans WHERE loaned_on < “2015-12-13”;
SELECT * FROM loans WHERE return_by > “2015-12-18”;
SELECT first_name, email FROM patrons WHERE id = 1 OR id = 3;
~~~

Treehouse Notes:

Certainly! Here are the points with the code highlighted:

Relational Operators

There are several relational operators you can use:

  • < less than
  • <= less than or equal to
  • > greater than
  • >= greater than or equal to

These are primarily used to compare numeric and date/time types.

Code Examples:

SELECT <columns> FROM <table> WHERE <column name> < <value>; SELECT <columns> FROM <table> WHERE <column name> <= <value>; SELECT <columns> FROM <table> WHERE <column name> > <value>; SELECT <columns> FROM <table> WHERE <column name> >= <value>;

Examples:

SELECT first_name, last_name FROM users WHERE date_of_birth < '1998-12-01'; SELECT title AS "Book Title", author AS Author FROM books WHERE year_released <= 2015; SELECT name, description FROM products WHERE price > 9.99; SELECT title FROM movies WHERE release_year >= 2000;

17
Q

Challenge: We’re back in the sports team database. There’s a results table with the columns id, home_team, home_score, away_team, away_score and played_on .

Find all the matches in the results table where “Hessle” was playing away as the away team and if they played on or after October 1st 2015. Date format is “YYYY-MM-DD”.

A

Answer to Challenge:
~~~
SELECT * FROM results WHERE away_team = “Hessle” AND played_on >= “2015-10-01”;
~~~

18
Q

Explain the following SQL Codes:

1:
~~~
– Who are the people with the Library IDs of MCL1001, MCL1100 or MCL1011?

– SELECT <columns> FROM <table> WHERE <condition 1> OR <condition 2> OR <condition 3>;</columns>

SELECT first_name, email FROM patrons WHERE library_id = “MCL1001” OR library_id = “MCL1100” OR library_id = “MCL1011”;
~~~

2:
~~~
– Who are the people with the Library IDs of MCL1001, MCL1100 or MCL1011?

– SELECT <columns> FROM <table> WHERE <column> IN (<value 1>, <value 2>, <value …>);</column></columns>

SELECT first_name, email FROM patrons WHERE library_id IN (“MCL1001”, “MCL1100”, “MCL1011”);
~~~

A

1:
The SQL code is querying a table named “patrons” to retrieve the values in the “first_name” and “email” columns. It selects only the rows where the value in the “library_id” column is either “MCL1001”, “MCL1100”, or “MCL1011”. This code is used to find the people with the Library IDs of MCL1001, MCL1100, or MCL1011.

2:
The SQL code is also querying a table named “patrons” to retrieve the values in the “first_name” and “email” columns. It selects only the rows where the value in the “library_id” column is in a specified list of values: “MCL1001”, “MCL1100”, and “MCL1011”. This code achieves the same result as the first example, finding the people with the Library IDs of MCL1001, MCL1100, or MCL1011. However, it uses the “IN” operator to specify the list of values instead of using multiple “OR” conditions.

Treehouse Notes:
Here are the points with the code examples enclosed as code:

  • SQL Used: **SELECT <columns> FROM <table> WHERE <column> IN (<value 1>, <value 2>, ...);**</column></columns>

Examples:
```sql
SELECT name FROM islands WHERE id IN (4, 8, 15, 16, 23, 42);

sql
SELECT * FROM products WHERE category IN (“eBooks”, “Books”, “Comics”);

sql
SELECT title FROM courses WHERE topic IN (“JavaScript”, “Databases”, “CSS”);

sql
SELECT * FROM campaigns WHERE medium IN (“email”, “blog”, “ppc”);
~~~

  • To find all rows that are not in the set of values, you can use NOT IN.

**SELECT <columns> FROM <table> WHERE <column> NOT IN (<value 1>, <value 2>, ...);**</column></columns>

Examples:
```sql
SELECT answer FROM answers WHERE id IN (7, 42);

sql
SELECT * FROM products WHERE category NOT IN (“Electronics”);

sql
SELECT title FROM courses WHERE topic NOT IN (“SQL”, “NoSQL”);
~~~

You can find more SQL examples and information in the SQL Basics Cheat Sheet.

19
Q

Challenge 1: We have an e-commerce database. Inside the products table we have the columns of id, name, description and price.

Without using the OR keyword, find all products with the price of 7.99, 9.99 or 11.99.

Challenge 2:
We have an e-commerce database. Inside the users table we have the columns of id, username, password, first_name and last_name.

Without using the OR keyword, find all the users with the username of “2spooky4me” or “beard_man”.

A

Answer to Challenge 1:
~~~
SELECT * FROM products WHERE price IN (“7.99”,”9.99”,”11.99”);
~~~

Answer to Challenge 2:
~~~
SELECT * FROM users WHERE username IN (“2spooky4me”, “beard_man”);
~~~

20
Q

Explain the following SQL Codes:

1:
~~~
— What are the book in the library from the 19th century?

SELECT title, author FROM books WHERE first_published >= 1800 AND first_published <= 1899;
~~~

2:
~~~
– SELECT <columns> FROM <table> WHERE <column> BETWEEN <value 1> AND <value 2>;</column></columns>

— What are the book in the library from the 19th century?

SELECT title, author FROM books WHERE first_published BETWEEN 1800 AND 1899;
~~~

3:
~~~
– SELECT <columns> FROM <table> WHERE <column> BETWEEN <value 1> AND <value 2>;</column></columns>

– What are the loans from week commencing Sunday 13th December 2015?

SELECT * FROM loans WHERE loaned_on BETWEEN “2015-12-13” AND “2015-12-19”;
~~~

A

1:
The SQL code is querying a table named “books” to retrieve the values in the “title” and “author” columns. It selects only the rows where the value in the “first_published” column is greater than or equal to 1800 and less than or equal to 1899. This code is used to find the books in the library that were first published in the 19th century.

2:
The SQL code is also querying a table named “books” to retrieve the values in the “title” and “author” columns. It uses the “BETWEEN” operator to specify a range of values for the “first_published” column. In this case, it selects only the rows where the value in the “first_published” column is between 1800 and 1899 (inclusive). This code achieves the same result as the first example, finding the books in the library that were first published in the 19th century.

3:
The SQL code is querying a table named “loans” to retrieve all the rows (*) where the value in the “loaned_on” column is between “2015-12-13” and “2015-12-19” (inclusive). This code is used to find the loans that occurred during the week commencing Sunday, December 13th, 2015. The “BETWEEN” operator is used to specify a range of values for the date.

Cheatsheet:
~~~
– Syntax for ranges
– SELECT <columns> FROM <table> WHERE <column> BETWEEN <value 1> AND <value 2>;</column></columns>

SELECT title, author FROM books WHERE first_published >= 1800 AND first_published <= 1899;
SELECT title, author FROM books WHERE first_published BETWEEN 1800 AND 1899;
SELECT * FROM loans WHERE loaned_on BETWEEN “2015-12-13” AND “2015-12-19”;
~~~

Treehouse Notes:
SQL Used
~~~
SELECT <columns> FROM <table> WHERE <column> BETWEEN <lesser> AND <greater>;
~~~</greater></lesser></column></columns>

Examples:
~~~
SELECT * FROM movies WHERE release_year BETWEEN 2000 AND 2010;
SELECT name, description FROM products WHERE price BETWEEN 9.99 AND 19.99;
SELECT name, appointment_date FROM appointments WHERE appointment_date BETWEEN “2015-01-01” AND “2015-01-07”;
~~~
See all of the SQL used in SQL Basics in the SQL Basics Cheat Sheet.

21
Q

Challenge 1: In the e-commerce database we have the products table with the columns id, name, description and price.

Find all the products in the database with the price including and between 10.99 and 12.99.

Challenge 2: We’re back in our sports team database with the results table. The columns are id, home_team, home_score, away_team, away_score and played_on.

There are 30 days in September. Find all the games played in the results table in September 2015.

A

Answer to Challenge 1:
~~~
SELECT * FROM products WHERE price BETWEEN “10.99” AND “12.99”;
~~~

Answer to Challenge 2:
~~~
SELECT * FROM results WHERE played_on BETWEEN “2015-09-01” AND “2015-09-30”;
~~~

22
Q

Explain the following codes:

1:
~~~
– What are all Harry Potter books in the library?

SELECT title FROM books WHERE title = “Harry Potter”;
– 0 results

SELECT title FROM books WHERE title LIKE “Harry Potter”;
– 0 results

SELECT title FROM books WHERE title LIKE “Harry Potter%”;
– 7 results
~~~

2:
~~~
– Is the book by Andy Weir called “The Martian” or “Martian”?

SELECT title FROM books WHERE title LIKE “%Martian”;
~~~

3:
~~~
– What non fiction books do we have with the “universe” anywhere in the title?

SELECT title FROM books WHERE title LIKE “%universe%” AND genre = “Non Fiction”;
~~~

A

1:

In this code snippet, there are three SQL queries executed to retrieve information about Harry Potter books in a library.

The first query SELECT title FROM books WHERE title = "Harry Potter"; attempts to find books with the exact title “Harry Potter.” However, it returns 0 results, indicating that there are no books with an exact title match for “Harry Potter.”

The second query SELECT title FROM books WHERE title LIKE "Harry Potter"; uses the LIKE operator with a pattern “Harry Potter.” However, it also returns 0 results because the pattern doesn’t match any book titles exactly.

The third query SELECT title FROM books WHERE title LIKE "Harry Potter%"; uses the LIKE operator with a pattern “Harry Potter%.” The % symbol is a wildcard that matches any sequence of characters. This query returns 7 results, indicating that there are seven books with titles that start with “Harry Potter” followed by any additional characters.

2:

This code snippet contains a single SQL query that aims to determine the title of a book written by Andy Weir. The query is as follows: SELECT title FROM books WHERE title LIKE "%Martian";

The LIKE operator is used with the pattern “%Martian.” The % symbol at the beginning of the pattern is a wildcard that matches any sequence of characters before the word “Martian.” This query will retrieve books whose titles end with “Martian” preceded by any characters. It allows for variations like “The Martian” or “Some Other Book - Martian.” The result will include any book title that ends with “Martian.”

3:

This code snippet presents a SQL query that seeks non-fiction books in the library with the word “universe” anywhere in their titles. The query is as follows: SELECT title FROM books WHERE title LIKE "%universe%" AND genre = "Non Fiction";

The LIKE operator is used with the pattern “%universe%.” The % symbol at the beginning and end of the pattern is a wildcard that matches any sequence of characters before and after the word “universe.” This query will retrieve books whose titles contain “universe” regardless of its position within the title.

Additionally, the query includes the condition AND genre = "Non Fiction"; to filter the results further. It ensures that only books with the genre “Non Fiction” are included in the final result set.

Cheatsheet:
~~~
– Syntax for searching with patterns
– SELECT <columns> FROM <table> WHERE <column> LIKE "<pattern>";
-- % is the wildcard for patterns</pattern></column></columns>

SELECT title FROM books WHERE title LIKE “Harry Potter%”;
SELECT title FROM books WHERE title LIKE “%Martian”;
SELECT title FROM books WHERE title LIKE “%universe%” AND genre = “Non Fiction”;
SELECT title FROM books WHERE title LIKE “%universe%” AND genre LIKE “non fiction”;
~~~

Treehouse Notes:
SQL Used
Placing the percent symbol (%) any where in a string in conjunction with the LIKE keyword will operate as a wildcard. Meaning it can be substituted by any number of characters, including zero!
~~~
SELECT <columns> FROM <table> WHERE <column> LIKE <pattern>;
~~~</pattern></column></columns>

Examples:
~~~
SELECT title FROM books WHERE title LIKE “Harry Potter%Fire”;
SELECT title FROM movies WHERE title LIKE “Alien%”;
SELECT * FROM contacts WHERE first_name LIKE “%drew”;
SELECT * FROM books WHERE title LIKE “%Brief History%”;
~~~

PostgreSQL Specific Keywords:
LIKE in PostgreSQL is case-sensitive. To case-insensitive searches do ILIKE.
~~~
SELECT * FROM contacts WHERE first_name ILIKE “%drew”;
~~~

23
Q

Challenge 1: In the e-commerce database we have a products table. The columns are id, name, description and price.

Find all the products where the pattern ‘t-shirt’ can be found anywhere in the product name.

Challenge 2: In the users table we have the columns id, username, password, first_name and last_name.

Find all users with the first name starting with the letter “L”.

A

Answer to Challenge 1:
~~~
SELECT * FROM products WHERE name LIKE “%t-shirt%”;
~~~

Answer to Challenge 2:
~~~
SELECT * FROM users WHERE first_name LIKE “L%”;
~~~

NOTE: the “” within LIKE keyword is not case sensitive.

24
Q

Explain the following codes:

1:
~~~
— What are the loans that are due back after December 18th 2015?

SELECT * FROM loans WHERE return_by > “2015-12-18” AND returned_on IS NULL;
~~~

2:
~~~
— What are the loans that have been returned already?

SELECT * FROM loans WHERE return_by > “2015-12-18” AND returned_on IS NOT NULL;

– Who is user 4?

SELECT first_name, email FROM patrons WHERE id = 4;
~~~

A

1:

The code snippet consists of a single SQL query that retrieves information about loans that are due back after December 18th, 2015. Here’s a breakdown of the query:

SELECT * FROM loans WHERE return_by > "2015-12-18" AND returned_on IS NULL;

The SELECT * statement is used to select all columns from the “loans” table. You can modify this to specify specific columns if needed, such as SELECT loan_id, borrower_id, due_date, etc.

The FROM loans clause specifies the table from which the data is being retrieved, in this case, the “loans” table.

The WHERE return_by > "2015-12-18" AND returned_on IS NULL clause filters the results based on two conditions. Firstly, return_by > "2015-12-18" checks if the "return_by" column, which represents the due date for returning the loan, is greater than December 18th, 2015. This ensures that only loans due after that date are included in the result set. Secondly, returned_on IS NULL ensures that only loans that have not been returned yet are considered. If the "returned_on" column is NULL, it means the book hasn’t been returned.

Overall, this query will return the details of loans that have a due date after December 18th, 2015 and have not been returned yet.

2:

This code snippet consists of two separate SQL queries. The first query retrieves information about loans that have already been returned, while the second query retrieves information about a specific user with the ID 4.

SELECT * FROM loans WHERE return_by > "2015-12-18" AND returned_on IS NOT NULL;

The first query uses the SELECT * statement to select all columns from the “loans” table.

The WHERE return_by > "2015-12-18" AND returned_on IS NOT NULL clause filters the results based on two conditions. Firstly, return_by > "2015-12-18" checks if the "return_by" column, representing the due date, is greater than December 18th, 2015. This ensures that only loans with a due date after that date are considered. Secondly, returned_on IS NOT NULL checks if the "returned_on" column, which indicates the date the loan was returned, is not NULL. This condition ensures that only loans that have been returned are included in the result set.

The second query is as follows:

SELECT first_name, email FROM patrons WHERE id = 4;

This query retrieves the first name and email of a specific user with the ID 4 from the “patrons” table.

The SELECT first_name, email statement specifies the columns to be selected from the table.

The FROM patrons clause specifies the table from which the data is being retrieved, in this case, the “patrons” table.

The WHERE id = 4 clause filters the results based on the condition that the ID column equals 4. This retrieves the details of the user with the ID 4, including their first name and email.

25
Q

Challenge 1: We’re back on the smartphone, but our phone_book is a mess. There’s a phone_book table but there’s missing information in a couple of the columns.

The phone_book has the following columns id, first_name, last_name and phone.

Find all contacts in the phone_book where the phone number is missing so we can go and ask them for their number.

Challenge 2: We’re still using the phone_book, with the columns id, first_name, last_name and phone.

Imagine we’re implementing the autocomplete feature for a search facility on the phone where a user can start typing a last name and suggestions will appear. Write a query to retrieve all values from the last name column where the last name value is present. Only retrieve the last_name column.

A

Answer to Challenge 1:
~~~
SELECT * FROM phone_book WHERE phone is NULL;
~~~

Answer to Challenge 2:
~~~
SELECT last_name FROM phone_book WHERE last_name IS NOT NULL;
~~~

26
Q

Explain the following code and its syntax:

SELECT * FROM loans, books WHERE loans.book_id = books.id;
A

The given code is an SQL query written in the syntax of the SQL programming language. It retrieves data from two tables, loans and books, based on a condition. Let’s break down the code and its syntax step by step:

  1. SELECT *: This is the select statement in SQL, used to specify the columns or data you want to retrieve from the tables. In this case, * is a wildcard character that means “all columns.”
  2. FROM loans, books: This specifies the tables from which you want to retrieve data. In this case, you want to retrieve data from the loans and books tables.
  3. WHERE loans.book_id = books.id: This is the condition that determines how the two tables are joined together. It uses the WHERE clause to specify the condition. In this case, the condition is that the book_id column in the loans table must match the id column in the books table.

Overall, this query is retrieving all columns from the loans and books tables where there is a matching book_id and id between the two tables. It effectively combines the loan information with the corresponding book information based on the matching IDs.