Sql queries: Difference between revisions

From wikinotes
 
(18 intermediate revisions by the same user not shown)
Line 3: Line 3:
<blockquote>
<blockquote>
<syntaxhighlight lang="MySQL">
<syntaxhighlight lang="MySQL">
SELECT *
SELECT *                   # select all rows
FROM  users
FROM  users               # from users table
WHERE username = "dvader"
WHERE username = "dvader" # where the 'username' column value is 'dvader'
AND  age > 40;
AND  age > 40;           # and the 'age' column value is above 40
</syntaxhighlight>
</syntaxhighlight>
</blockquote><!-- Example -->
</blockquote><!-- Example -->
Line 12: Line 12:
= Query Components =
= Query Components =
<blockquote>
<blockquote>
== SELECT ==
SELECT which columns you'd like to see, and how you'd like them to be presented (order, max results, etc).
<blockquote>
Determines what columns you want to return.
 
<syntaxhighlight lang="MySQL">
<syntaxhighlight lang="MySQL">
SELECT *           # select all columns
SELECT *                               # select all columns
SELECT col1, col2  # select col1, and col2 only
SELECT name, age FROM users;          # select name, and age only
SELECT col1 AS foo  # rename column in results table
SELECT name AS userame FROM users;    # rename column in results table
SELECT DISTINCT name FROM users;      # select 1x row for each unique name in users
SELECT * FROM users LIMIT 10;          # only select first 10 results
SELECT * FROM users ORDER BY name ASC  # sort results in ascending order by name
</syntaxhighlight>
</syntaxhighlight>


=== DISTINCT ===
After your selection you may:
* use [[sql joins]] to associate the queried table's data to other tables.<br>''(ex: find users assigned to a project)''<br><br>
* use [[sql aggregate functions]] to operate on groups of rows<br>''(ex: find average age of users in users table)''<br><br>
* use [[sql comparison operators]] in your <code>WHERE</code> statement to determine what you want to select.<br>''(ex: find users whose name starts with an 'A')''
 
</blockquote><!-- Query Components -->
 
= Techniques =
<blockquote>
<blockquote>
Distinct only returns one result per unique value of N
== Nested Queries ==
<syntaxhighlight lang="MySQL">
SELECT DISTINCT username FROM  users WHERE last_name = "skywalker";
</syntaxhighlight>
</blockquote><!-- DISTINCT -->
 
=== CONCAT ===
<blockquote>
<blockquote>
CONCAT lets you combine columns into one
You can nest SQL queries and treat them as tables.
<syntaxhighlight lang="MySQL">
SELECT CONCAT(first_name, " ", last_name) AS fullname FROM users;
</syntaxhighlight>
</blockquote><!-- CONCAT -->


=== SUBSTRING_INDEX ===
The example below finds <code>users.id</code> values<br>
<blockquote>
that are not present in the many:many <code>user_departments</code> table,<br>
SUBSTRING_INDEX lets you split/tokenize a string
by joining a user table query to itself.
<syntaxhighlight lang="mySQL">
SELECT SUBSTRING_INDEX('www.mysql.com', '.', 2)
##> www.mysql
</syntaxhighlight>
</blockquote><!-- SUBSTRING_INDEX -->


=== LIMIT ===
<blockquote>
LIMIT lets you choose only the first N results
<syntaxhighlight lang="MySQL">
<syntaxhighlight lang="MySQL">
SELECT * FROM users LIMIT 10
SELECT users.*
</syntaxhighlight>
FROM users
</blockquote><!-- LIMIT -->
 
LEFT JOIN (
  SELECT DISTINCT users.id AS user_id
  FROM   user_departments
  INNER JOIN users ON users.id = user_departments.user_id
) AS users_with_departments
ON users_with_departments.user_id = users.id


=== ORDER BY ===
WHERE users_with_departments.user_id IS NULL;
<blockquote>
<syntaxhighlight lang="MySQL">
SELECT * FROM users ORDER BY first_name ASC;
</syntaxhighlight>
</syntaxhighlight>
</blockquote><!-- ORDER BY -->
</blockquote><!-- Select -->
== JOINS ==
<blockquote>
See [[sql: joins]]
</blockquote><!-- JOINS -->


== WHERE ==
You can also nest a query within a <code>WHERE</code> condition.<br>
<blockquote>
Joined tables are accessible within this nested query.
Defines the Matches that will be selected.


