Week 2 Topic 3: Create tables with SQL and insert data

Choose a study mode

Play Quiz
Study Flashcards
Spaced Repetition
Chat to Lesson

Podcast

Play an AI-generated podcast conversation about this lesson
Download our mobile app to listen on the go
Get App

Questions and Answers

Which SQL statement is used to create a new table in a database?

  • CREATE TABLE (correct)
  • MAKE TABLE
  • INSERT TABLE
  • NEW TABLE

What is the purpose of the DROP TABLE command in SQL?

  • To create a backup of a table.
  • To delete a table from the database. (correct)
  • To modify the structure of an existing table.
  • To remove all data from a table.

Which SQL keyword is used to add data into a table?

  • ADD INTO
  • CREATE
  • INSERT INTO (correct)
  • UPDATE

What is the purpose of the SELECT command in SQL?

<p>To retrieve data from a table. (A)</p> Signup and view all the answers

Which SQL operator is used to filter rows based on a pattern?

<p>LIKE (C)</p> Signup and view all the answers

What is the function of the SQL ORDER BY clause?

<p>To sort the result set. (C)</p> Signup and view all the answers

Which keyword is used to rename a column in a SQL query result?

<p>AS (C)</p> Signup and view all the answers

What is the purpose of the LIMIT clause in SQL?

<p>To restrict the number of rows returned by a query. (D)</p> Signup and view all the answers

Which SQL aggregate function returns the average value of a numeric column?

<p>AVG() (A)</p> Signup and view all the answers

Which SQL clause is used to group rows that have the same values in a specified column?

<p>GROUP BY (A)</p> Signup and view all the answers

What is the purpose of the HAVING clause in SQL?

<p>To filter groups based on a condition. (B)</p> Signup and view all the answers

What is a 'view' in SQL?

<p>A saved query. (C)</p> Signup and view all the answers

When creating a table with a foreign key, what must be ensured regarding the data type of the foreign key column?

<p>It must match the data type of the primary key in the related table. (A)</p> Signup and view all the answers

If you want to retrieve all columns from a table named 'Employees', which SQL statement would you use?

<p>SELECT * FROM Employees; (B)</p> Signup and view all the answers

Which of the following SQL statements is correctly formatted to insert a new customer into the Customer table with columns (CustomerID, FirstName, LastName, Phone)?

<p>INSERT INTO Customer VALUES (1, 'John', 'Doe', '123-456-7890'); (C)</p> Signup and view all the answers

You want to select all customers from the 'Customer' table who live in 'New York'. Which SQL statement would you use?

<p>SELECT * FROM Customer WHERE City = 'New York'; (B)</p> Signup and view all the answers

Which of the following is a valid use case for the OFFSET clause in SQL?

<p>To define the starting point for retrieving rows in pagination. (B)</p> Signup and view all the answers

In SQL, which operator is used to check if a value falls within a specified range?

<p>BETWEEN (A)</p> Signup and view all the answers

What will the following SQL statement return: SELECT COUNT(*) FROM Orders WHERE CustomerID IS NULL;?

<p>The number of orders where the CustomerID is NULL. (C)</p> Signup and view all the answers

Given a table Products with columns Price and Category, which SQL statement would find the average price for each category?

<p>SELECT Category, AVG(Price) FROM Products GROUP BY Category; (C)</p> Signup and view all the answers

What is the critical difference between the WHERE and HAVING clauses in SQL?

<p><code>WHERE</code> is used for filtering individual row values, while <code>HAVING</code> is used for filtering on aggregate functions or groups. (C)</p> Signup and view all the answers

What is the purpose of the wildcard character '%' in a SQL LIKE clause?

<p>Matches zero or more characters. (D)</p> Signup and view all the answers

Given a table Employees with columns Salary and Department, how would you select the department with the highest average salary?

<p>SELECT Department FROM Employees GROUP BY Department ORDER BY AVG(Salary) DESC LIMIT 1; (D)</p> Signup and view all the answers

You have a table named Products with columns name, category, and price. Write an SQL query to create a view named ExpensiveFood that selects the names and prices of products that belong to the 'Food' category and have a price greater than $50. The view should include columns named Product_Name and Product_Price.

<p><code>CREATE VIEW ExpensiveFood AS SELECT name AS Product_Name, price AS Product_Price FROM Products WHERE category = 'Food' AND price &gt; 50;</code> (C)</p> Signup and view all the answers

What potentially unintended consequence should be carefully considered when using COUNT(*) instead of COUNT(column_name) in SQL, especially on tables permitting NULL values?

<p><code>COUNT(*)</code> may include rows with <code>NULL</code> values in the count, leading to an overestimation of non-null entries in a specific column. (A)</p> Signup and view all the answers

In a scenario where you need to optimize query performance on a very large table, what would be the most effective approach to improve the speed of data retrieval when using WHERE clauses with frequently queried columns?

<p>Create indexes on the frequently queried columns in the <code>WHERE</code> clauses. (D)</p> Signup and view all the answers

