Sql queries: Difference between revisions

From wikinotes
m (Will moved page Sql: queries to Sql queries without leaving a redirect)
Line 14: Line 14:
== SELECT ==
== SELECT ==
<blockquote>
<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 ===
<blockquote>
Distinct only returns one result per unique value of N
<syntaxhighlight lang="MySQL">
SELECT DISTINCT username FROM  users WHERE last_name = "skywalker";
</syntaxhighlight>
</blockquote><!-- DISTINCT -->
=== LIMIT ===
<blockquote>
LIMIT lets you choose only the first N results
<syntaxhighlight lang="MySQL">
SELECT * FROM users LIMIT 10
</syntaxhighlight>
</blockquote><!-- LIMIT -->
=== ORDER BY ===
<blockquote>
<syntaxhighlight lang="MySQL">
SELECT * FROM users ORDER BY first_name ASC;
</syntaxhighlight>
</blockquote><!-- ORDER BY -->
</blockquote><!-- Select -->
</blockquote><!-- Select -->



Revision as of 18:43, 19 September 2021

Example

SELECT *
FROM  users
WHERE username = "dvader"
AND   age > 40;

Query Components

SELECT

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

JOINS

See sql: joins


Techniques

Nested Queries

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%';

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