Basics
<syntaxhighlight lang="MySQL">
<syntaxhighlight lang="MySQL">
SELECT * FROM users WHERE name = 'Smith' AND age < 30;          # AND
SELECT *
SELECT * FROM users WHERE name = 'Smith' OR age < 30;            # OR
FROM users
SELECT * FROM users WHERE age BETWEEN  30 AND 40;                # BETWEEN
LEFT JOINS assignments ON assignments.user_id = users.id
SELECT * FROM users WHERE name IN ('john', 'jane', 'iggy');      # IN
WHERE ((SELECT COUNT(1) FROM users WHERE assignments.active = 1) > 0)  # the outer 'assignmens' is in scope here
SELECT * FROM users WHERE name NOT IN ('john', 'jane', 'iggy');  # NOT IN
SELECT * FROM users WHERE first_name LIKE "Andr%";              # LIKE (glob match)
SELECT * FROM users WHERE first_name REGEXP "^A.*"              # REGEXP
</syntaxhighlight>
</syntaxhighlight>
</blockquote><!-- Operators -->
</blockquote><!-- Nested Queries -->
</blockquote><!-- Query Components -->


= Techniques =
== Dynamically Defined Tables ==
<blockquote>
<blockquote>
== Nested Queries ==
<source lang="mySQL">
SELECT user_Id
FROM (
  SELECT DISTINCT    d.user_Id                                          ,
                      CONCAT(u.firstName, " ", u.lastName)  user_fullName
  FROM                userDepartmentTable            d
  INNER JOIN          userTable AS u ON d.user_Id  =  u.user_Id
  WHERE              d.department_Id              =  2
) u
WHERE u.user_fullName REGEXP 'andr%';
</source>
== Dynamically Defined Tables ==
Some databases do not implement the SQL IN operator.<br>
Some databases do not implement the SQL IN operator.<br>
Instead, you can use VALUES.
Instead, you can use VALUES.
Line 123: Line 88:
</source>
</source>
</blockquote><!-- Techniques -->
</blockquote><!-- Techniques -->
</blockquote><!-- Dynamically Defined Tables -->

Latest revision as of 20:41, 9 August 2022

Example

SELECT *                   # select all rows
FROM  users                # from users table
WHERE username = "dvader"  # where the 'username' column value is 'dvader'
AND   age > 40;            # and the 'age' column value is above 40

Query Components

SELECT which columns you'd like to see, and how you'd like them to be presented (order, max results, etc).

SELECT *                               # select all columns
SELECT name, age FROM users;           # select name, and age only
SELECT name AS userame FROM users;     # rename column in results table
SELECT DISTINCT name FROM users;       # select 1x row for each unique name in users
SELECT * FROM users LIMIT 10;          # only select first 10 results
SELECT * FROM users ORDER BY name ASC  # sort results in ascending order by name

After your selection you may:

  • use sql joins to associate the queried table's data to other tables.
    (ex: find users assigned to a project)

  • use sql aggregate functions to operate on groups of rows
    (ex: find average age of users in users table)

  • use sql comparison operators in your WHERE statement to determine what you want to select.
    (ex: find users whose name starts with an 'A')

Techniques

Nested Queries

You can nest SQL queries and treat them as tables.

The example below finds users.id values
that are not present in the many:many user_departments table,
by joining a user table query to itself.

SELECT users.*
FROM users

LEFT JOIN (
  SELECT DISTINCT users.id AS user_id
  FROM   user_departments
  INNER JOIN users ON users.id = user_departments.user_id
) AS users_with_departments
ON users_with_departments.user_id = users.id

WHERE users_with_departments.user_id IS NULL;

You can also nest a query within a WHERE condition.
Joined tables are accessible within this nested query.

SELECT *
FROM users
LEFT JOINS assignments ON assignments.user_id = users.id
WHERE ((SELECT COUNT(1) FROM users WHERE assignments.active = 1) > 0)  # the outer 'assignmens' is in scope here

Dynamically Defined Tables

Some databases do not implement the SQL IN operator.
Instead, you can use VALUES.

SELECT *
FROM (
  VALUES (1), (2)
) foo(id);

Most useful within a join

SELECT *
FROM (
  VALUES (1), (2)
) foo(id)

INNER JOIN (
  (VALUES (1)) bar(id)
) ON foo.id = bar.id