Consider a Products table with columns ID, Name, Category, and Price. Write an SQL query to find the second most expensive product in each category. Assume that there are at least two products in each category.

<pre><code class="language-SQL">SELECT p1.Category, p1.Name, p1.Price FROM Products p1 WHERE 1 = (SELECT COUNT(DISTINCT p2.Price) FROM Products p2 WHERE p2.Category = p1.Category AND p2.Price &gt; p1.Price); ``` (D) </code></pre> Signup and view all the answers

Given two tables, Customers (CustomerID, Name) and Orders (OrderID, CustomerID, OrderDate), write an SQL query to find customers who have placed orders on every single day that any order was placed across the entire system. This requires identifying customers who have an entry in the Orders table for each distinct OrderDate that exists in that table.

<p>All of the above are correct. (D)</p> Signup and view all the answers

Given the table 'Product' with fields (ProductID, ProductName, Price, CategoryID), and the table 'Category' with fields (CategoryID, CategoryName), what would be the most efficient SQL query to retrieve a list of all categories and the average product price in each, but only for categories where the maximum product price is greater than $100?

<pre><code class="language-sql">SELECT c.CategoryName, AVG(p.Price) FROM Product p JOIN Category c ON p.CategoryID = c.CategoryID GROUP BY c.CategoryName HAVING MAX(p.Price) &gt; 100; ``` (D) </code></pre> Signup and view all the answers

Flashcards

SQL (Structured Query Language)

A standard programming language used for managing and manipulating databases.

CREATE TABLE

SQL command used to create a new table in a database.

Data Type

Specifies the type of data a column can hold (e.g., INTEGER, TEXT).

Foreign Key

A field in one table that refers to the primary key in another table.

Signup and view all the flashcards

Primary Key

A column (or set of columns) that uniquely identifies each row in a table.

Signup and view all the flashcards

DROP TABLE

SQL command used to remove an existing table from a database.

Signup and view all the flashcards

INSERT INTO

SQL command used to insert new data into a table.

Signup and view all the flashcards

SELECT

SQL command used to retrieve data from a database.

Signup and view all the flashcards

% wildcard

A wildcard that matches zero or more characters in a LIKE operator.

Signup and view all the flashcards

_ wildcard

A wildcard that matches exactly one character in a LIKE operator.

Signup and view all the flashcards

IN Operator

SQL operator used to check if a value is in a list of values.

Signup and view all the flashcards

ORDER BY

SQL keyword used to sort the result set of a query.

Signup and view all the flashcards

ASC (Ascending)

Specifies sorted order from smallest to largest.

Signup and view all the flashcards

DESC (Descending)

Specifies sorted order from largest to smallest.

Signup and view all the flashcards

AS (Alias)

SQL keyword used to rename a column in the result set.

Signup and view all the flashcards

LIMIT

SQL clause used to limit the number of rows returned by a query.

Signup and view all the flashcards

OFFSET

SQL clause used to skip a specified number of rows before returning data.

Signup and view all the flashcards

Aggregate Functions

Functions that operate on multiple rows and return a single value.

Signup and view all the flashcards

COUNT()

Aggregate function that returns the number of rows in a table.

Signup and view all the flashcards

SUM()

Aggregate function that calculates the sum of values in a column.

Signup and view all the flashcards

AVG()

Aggregate function that computes the average value of a column.

Signup and view all the flashcards

MIN()

Aggregate function that returns the smallest value in a column.

Signup and view all the flashcards

MAX()

Aggregate function that returns the largest value in a column.

Signup and view all the flashcards

GROUP BY

SQL keyword used to group rows with the same values into summary rows.

Signup and view all the flashcards

HAVING

SQL clause used to filter the results of aggregate functions.

Signup and view all the flashcards

VIEW

A saved query that works like a regular table, but cannot be edited.

Signup and view all the flashcards

CREATE VIEW

SQL command used to create a view.

Signup and view all the flashcards

Study Notes

  • SQL (Structured Query Language) is a standard programming language used to create tables in relational databases.
  • Many relational databases support basic SQL operations, but some software may have extra features or slight command differences.

CREATE TABLE Syntax

  • The CREATE TABLE syntax creates a new table in a database.
  • It defines the table's structure, including column names, data types, constraints, and indexes.
  • Syntax:
CREATE TABLE table_name (
    column1 datatype [ constraint ],
    column2 datatype [ constraint ],...
    columnN datatype [ constraint ]
);
  • Example: Creating a Customer table:
CREATE TABLE Customer (
   CustomerID INTEGER ,
   FirstName TEXT ,
   LastName TEXT ,
   Address TEXT ,
   Phone TEXT , PRIMARY KEY (CustomerID)
);
  • When creating a table with a foreign key, ensure the data type matches the primary key in the related table.
  • If a table name is a reserved keyword (e.g., ORDER), use an alternative name (e.g., Orders).
  • For tables with multiple primary keys, list all primary keys separated by a comma e.g. PRIMARY KEY (OrderID, ProductID)
  • To delete a table, use the command: DROP TABLE MyCoolTable;

INSERT INTO Syntax

  • The INSERT INTO command inserts data into a table.
  • Syntax: INSERT INTO MyTable (MyFirstCol, MySecondCol) VALUES (value1, value2);
  • Example: Inserting data into the Customer table:
INSERT INTO Customer VALUES ( 1 , 'Fred' , 'Banks' , '3134 Hudson Lane' , '405195595' );
INSERT INTO Customer VALUES ( 2 , 'Nicholas' , 'Ramos' , '9 Washington Center' , '946151556' );
INSERT INTO Customer VALUES ( 3 , 'Anne' , 'Hansen' , '8604 Burrows Pass' , '129895116' );
INSERT INTO Customer VALUES ( 4 , 'Douglas' , 'Mendoza' , '9 Monument Avenue' , '898719584' );
INSERT INTO Customer VALUES ( 5 , 'Bonnie' , 'Lawson' , '9 Oneill Avenue' , '887514739' );
INSERT INTO Customer VALUES ( 6 , 'Elizabeth' , 'Ryan' , '1289 Del Mar Street' , '887514733' );

SELECT Command

  • SELECT retrieves data from the database.
  • SELECT * FROM TableName; selects all data from a table.
  • To select specific columns, list the column names after the SELECT command such as SELECT FirstName, Address FROM Customer;

WHERE Keyword

  • Filters rows based on a condition.
  • Only shows rows where the expression is true.
  • SELECT * FROM Customer WHERE LastName = 'Wood'; only selects customers with the last name 'Wood'.
  • Mathematical operations can be used in the WHERE clause such as SELECT * FROM Customer WHERE CustomerID > 2;

LIKE Operator

  • Checks if text matches a pattern.
  • % matches zero or more characters.
  • _ matches exactly one character.

IN Operator

  • Checks if a value is in a list of possible values.
  • SELECT * FROM Customer WHERE CustomerID IN (2,3,4); selects customers with CustomerID 2, 3, or 4.

ORDER BY Keyword

  • Displays results in a specific order.
  • ASC: ascending order (default).
  • DESC: descending order.

AS (Alias) Keyword

  • Renames a column.
  • SELECT FirstName AS FN, LastName AS LN FROM Customer; renames FirstName to FN and LastName to LN in the output.

LIMIT and OFFSET Clauses

  • Restrict the number of rows returned by a SELECT statement.
  • LIMIT determines the number of rows returned.
  • OFFSET skips a specified number of rows before returning data.
  • Often used with ORDER BY.

Aggregate Functions

  • Aggregate functions work over multiple rows and combine them.
  • COUNT(): Counts all the values.
  • SUM(): Adds all the values together.
  • AVG(): Computes the average.
  • MIN(): Gets the lowest value.
  • MAX(): Gets the highest value.

Aggregate - COUNT()

  • COUNT() returns the number of rows in the table.
  • It always returns a single row unless GROUP BY is used.
  • SELECT COUNT (ProductID) FROM Product; returns the number of products.
  • COUNT(1) or COUNT(*) counts the number of rows.
  • COUNT(ProductID) counts rows where ProductID is not null.

Aggregate - AVG(), MIN(), MAX()

  • Example:
SELECT AVG(Price), MIN(Price), Max(Price)
FROM Product;

GROUP BY Keyword

  • Used to determine the aggregate price per brand.
  • SELECT AVG(Price), BrandID FROM Product GROUP BY BrandID;

WHERE Clause (with Aggregate Functions)

  • The WHERE clause is processed before aggregate functions.
  • Rows are filtered based on the WHERE clause condition before aggregates are applied.
  • Aggregates cannot be used in a WHERE clause.

HAVING Clause

  • Similar to WHERE, but it occurs after the aggregates have finished.
  • SELECT ProductID,AVG(Price) FROM Product WHERE BrandID < 3 GROUP BY ProductID;
  • Only shows brands that have an average price of over $20.

VIEW

  • A saved query that works like a regular table, but the rows cannot be edited.
  • Useful for large and complex queries.
  • CREATE VIEW MyCoolView AS SELECT*FROM Mycool table; creates a view named MyCoolView.
  • Example: Creating a view to show the number of orders per CustomerID:
CREATE VIEW OrdersPerCustomer AS
 SELECT CustomerID,COUNT(OrderID)AS OrderCount 
FROM Orders GROUP BY CustomerID;
  • After creating a VIEW, it can be used as a standard table, but the rows cannot be changed.
  • SELECT * FROM OrdersPerCustomer;

Studying That Suits You

Use AI to generate personalized quizzes and flashcards to suit your learning preferences.

Quiz Team

More Like This

SQL CREATE TABLE Quiz
6 questions

SQL CREATE TABLE Quiz

SpectacularPrairie avatar
SpectacularPrairie
SQL Basics
6 questions

SQL Basics

ResponsiveMoose avatar
ResponsiveMoose
SQL CREATE TABLE Commands
44 questions
Use Quizgecko on...
Browser
Browser