Prompt stringlengths 10 31k | Chosen stringlengths 3 29.4k | Rejected stringlengths 3 51.1k | Title stringlengths 9 150 | Tags listlengths 3 7 |
|---|---|---|---|---|
I have tables like these:
```
Fields (ID int, Name varchar(20))
ID Name
===============
1 FieldName
2 FeildDesc
Container (ID int, Name varchar(100))
ID Name
====================================
1 C1
2 C2
3 C3
ContainerField (ContainerId int, FieldId int, FieldValue varchar(... | Join the table twice, once for the names and once for the descriptions.
```
select
c.Id as ContainerId,
cfn.FieldValue as Name,
cfd.FieldValue as Desc
from
Container c
left join ContainerField cfn
on cfn.ContainerId = c.ID and cfn.FieldId = 1
left join ContainerField cfd
on cfd.ContainerId = c.ID a... | No need for an outer join, an inner join will do it. You're also not using anything from `Container` (if you want to display the container name instead of ID, you can do an inner join with it to get that).
```
SELECT c.id AS ContainerID,
MAX(CASE WHEN f.name = 'FieldName' THEN c.FieldValue END) AS Name,
... | SQL Outer Join? | [
"",
"sql",
"t-sql",
""
] |
My table has 1 row 300,000 records and a few duplicate records they don't have a primary key so i came to the conclusion i need to copy all the distinct rows in the table im using this line of code
```
select * into newtable from (select distinct tag from Tags)
```
but i keep getting a syntax error 'incorrect syntax ... | You have to name a subquery:
```
from (...) as SubQueryAlias
```
In your case (the `as` is usally optional, except in Oracle, where it is not allowed):
```
select * into newtable from (select distinct tag from Tags) tags
``` | In MySQL, you would use `create table as`:
```
create table newtable as
select distinct tag from Tags;
``` | Sytax error when select distinct rows in a sql table | [
"",
"mysql",
"sql",
"duplicates",
""
] |
Is there a way to truncate an nvarchar using DATALENGTH? I am trying to create an index on a column, but an index only accepts a maximum of 900 bytes. I have rows that consist of 1000+ bytes. I would like to truncate these rows and only accept the first n characters <= 900 bytes. | Can be this sql useful, Just update the table for that column.
```
Update Table
Set Column = Left(Ltrim(Column),900)
``` | Create a COMPUTED COLUMN that represents the data you want to index, then create an index on it.
```
ALTER TABLE MyTable ADD ComputedColumn AS LEFT(LargeNVarcharColumn,900);
CREATE NONCLUSTERED INDEX MyIndex ON MyTable
(
ComputedColumn ASC
);
```
---
**Reference:**
* [computed\_column\_definition](http://msdn.... | SQL Server - Truncate Using DATALENGTH | [
"",
"sql",
"sql-server",
"t-sql",
"datalength",
""
] |
This seems like something that should be fairly common, so this could be as simple as giving me the right vocabulary for what I'm describing.
I want to return the results of a query and in a column I want to return a repeating number sequence of 1, 2, 3.
Desired Result Set:
```
Num Result
---------------
1 r... | I think you can do this...
```
SELECT MOD(i,3)+1
, result
FROM
( SELECT @i:=@i+1 i
, result
FROM results
, ( SELECT @i:=2 ) vals
ORDER
BY result
) x;
``` | Although you can do this with `mod()`, I think an `if()` is simpler:
```
SELECT @row := if(@row < 3, @row + 1, 1) as Num,
a.Result
FROM Results a CROSS JOIN
(SELECT @row := 0) vars
ORDER BY a.Result ASC;
```
I'm not sure what the table `randoms` is for. It doesn't seem necessary to the problem. [Here](ht... | Repeating Running Numbers along side MySQL Results | [
"",
"mysql",
"sql",
""
] |
I have a scenario where I have to select multiple rows from table, I have multiple rows of one record but with different status,
at times I have two identical rows with identical data for status < for that case I canted to select Non zero for the first occurrence and set 0 for the remaining occurrences.
Below is the I... | You might modify your inner select using Row\_Number() and set price to Zero for RowNumber > 1.
```
SELECT CASE WHEN Temp.RowNumber > 1 THEN
0
ELSE
Temp.Price END AS Price,
* FROM (
SELECT *,Row_Number() over (PARTITION by ID,Status ORDER BY ID,Date) AS 'RowNumber'
FROM #Temp
) Temp
Order by... | You can try this:
```
;WITH DataSource AS
(
SELECT RANK() OVER (PARTITION BY [ID], [ItemName], [Price], [Status] ORDER BY Date) AS [RankID]
,*
FROM #Temp
)
SELECT [ID]
,[ItemName]
,IIF([RankID] = 1, [Price], 0)
,[Status]
,[Date]
FROM DataSource
ORDER BY [ID]
,[Date]
`... | Selection One Entry Only As Non Zero In SQl Select | [
"",
"sql",
"sql-server",
"t-sql",
"select",
""
] |
I have these two tables:
**popular\_song**
```
song_name | rate | country_id
------------------------------
Tic Tac | 10 | 1
Titanic | 2 | 1
Love Boat | 8 | 2
Battery | 9 | 2
```
**country**
```
conutry_id | country
--------------------------
1 | United States
2 | Germany
```... | There is a trick that you can use with `substring_index()` and `group_concat()`:
```
SELECT MAX(rate),
substring_index(group_concat(song_name order by rate desc separator '|'), '|', 1) as song,
country
FROM popular_song ps JOIN
country cnt
ON ps.country_id = cnt.country_id
GROUP BY country;
```
... | You can use another self join to popular songs table with the max rating
```
SELECT ps.*,cnt.country
FROM popular_song ps
JOIN (SELECT MAX(rate) rate, country_id FROM popular_song GROUP BY country_id) t1
ON(ps.country_id = t1.country_id and ps.rate= t1.rate)
JOIN country cnt
ON ps.country_id = cnt.conutry_id
```
[**... | Get the max value in a specific group of rows | [
"",
"mysql",
"sql",
"database",
"greatest-n-per-group",
""
] |
I have a Scalar SQL function thats returns a decimal value, and this function is used in many stored procedures across my database. Now in some procedures, I need to set a value based on some criteria inside the function. To make it clearer, depending on some variables used in calculating the result of the function, I ... | You have a couple of options
1) Change it from a function to a stored procedure, and add an output parameter.
2) Change it from a scalar function to a table valued function returning a single row, with the additional value as an additional column.
If you need to preserve the existing function signature then just cre... | No, you cannot. Functions are severely limited in SQL Server and do not allow any side effects.
What you can do, however, is convert your scalar function into a table function. In it, you can return a table with as many columns as you need, so returning more than one value is not a problem. | Return two values from a scalar SQL Function | [
"",
"sql",
"sql-server",
"sql-server-2008",
"t-sql",
""
] |
I'm new in coding stored procedures. Basically I would just like to transfer top 10 records of table 1 to table 2(which I created). My code can't insert the records I selected from table 1. I'm not sure if I'm missing something or I'm doing it wrong. Please help. Thanks in advance!
Note:
1.) Table 1 and Table 2 are w... | ```
ALTER PROCEDURE [dbo].[sp_BI_Get_AsiaTopTen]
AS
BEGIN
SET NOCOUNT ON;
INSERT INTO [dbo].[tbl_BI_AsiaTopTen]
([FYName],[FMONTH],[FMONTH_NUM],[World_AREA])
SELECT TOP 10 [FYName]
, [FMONTH]
, [FMONTH_NUM]
, [World_AREA]
FROM [db... | Try something like this instead:
```
INSERT INTO [dbo].[tbl_BI_AsiaTopTen]
(
[FYName],
[FMONTH],
[FMONTH_NUM],
[World_AREA]
)
SELECT TOP 10
[FYName],
[FMONTH],
[FMONTH_NUM],
[World_AREA]
FROM [dbo].[tbl_BI_FastReport1_Temp]
WHERE [World_AREA] = 'Asia'
AND ... | STORED PROC - select then insert | [
"",
"sql",
"sql-server",
"stored-procedures",
""
] |
I have a table name `tbl_Employees`
```
id Name Designation
1 Rajeev Developer
2 Deepak Developer
3 Pankaj Sales
4 Siksha Sales
5 Parul Sales
6 Nikita HR
7 Dinesh Account
8 Mahiman Travel
9 Mukesh Adevertising
10 Pulkit Marketing
11 Diksha Database
12 Gurinder Database
```
I am ... | You can use `NEWID()` to select records rendomly as below:
```
SELECT TOP(5) * FROM tbl_Employees ORDER BY NEWID()
``` | ```
select top 5 * from [yourtable] order by newid()
``` | Random records Select in mysql | [
"",
"sql",
"sql-server",
""
] |
I have tried this query, but it returns an error :
```
Select DATA_TYPE
From INFORMATION_SCHEMA.COLUMNS
WHERE TABLE_NAME = 'Customers' AND
COLUMN_NAME IN (Select *
From INFORMATION_SCHEMA.COLUMNS
Where TABLE_NAME = 'Customers');
```
Error :
> Only one expression can be specified in the select list when the subquery... | Just use
```
Select COLUMN_NAME , DATA_TYPE
From INFORMATION_SCHEMA.COLUMNS
WHERE TABLE_NAME = 'Customers'
```
BTW if you use the `in` clause, then select only a single column in the subquery and not all
```
where COLUMN_NAME IN (Select col from table)
```
and not
```
where COLUMN_NAME IN (Select * from table)
``... | I would be careful with collation and use:
```
Select DATA_TYPE
From INFORMATION_SCHEMA.COLUMNS
WHERE lower(TABLE_NAME) = 'customers';
``` | How to display data type of all columns in a sql query | [
"",
"sql",
"types",
"sqldatatypes",
""
] |
I am using the following query. In this query I want to apply the where clause based on passed parameter. But the issue is that where clause is like **'value = if parameterVal = 'I' than NULL else NOT NULL'**
I've build a query like this
```
SELECT * FROM MASTER
WHERE
Column1 IS (CASE WHEN :Filter = 'I' THEN 'NULL' E... | ```
SELECT * FROM MASTER
WHERE (Filter = 'I' AND Column1 IS NULL)
OR
(Filter <> 'I' AND Column1 IS NOT NULL)
``` | If you really insist on using a CASE the `SELECT` could be rewritten as:
```
SELECT *
FROM MASTER
WHERE CASE
WHEN COLUMN1 IS NULL AND FILTER = 'I' THEN 1
WHEN COLUMN1 IS NOT NULL AND FILTER <> 'I' THEN 1
ELSE 0
END = 1
```
[SQLFiddle here](http://sqlfiddle.com/#!4/685b0/1)
F... | Case when statement in SQL | [
"",
"sql",
"oracle",
""
] |
does someone know how to speed up following query:
```
select count (*)
from table
where column1 between DATEADD(day, -90, convert(date, getdate())) AND getdate()
and column2 is not null
```
This query takes 20 sec. for 8.000 rows
I think/know the bottleneck is the conversion, but it is necessary... | It is unlikely to be an index issue.
There is a [bug](https://connect.microsoft.com/SQLServer/feedback/details/630583/incorrect-estimate-with-condition-that-includes-datediff) in sqlserver-2008. It should be fixed in newer versions of sqlserver
Try this instead:
```
declare @from datetime = DATEADD(day, -90, conver... | Your query is fine. The conversions are on constants, rather than on the column. Instead, you need an index. This will probably help:
```
create index idx_table_column1_column2 on table(column1, column2);
```
This is a covering index, so only the index will be used to satisfy the query. | Speed up query containing convert | [
"",
"sql",
"sql-server",
""
] |
I have a `Group` table with the columns `GroupId` and `GroupName`. Also there is another table called `Group_Student` which keeps track of which group a student belongs. It contains the columns `GroupId` (foreign key to the `Group` table) and `StudentId`.
I would like to know on how I can write a SQL query which lists... | Here is a sql fiddle of this working
<http://sqlfiddle.com/#!3/0f8a5/2/0>
```
select
groupname, [group].groupid, count(*) as 'MemberCount'
from [group]
inner join group_student on [group].groupid = group_student.groupid
group by groupname, [group].groupid
``` | ```
SELECT GroupName, Group.GroupID, COUNT(StudentId) AS MemberCount
FROM Group
INNER JOIN Group_Student ON Group.GroupID = Group_Student.GroupID
GROUP BY Group.GroupID
``` | SQL to get Count of Members in each group | [
"",
"sql",
"sql-server",
"t-sql",
""
] |
i am very new in Laravel,currently working with Laravel4.I am trying to add a multiple column search functionality in my project.I can do single column eloquent search query,But honestly i have no idea how to do multiple column eloquent search query in laravel.I have **two drop down menu**
1.Locatiom
2.blood group.
i... | Simply chain `where` for each field you need to search through:
```
// AND
$results = SomeModel::where('location', $location)->where('blood_group', $bloodGroup)->get();
// OR
$results = SomeModel::where('location', $location)->orWhere('blood_group', $bloodGroup)->get();
```
You can make it easier to work with thanks... | This is a great way but I think there is an error somewhere as laravel would not allow you to access a non-static function so instead of using
```
SomeModel::searchBloodGroup($bloodGroup)->searchLocation($location)->get();
```
you could simply use
```
SomeModel::BloodGroup($bloodGroup)->Location($location)->get();
`... | Laravel multiple column eloquent search query | [
"",
"mysql",
"sql",
"laravel-4",
""
] |
I'm creating custom views that show totals for different things in a database, and I'd like to also show the differences.
For example;
```
SELECT
(SELECT COUNT(*) FROM `documents`) AS `doc_count`,
(SELECT COUNT(*) FROM `contacts`) AS `user_count`,
(`doc_count` - `user_count`) AS `difference`;
```
I get an e... | You could wrap both queries with an additional query:
```
SELECT doc_count, user_count, doc_count - user_count AS difference
FROM ((SELECT COUNT(*) FROM `documents`) AS doc_count,
(SELECT COUNT(*) FROM `contacts`) AS user_count) t
``` | No you can't use the aliases at same level of query you have to use the whole expression or use sub select
```
SELECT
(SELECT COUNT(*) FROM `documents`) AS `doc_count`,
(SELECT COUNT(*) FROM `contacts`) AS `user_count`,
((SELECT COUNT(*) FROM `documents`) - (SELECT COUNT(*) FROM `contacts`)) AS `difference`;
... | How to show the difference between two counts using aliases? | [
"",
"mysql",
"sql",
"select",
""
] |
I am doing a SELECT from a MYSQL table
Table looks like this
```
year tour starts scoring_avg
1990 EUR 5 71.56
1990 USA 6 0.0
1991 EUR 12 71.21
1991 USA 8 69.23
```
I am doing a SELECT like so
```
SELECT
year,
SUM(starts),
... | If you just want to change `scoringavg`, use conditional aggregation:
```
SELECT year, SUM(starts),
SUM(case when scoring_avg > 0 then starts*scoring_avg end) as scoring_avg
FROM scores
GROUP BY year;
```
However, I would suggest doing all the work in a single query and not doing any division afterwards. The f... | You may try this:
```
SELECT
year,
SUM(starts),
SUM(starts*scoring_avg) as scoring.avg
FROM scores
WHERE scoring_avg > 0
GROUP BY year
``` | MYSQL avoid SELECT computation if multiplying by ZERO | [
"",
"mysql",
"sql",
"select",
""
] |
I am in the process of migrating a SQL Server database to Oracle, where I have to convert SQL Server procedure which uses special tables called `INSERTED` and `DELETED` in SQL Server.
As per my understanding these tables hold copies the data of last inserted/deleted records.
(find the msdn article here: <http://msdn.m... | Thanks for the answers and comments. here is the complete solution to my problem.If some one meet the exact problem this will help.
```
create or replace PROCEDURE CreateTrackingTriggers
(
-- take the target table and shadow user as agruments
v_TableName IN NVARCHAR2 DEFAULT NULL,
v_ShadowUser IN NVARCHAR2 DEFAULT 'SH... | Oracle triggers use pseudo-records rather than special tables. That is, instead of tables we can access the values of individual columns.
We distinguish pseudo-records in the affected table from records in (other) tables by using the prefixes `:NEW` and `:OLD` . Oracle allows us to declare our own names for these, but... | Oracle equivalent for SQL Server INSERTED and DELETED tables | [
"",
"sql",
"sql-server",
"oracle",
"triggers",
""
] |
I'm having trouble running/configuring a query for Microsoft SQL Server, the query is as follows:
```
SELECT
ps.WeekIncluded AS PaidWeeks,
PayD.PayDate AS PayDates,
ps.PayYear AS PYear,
months.PMonth,
(SELECT sum(DayPay) FROM Shifts GROUP BY WeekNumber)
FROM dbo.PayStructure ps
JOIN dbo.Months Mon... | ```
SELECT
ps.WeekIncluded AS PaidWeeks,
PayD.PayDate AS PayDates,
ps.PayYear AS PYear,
months.PMonth,
SumPay
FROM dbo.PayStructure ps
JOIN dbo.Months Months
ON ps.MonthID = months.ID
JOIN dbo.PayDates PayD ON ps.MonthID = PayD.MonthID
LEFT JOIN
(SELECT S. WeekNumber,
PSI.MonthId,
PSI.PayYear... | The error message is fairly clear; SQL Server cannot know from your query which possible value of `WeekIncluded` it should include the result set for you query. Think of it yourself -- there will be one row per month in your output and one "slot" for a WeekIncluded value. Which one should be shown?
Try running the que... | Being unable to run query in Microsoft SQL Server | [
"",
"sql",
"sql-server",
""
] |
Modeling a PostgreSQL database, is it a bad practice to create a table to serve another tables? For example, create a table with default address fields.
```
CREATE TABLE address (
zipcode char(8) NOT NULL,
street varchar(80) NOT NULL,
number varchar(10) NOT NULL,
city varchar(60) NOT NULL,
state ch... | **If** the intention is to copy the table layout, the basic idea is fine, but **[inheritance](http://www.postgresql.org/docs/current/interactive/ddl-inherit.html)** is a misunderstanding.
The idea to ***copy*** the table schema from another table is sound (if you really *need* a copy). But use
```
CREATE TABLE new_ta... | That isn't a good idea. Querying the `address` table will show you a bunch of jumbled addresses from all sources, but nothing to connect them to anything else usefully.
This would be better done with a conventional relational model via a foreign key reference to an address ID.
Another option is to define the address ... | Is it a bad practice to use a table only for multiple inheritance? | [
"",
"sql",
"postgresql",
"inheritance",
"postgresql-9.2",
"postgresql-8.4",
""
] |
I am struggling with an SQL query. This situation is as follows:-
I have 2 tables Users and Results:-
**Users**
* user\_id (PK)
**Results**
* result\_id
* fk module\_id
I am trying to select all users from the Results table who don't have an entry for module 1.
I can select all users with no corresponding record... | Is that what you want:
```
SELECT *
FROM user U
LEFT OUTER JOIN results R ON R.user_id = U.user_id
WHERE R.result_id IS NULL
OR(R.result_id IS NOT NULL AND R.module_id <> 1)
```
Hope this will help you. | If your requirement is to JOIN all users to their results unless the result happens to be module #1, you can use this:
```
SELECT *
FROM user u
LEFT JOIN results r ON
u.user_id = r.user_id AND
r.module_id != 1;
```
I'm not completely clear on whether you want all users and associated non-module 1 results, ... | SQL include results where id does not exists in related table | [
"",
"mysql",
"sql",
"join",
""
] |
I am trying to create a view as follows :
```
CREATE VIEW TEMP_VIEW AS
SELECT
a.actor_id,
a.first_name,
a.last_name,
LISTAGG(DISTINCT(c.name ) || ': ' ||
(SELECT LISTAGG(f.title,', ') WITHIN GROUP (ORDER BY f.title)
FROM film f
INNER JOIN film_category fc
... | No.1 - The error message is quite clear, you cannot use DISTINCT function within LISTAGG.
No.2 - In a normalized data structure, a category name will always be unique
Try and check it yourself :
```
SELECT COUNT(DISTINCT(name)) FROM category;
SELECT COUNT(*) FROM category;
```
If your schema is properly normalized ... | I would do this with nested selects. I think the following does what you want:
```
SELECT actor_id, first_name, last_name,
LISTAGG(category || ': ' || films, '; ') WITHIN GROUP (ORDER BY category)
FROM (SELECT a.actor_id, a.first_name, a.last_name, c.name as category
LISTAGG(f.title, ', ') WITHIN G... | Need some assistance in creating a view definition | [
"",
"sql",
"oracle",
""
] |
I want to add a new column to an already existing table, but I want to give it a default value dependent on already existing data:
e.g. Each record has a `start_date`. Now I want to add an `open_until` column, and I want to fill it with the value for `start_date` of each existing record. (the upcoming records will be ... | You can also do it within South. The only caveat is that you need two steps for that:
1. A **schema migration** that adds the open\_until column
```
from django.db import models
import datetime
class MyModel(models.Model):
start_date = models.DateField(),
open_until = models.DateField(defau... | In Python 3.8 I first add fields to `MyApp` models file and it looks like:
```
from django.db import models
import datetime
class MyModel(models.Model):
start_date = models.DateField(),
open_until = models.DateField(default=datetime.date.today),
```
Then, after running `manage.py makemigrations` add this lin... | Django migrations/South: New column take default value another value from the same record | [
"",
"sql",
"django",
"migration",
"django-south",
"relational",
""
] |
I am working on a some kind of chat app. I store every message in a SQLite table such as following
```
| id | fromId | toId | date | content |
---------------------------------------------
| 0 | 1423 | 90 | ... | ... |
| 1 | 324 | 90 | ... | ... |
| 2 | 90 | 324 | ..... | Try this:
```
SELECT *
FROM chat c
WHERE NOT EXISTS
(SELECT * FROM chat
WHERE c.fromId IN (fromId, toId) AND c.toID IN (fromId, toID) AND c.id < id);
```
<http://sqlfiddle.com/#!7/d57f3/2/0> | If you have indexes on `chat(fromid, toid)` and `chat(toid, fromid)`, then the most efficient way may be:
```
select c.*
from chat c
where not exists (select 1
from chat c2
where c2.fromId = c.fromId and c2.toId = c.toId and c2.id > c.id
) and
not exists (sele... | Get the latest message for each two clients using SQL | [
"",
"android",
"sql",
"sqlite",
""
] |
I want to import a csv file into a database
**Header**
id,name,surname,date1,date2
**Data**
10001,Bob,Roberts,03/06/2007 15:18:25.10,03/06/2007 15:18:29.19
This file has millions of rows and in order to import it I used the following command:
```
mysqlimport --ignore-lines=1 --fields-terminated-by=, --columns='id,... | I have played with this issue for a bit and I solved it converting my dates with an awk script and upgrading mysql to version 5.6 which supports milliseconds
Thanks anyway | Your dates aren't in the MySql standard format, which is "YYYY-mm-dd HH:MM:SS".
Mysqlimport should be able to accept some date conversion function among the command line parameters, like you would do if you were using "LOAD DATA" command (which is used by mysqlimport utility), but at this time it isn't:
<http://bugs.... | Import dates in mysql | [
"",
"mysql",
"sql",
"mysqlimport",
""
] |
I have the following MySQL query:
```
select * from u, s, c, ut, m
```
which works fine, displaying all columns of all tables. I want to add record counts to only the `u` table.
I tried this:
```
select (select count(*) as totalcount from u), * from u, s, c, ut, m
```
but it is throwing an error. | This query is working for me :
```
select * , (select count(*) from u) as totalcount from u , s , c , ut , m ;
``` | ```
select (select count(*) as totalcount from u), * from u, s, c, ut, m
```
I try your query and it works fine . Just try this . I hope it works.
```
select (select count(*) from u) as totalcount, * from u, s, c, ut, m
``` | Adding 'count' in MySQL query with multiple tables in 'from' clause | [
"",
"mysql",
"sql",
""
] |
Very simple basic SQL question here.
I have this table:
```
Row Id __________Hour__Minute__City_Search
1___1409346767__23____24_____Balears (Illes)
2___1409346767__23____13_____Albacete
3___1409345729__23____7______Balears (Illes)
4___1409345729__23____3______Balears (Illes)
5___1409345729__22__... | ```
SELECT Row,
Id,
Hour,
Minute,
City_Search
FROM Table T
JOIN
(
SELECT MIN(Row) AS Row,
ID
FROM Table
GROUP BY ID
) AS M
ON M.Row = T.Row
AND M.ID = T.ID
``` | Can you change hour/minute to a timestamp?
What you want in this case is to first select what uniquely identifies your row:
```
Select id, max(time) from [table] group by id
```
Then use that query to add the data to it.
```
SELECT id,city search, time
FROM (SELECT id, max(time) as lasttime FROM [table] GROUP BY i... | Filter SQL data by repetition on a column | [
"",
"sql",
"google-bigquery",
""
] |
I have the following tables:
Basically I have a many2many relation between students and courses using the junction table students\_courses

Here is some data populated into the tables:
students:
` currency formatting problem here.
The below code is working for me:
```
SELECT TO_CHAR(10000,'L99G999D99MI',
'NLS_NUMERIC_CHARACTERS = ''.,''
NLS_CURRENCY = $') "Amount"
FROM DUAL;
```
which will provide me with the output: `$10,000.00`.
Now, I want to conv... | If you want to do it in the query:
```
SELECT TO_CHAR(10000,'L99G999D99MI',
'NLS_NUMERIC_CHARACTERS = ''.''''''
NLS_CURRENCY = ''$'' ') "Amount"
FROM DUAL;
```
Gives `$10'000.00` (as this string is getting pre-processed there are pairs of quotes around the characters (becoming single)... | This can be used as well since the decimal notation is already know for French countries
```
SELECT TO_CHAR(1000000000,'999,999,999,999.99') "Amount" FROM DUAL;
``` | SQL to_char Currency Formatting | [
"",
"sql",
"oracle",
"currency",
"to-char",
""
] |
I am trying to copy data from one column to another column in a different table using MySQL but the table that I am importing into has a foreign key restraint that is preventing me from doing this;
Here is the table that I would like to import from (product\_code) column
Table1
```
+----+--------------+-------------... | The fix was simple,
Just wrap the query inside:
```
SET AUTOCOMMIT = 0;
SET FOREIGN_KEY_CHECKS = 0;
SET UNIQUE_CHECKS = 0;
# YOUR QUERIES HERE...
SET AUTOCOMMIT = 1;
SET FOREIGN_KEY_CHECKS = 1;
SET UNIQUE_CHECKS = 1;
```
The the data goes in, only difficulty is the large size of the dataset but breaking it into ch... | To me your query looks OK.
try breaking the "insert - select" into parts either using some id in the where clause or using limit in the select.
insert 100 records. See how it goes. check your time\_out variables. increase accordingly if needed. | Copy Data from one column to another column in a different table using MySQL | [
"",
"mysql",
"sql",
""
] |
I have a table like below
```
id name year
--------------
1 A 2000
2 B 2000
2 B 2000
2 B 2000
5 C 2000
1 D 2001
3 E 2001
```
as well as you see in the year 2000 we missed id '3' and id '4' and in the year 2001 we missed id '2'. I want to generate my second table whic... | Gaps and Islands in Sequences is the name of this problem. you read this [article](https://www.simple-talk.com/sql/t-sql-programming/the-sql-of-gaps-and-islands-in-sequences/) | Here's something to get you started:
```
WITH cte AS
(
SELECT *
FROM
(VALUES
(1),(2),(3),(4),(5)
) Tally(number)
), cte2 as
(
SELECT DISTINCT [year]
FROM
(VALUES
(2000),(2000),(2001)
)tbl([year])
), cte3 as
(
SELECT *
FROM cte
CROSS JOIN cte2
)
SELECT *
FROM cte3... | SQL Server find the missing number | [
"",
"sql",
"sql-server",
"t-sql",
""
] |
still working on a query for a project and my partner has managed to come up with a nifty SQL statement what works wonders when run but wont seem to work in VBA and it has got me questioning how much of SQL statements are supported in VBA
This is the original query which my work partner whipped up and it works great w... | ```
Dim query As String
query = "SELECT " & _
"crm_clients.id, " & _
"crm_clients.national_insurance, " & _
"crm_clients.total_hmrc, " & _
"(SELECT " & _
" crm_crmuseractions.Title " & _
"FROM " & _
" dev_pfands.crm_crmuseractions " & _
"WHERE crm_crmuseractions.`id` =... | You need to concatenate the strings of data across the multiple lines like so:
```
strText = "This is the first line " & _
"This is the second line"
```
Given the large amount of text you have, you may run into an error `Too many line continuations` (as the maximum amount of line continuations is 25). In wh... | VBA SQL query strings, how much is supported? | [
"",
"sql",
"vba",
"excel",
""
] |
When I am trying to calculate the date difference by using datediff function it showing that invalid identifier.
```
SELECT DATEDIFF(day,'2008-08-05','2008-06-05') AS DiffDate from da_static_trade.
Error : invalid identifier.
```
Can you please tell me what is the function to calculate date difference. | There is no `DATEDIFF()` function in Oracle. On Oracle, it is an arithmetic issue
```
select DATE1-DATE2 from table
``` | Oracle support Mathematical Subtract `-` operator on Data datatype. You may directly put in select clause following statement:
```
to_char (s.last_upd – s.created, ‘999999D99′)
```
Check the [EXAMPLE](http://crackingsiebel.wordpress.com/2010/12/01/oracle-sql-date-difference-in-days/) for more visibility.
In case you... | How to calculate difference between two dates in oracle 11g SQL | [
"",
"sql",
"oracle11g",
""
] |
See the below example,
```
create table data(name varchar, value int);
insert into data values('joe',1);
insert into data values('bob',2);
insert into data values('jane',3);
insert into data values('anne',4);
insert into data values('kate',5);
```
And if I Execute
```
select * from data limit 2;
```
Will Get
```
... | You have two options according to your need i.e,
```
select * from data order by value desc limit 2
```
Or
[**LIMIT and OFFSET**](http://www.postgresql.org/docs/9.3/static/queries-limit.html)
if you want the 4th and 5th row just offset the first 3 so that the 4th row becomes the start of our set and you can spec... | I know I'm answering a six year old question and I know the accepted answer says to use an offset, however that's only going to be useful if you know the length of the table. Looking at the wording of the question and the example given, I assumed that like myself, the author wanted the last entries in a table based on ... | PostgreSQL:How get last rows from a select query | [
"",
"sql",
"postgresql",
""
] |
Is there a way to for an sql statement to search if a column string with multiple items contains a certain item, but not include a certain item that is a substring. The following is the current sql statement that I am using.
```
select * from tbltest where platform like '%item%'
```
platform is the column string that... | If you want to require that an item be surrounded by spaces you can add them on either side of your list as well as your term:
```
select *
from tbltest
where ' '+platform+' ' like '% item %'
```
Ideally data is not stored in lists, as this searching will not be terribly efficient. | ```
select *
from tbltest
where (platform like 'item%' or platform like '% item%')
and (platform like '%item' or platform like '%item %')
```
What this does is check whether the `item` is surrounded by spaces, the beginning and/or the ending of the string.
A requirement would be that there's no `item` with a space ... | SQL search column where one item in column is substring of another item | [
"",
"sql",
""
] |
I need to execute a stored procedure at the end of each calendar month. it should take end of the current month as finish and end of previous month as start date.
Here examples:
```
exec my_report @ReportStartDate = '20140731', @ReportEndDate='20140831'
exec my_report @ReportStartDate = '20140131', @ReportEndDate='20... | Your script seems a bit complicated
```
DECLARE @ReportStartDate date, @ReportEndDate date
-- for sqlserver 2012
SELECT
@ReportStartDate = EOmonth(getdate(), -1),
@ReportEndDate = EOmonth(getdate())
-- for earlier versions
SELECT
@ReportStartDate = dateadd(month, datediff(m, 0, getdate()), -1),
@ReportEndD... | Here my script. I changed to a SP. It works fine. Thanks every one
```
declare
@ReportStartDate DATETIME=EOmonth(getdate(), -1),
@ReportEndDate DATETIME=EOmonth(getdate())
if @ReportEndDate=getdate()
Begin
insert into report_log (col1,
col2,
col3
) exec Report @ReportStartDate, @ReportEndDate,@username=null,@Languag... | SQL Server : how to run a stored procedure at the end of each calendar month | [
"",
"sql",
"sql-server",
"t-sql",
""
] |
How can I convert the following query to inner join and avoid using distinct to optimise performance.
```
select distinct(GroupId)
from BatchQuotaIndividualQuotas
where BatchQuotaCommonSettingsID = 58
and
GroupId not in
(
select distinct(groupid)
from BatchQuotaInd... | if you remove distinct from the where clause, your query will run faster.
Here are 2 better ways of writing it
count(ObjectiveFunctionTotalResultID) will count not null values
```
SELECT GroupId
FROM BatchQuotaIndividualQuotas
WHERE BatchQuotaCommonSettingsID = 58
GROUP BY GroupId
HAVING count(ObjectiveFunction... | First of all, distinct is not a function, but a modifier of the select statement. You select a distinct combination of field values rather than a distinct single field. The parentheses will actually call a syntax error if you have more fields. So it's not
```
select
distinct(groupid)
```
but
```
select distinct
... | Changing not in clause to inner join | [
"",
"sql",
"sql-server",
""
] |
I have built a cube in Business Development Intelligent Studio(BIDS) using some database with the name 'Test\_cube' which consists of Products dimension table, customers dimension table and orders fact table.
The products table attributes :prodID-primary key,prodname,prodtype,prodcost
The customers table attributes... | Try this
Double Click on your data source under solution explorer -> Navigate to `Impersonation Information` tab -> Choose `inherit`
Now try processing it again. | I used 'Use a specific username and password' and typed in the username and password I use to log into my PC and it worked | Trying to process the cube but getting the error at impersonation information | [
"",
"sql",
"bids",
"ssas-2008",
""
] |
Here is my current SQL statement
```
SELECT
Customers.Customer,
SUM(CASE WHEN Products.ProductID in ('ab6','ab5','ab4','ab3','ab2','ab1','abc'.......many others THEN 1 ELSE 0 END) AS Product_10,
FROM Customers
INNER JOIN Products ON Customers.ProductID = Products.ProductID
GROUP BY Customers.Customer
```
So basic... | Most databases have a way of combining strings. In MySQL, the function is `group_concat()`, so you can get what you want using:
```
SELECT c.Customer,
SUM(CASE WHEN p.ProductID in ('ab6','ab5','ab4','ab3','ab2','ab1','abc'.......many others THEN 1 ELSE 0 END) AS Product_10,
GROUP_CONCAT(DISTINCT p.Produc... | ```
SELECT
Customers.Customer,
Products.ProductID,
SUM(CASE WHEN Products.ProductID in ('ab6','ab5','ab4','ab3','ab2','ab1','abc'.......many others THEN 1 ELSE 0 END) AS Product_10,
FROM Customers
INNER JOIN Products ON Customers.ProductID = Products.ProductID
WHERE Products.ProductID in ('ab6','ab5','ab4','ab3',... | SUM(CASE WHEN Products.ProductID in (show which product matched) SQL | [
"",
"sql",
"count",
"case",
""
] |
I have the following log table for user messages (simplified form) in Postgres 9.2:
```
CREATE TABLE log (
log_date DATE,
user_id INTEGER,
payload INTEGER
);
```
It contains up to one record per user and per day. There will be approximately 500K records per day for 300 days. payload is ever increasing f... | For best read performance you need a [multicolumn index](https://www.postgresql.org/docs/current/indexes-multicolumn.html):
```
CREATE INDEX log_combo_idx
ON log (user_id, log_date DESC NULLS LAST);
```
To make **[index only scans](https://wiki.postgresql.org/wiki/Index-only_scans)** possible, add the otherwise not n... | This is not a standalone answer but rather a comment to @Erwin's [answer](https://stackoverflow.com/a/25536748/2684232). For 2a, the lateral join example, the query can be improved by sorting the `users` table to exploit the locality of the index on `log`.
```
SELECT u.user_id, l.log_date, l.payload
FROM (SELECT use... | Optimize GROUP BY query to retrieve latest row per user | [
"",
"sql",
"postgresql",
"indexing",
"greatest-n-per-group",
"postgresql-performance",
""
] |
I have a UDF that calculates a score based on a range of values that are going in to the table.
The UDF has to be applied/called during the table creation process, this is where I'm having a little trouble.
The UDF had to be created using case when methods only, so I can't change much on that but I'm sure I've just g... | Try to use this for Cupid column:
```
Cupid as dbo.cupidscoreUDF(Gender, Name, Dob, Weight, Height, Smoker, Salary)
``` | I would very seriously suggest moving the calling of the UDF to the insert/update instead of the table definition. To make this easier you could make a simple procedure to insert/update that calls the UDF. That way you avoid having to give the data twice.
here is a very generic example, in this example it looks a bit ... | Calling a UDF during table creation | [
"",
"sql",
"sql-server",
"t-sql",
"user-defined-functions",
""
] |
I have a case where I want to return the exchange rate of a currency, but if the date of the job is before 1/1/1999, then I want to just return the rate of 1/1/1999 since the exchange\_rate table has no information before 1/1/1999. So in this case, if the returned date from the COALESCE is 1/1/1985, the query should ju... | Do this:
```
CASE
WHEN COALESCE(j.offer_date, j.accepted_date, j.reported_date, j.start_date) < '1999-01-01' THEN '1999-01-01'
ELSE COALESCE(j.offer_date, j.accepted_date, j.reported_date, j.start_date)
END
```
And, yes, I know that's repetitive and a lot to type, but it will get the job done. | I personally would use case statement in select part
```
SELECT
CASE
WHEN date < '1999-01-01' THEN (SELECT TOP 1 [COLUMN_YOU_WANT] FROM exchange_rate AS c3 WHERE date = '1999-01-01' AND c3.currency_id = j.currency_id)
ELSE c1.[COLUMN_YOU_WANT]
END, j.offer_date, j.accepted_date, ...
```
Basically ... | SQL Conditional Date COALESCE | [
"",
"sql",
"sql-server",
"join",
""
] |
I have the following tables
```
Employee
ID QueueID OverrideQueueID
1 1 NULL
2 2 3
3 1 3
4 4 NULL
Queue
ID
1
2
3
4
```
I need to join these tables together. Basically the join needs to look to see if there is an OverrideQueueID, i... | COALESCE or ISNULL in the join is nonetheless the way to go.
Analyse the execution plan of your query if the performances are not up to your expectations and edit yout post with the result. | To address your perf concerns, another option would be to add a computed, persisted column to the employee table, then index this column and do all joins against it instead of either QueueId or OverrideQueueId. For example:
```
ALTER TABLE dbo.Employee ADD ActiveQueueId AS COALESCE(OverrideQueueId, QueueId) PERSIS... | Joining 2 columns in 1 table to 1 column in another table | [
"",
"sql",
"sql-server",
"sql-server-2012",
"ssms",
""
] |
The structure of the table and data is as follows:
```
CityID cityname CountryID
A1 abc IN
A2 bcd IN
A2 cde US
A2 def UK
A3 efg SL
A4 fgh SL
A4 ghi NZ
```
Here the `CityIDs` are duplicates and the output shou... | Try following query:-
```
SELECT CityID, cityname, CountryID
FROM tab
WHERE CityID IN (SELECT CityID FROM tab
GROUP BY CityID
HAVING COUNT(CityID) > 1);
``` | Try this using [OVER](http://msdn.microsoft.com/en-us/library/ms189461.aspx) clause:
```
DECLARE @tbl_city TABLE
(
[CityID] CHAR(2)
,[CityName] VARCHAR(12)
,[CountryID] CHAR(2)
)
INSERT INTO @tbl_city
VALUES ('A1', 'abc', 'IN')
,('A2', 'bcd', 'IN')
,('A2', 'cde', 'US')
,('A2', 'def', 'UK')
... | how to get duplicate rows of a single column including other columns in sql server | [
"",
"sql",
"sql-server",
"t-sql",
""
] |
I'm trying to write a query that's pulling dates from one table of schedules and seeing if they had followup contact from another table within X number of days.
I have a query that's something like this but it's not doing the checks properly. My logic seems right in my head but I guess it's not right:
```
select
appo... | I would recommend that you use `apply` for this purpose. I think it is the easiest way to express your logic:
```
select a.person_id, a.datetime, c.datetime as nextdatetime,
(case when datediff(d, a.datetime, c.datetime) <= 3 then 'yes' else 'no'
end) as within3days
from appointments a outer apply
... | I think this is what you want:
```
select a.person_id,
a.date,
c.date as first_call_after,
case when datediff(d,a.date,c.date) >= 3
then 'yes' else 'no' end as within3days
from appointments a
left join calls c
on a.person_id = c.person_id
and c.date = (select min(x.date)
... | SQL find next followup within X number of days (joins comparing datetimes) | [
"",
"sql",
"sql-server",
"join",
""
] |
I am having difficulties writing a Postgres function, as I am not familiar with it. I have multiple tables to import into Postgres with this format:
```
id | 1960 | 1961 | 1962 | 1963 | ...
____________________________________
1 23 45 87 99
2 12 31 ...
```
which I need to convert into this ... | A **completely dynamic** version requires dynamic SQL. Use a plpgsql function with `EXECUTE`:
For **Postgres 9.2 or older** (before `LATERAL` was implemented):
```
CREATE OR REPLACE FUNCTION f_unpivot_years92(_tbl regclass, VARIADIC _years int[])
RETURNS TABLE(id int, year int, value int) AS
$func$
BEGIN
RETURN ... | `PostgreSQL 9.3` offers as neat [JSON functions](http://www.postgresql.org/docs/9.3/static/functions-json.html) which can be used for such tasks without defining new functions or knowing a number of columns.
```
SELECT id, (k).key as year, (k).value as value FROM
(SELECT j->>'id' as id, json_each_text(j) as k
FR... | How to unpivot a table in PostgreSQL | [
"",
"sql",
"postgresql",
"pivot",
"dynamic-sql",
"unpivot",
""
] |
Consider the following output:
```
ObjectNumber Field1 Field2 Field3
------------------------------------
1 1 0 0
1 0 0 1
2 0 0 0
2 1 0 0
2 0 1 1
```
I need to "merge" these rows into 1... | In this case both max() en sum() will work, but sum() seems more appropriate since you say that the output is 'adding up all the fields'.
```
SELECT ObjectNumber,
sum(Field1) AS Field1,
sum(Field2) AS Field2,
sum(Field3) AS Field3
FROM youroutput t
GROUP BY ObjectNumber;
``` | Just use an aggregation query with `max()`:
```
select ObjectNumber, max(Field1) as Field1, max(Field2) as Field2, max(Field3) as Field3
from youroutput t
group by ObjectNumber;
``` | Merge multiple rows into 1 | [
"",
"sql",
"sql-server",
"sql-server-2008",
""
] |
[Summary of the question: 2 SQL statements produce same results, but at different speeds. One statement uses `JOIN`, other uses `IN`. `JOIN` is faster than `IN`]
I tried a 2 kinds of `SELECT` statement on 2 tables, named *booking\_record* and *inclusions*. The table *inclusions* has a many-to-one relation with table *... | This behavior is well-documented. See [here](http://dev.mysql.com/doc/refman/5.6/en/subquery-optimization.html).
The short answer is that until MySQL version 5.6.6, MySQL did a poor job of optimizing these types of queries. What would happen is that the subquery would be run each time for every row in the outer query.... | EXPLAIN should give you some clues ([Mysql Explain Syntax](http://dev.mysql.com/doc/refman/5.0/en/explain.html)
I suspect that the IN version is constructing a list which is then scanned by each item (IN is generally considered a very inefficient construct, I only use it if I have a short list of items to manually ent... | MySQL(version 5.5): Why `JOIN` is faster than `IN` clause? | [
"",
"mysql",
"sql",
"join",
""
] |
I have a query where I am trying to select the contents of another row and insert it into the table but changing particular values. Inside this I am trying to use a `Replace()` function to replace certain characters in the given column.
Is this correct or will I need to take this out and do this via an `Update` statem... | This looks correct to me and should do what you are wanting to do. But is there some reason why you simply can't try this yourself and check the results?
If Column3 is a data type of 'Text', this isn't going to work since Replace doesn't work on that data type. You could cast the data type is nvarchar(max) to make thi... | ```
INSERT INTO [dbo].[PurchaseLogic]
([column1]
,[column2]
,[column3]
,[column4])
SELECT [column1]
,[column2]
,CAST(REPLACE(CAST(column3 as Varchar(MAX)),'TextA','TextB') AS Text)
,[column4]
FROM dbo.purchaselogic
WHERE column1 = 1
```
I got the essense of it [here](... | SQL Server - Insert Select | [
"",
"sql",
"sql-server",
""
] |
The `service_option` table and the `room` table have a same column `room_key`, the `room` table and the `user` table share a same column `user_key`, what I want is obtaining user's infomation from service options.
```
SELECT user_key, user_id, user_status, user_company_name
FROM user
WHERE user_key
IN (
SELECT use... | This is probably the query you're looking for:
```
SELECT U.user_key
,U.user_id
,U.user_status
,U.user_company_name
FROM [user] U
INNER JOIN room R ON R.user_key = U.user_key
INNER JOIN service_option S ON S.room_key = R.room_key
AND S.service_option_key = 3
... | Do not use WHERE IN, but join :
```
SELECT u.user_key, u.user_id, u.user_status, u.user_company_name
FROM user u, room r, service_option so
WHERE u.user_key = r.user_key
AND r.room_key = so.room_key
AND so.service_option_key = 3
AND so.ordered_service_option_status != 0
``` | how to reconstruct this sql query | [
"",
"mysql",
"sql",
""
] |
I am have the following sequence of actions for users and a `DateTime`time stamp of each action.
Below is an example table
```
Actions:
+------------+-------------+----------------------+
| session_id | action_name | time |
+------------+-------------+----------------------+
| 123abcd | ADD ... | I think you probably want this:
```
select session_id,
min(time) as first_action_time,
min(case when action_name = 'EMAIL' then time end) as first_email_time,
timestampdiff(second,min(time),min(case when action_name = 'EMAIL' then time end)) as diff_in_secs
from actions
group by sessio... | You can do this with conditional aggregation:
```
select session_id,
timestampdiff(second, min(case when action_name = 'EMAIL' then action_time end),
min(action_time)) / 60
from actions a
group by session_id;
``` | MySQL get time duration up to a selected action | [
"",
"mysql",
"sql",
""
] |
I've been stuck on this issue for a while now. I'm really close I think, but there's something I'm missing.
A Transaction can have zero or many TransactionErrors. I am trying to display all Transactions only once, and I'm also trying to display only the latest error message if there is one.
```
SELECT [Transactio... | I have a similar solution to Krishnraj Rana. However, I think that you need to avoid having the rowid filter in the WHERE clause because that will make if behave like an inner join:
```
; with Errors as
(SELECT [ErrorMessage]
, Row_Number() over (Partition By TransactionId order by TransactionErrorId Desc) a... | You can achieve it by using **ROW\_NUMBER()** with **PARTITION BY** clause like this -
```
SELECT [Transaction].[TransactionID]
,[FileName]
,[DestinationSystem]
,[CreatedOn]
,LEFT([TransactionError].[ErrorMessage], 300) AS LatestErrorMessage --Gets only the first 300 characters of the error message
... | Display Only One Record That May Or May Not Have Children | [
"",
"sql",
"sql-server",
""
] |
I have an Item table:
```
ItemID ItemNumber CategoryID
----------------------------------
1 1 1
2 2 1
3 3 1
4 1 2
5 2 2
6 3 2
7 1 3
8 2 3
9 3 ... | You can try below query
```
select i.ItemNumber, c.GenreID, count(*)
from Item i, Category c
where i.CategoryID = c.CategoryID
group by i.ItemNumber, c.GenreID
having count(*) > 1
``` | You need to join the tables together and count the distinct genres per item. The resulting query is something like this, if I understand your problem correctly:
```
select i.itemnumber, count(distinct c.genreid) as numgenres
from items i join
categories c
on i.categoryid = c.categoryid
group by i.itemnumber
... | SQL count duplicate values across multiple tables | [
"",
"sql",
"sql-server",
""
] |
I am trying to select all the rows in which COLUMN has a value between 1 and 9. The problem is the datatype for COLUMN is text and I have used the following code to get those rows:
```
SELECT * FROM TABLE WHERE COLUMN BETWEEN '1' AND '9';
```
Instead of getting rows with COLUMN value between 1 and 9, I also get rows ... | For example like this:
```
SELECT * FROM TABLE WHERE COLUMN BETWEEN '1' AND '9' and LEN(COLUMN) = 1;
``` | If all of the values in the column are **guaranteed to be integers**™ you could do this:
```
SELECT * FROM TABLE WHERE CInt(COLUMN) BETWEEN 1 AND 9
``` | Using between operator with numeric text values in Microsoft Access SQL | [
"",
"sql",
"ms-access",
"between",
""
] |
I am having some trouble getting my SQL to run efficiently with an IN statement. If I run the two statements separately, and manually paste in the series of results (in this case there are 30 vendor\_id's) the vendor\_master query runs instantly, and the invoices query runs in about 2 seconds.
```
select * FROM invoic... | > *So what causes the HUGE slowdown, more than 60 seconds and often times out?*
The `IN` clause works well when the data set inside the `IN` condition is "small" and "deterministic". That's because the condition is evaluated *once* per row. So, assuming that the query in the `IN` clause returns 100 rows and the table ... | Prior to MySQL 5.6.6, `in` was optimized quite inefficiently. Use `exists` instead:
```
select *
FROM invoices i
where exists (select 1
from vendor_master vm
where i.vendor_id = vm.vendor_id and vm.vendor_master_id = 12345
);
```
For best performance, you want an index on `ven... | SQL IN Statement Slowness | [
"",
"mysql",
"sql",
""
] |
I have two tables:
Users:
```
id name isSpecial
1 Tal 1
2 Jorden 0
3 John 1
4 Paige 0
```
Details:
```
id userId Country zipCode
1 1 Israel 4564
2 3 US 554654
```
I want to ... | You can use a `LEFT JOIN`:
```
SELECT
u.id,
u.name,
u.isSpecial,
d.country,
d.zipCode
FROM Users u
LEFT JOIN Detals d
ON u.id = d.userId
WHERE u.name = 'Jorden'
OR u.isSpecial = 1
``` | Like this
```
SELECT u.id,u.name,d.country,d.zipCode FROM
Users u
LEFT outer JOIN Details d
ON u.id = d.userId
WHERE u.name = 'Jorden' OR u.isSpecial = '1'
``` | Select from two tables statment | [
"",
"mysql",
"sql",
""
] |
i have two sql statements
the first one
```
SELECT
course.CourseNum,
course.CourseName,
course.CreditHours
FROM course
WHERE course.TypeID=1
```
result is
```
Course Num------Course Name---------Credit Hours
1101----------Arabic Language----------3
... | You can do a left join and look for NULL. Also use table alias when possible to make the code more readable.
```
select
c.CourseNum,
c.CourseName,
c.CreditHours
from course c
left join studentcoursecomplete cc
on cc.CourseID = c.CourseID
and cc.SID = 1
where c.TypeID=1
and cc.CourseID is null
``` | Try this code. It should give your desired result.
```
SELECT course.CourseNum, course.CourseName, course.CreditHours
FROM course course left join
studentcoursecomplete studentcoursecomplete on
studentcoursecomplete.CourseID = course.CourseID and studentcoursecomplete.SID=1
where studentcoursecomplete.CourseID is nul... | how can i make this select statement | [
"",
"mysql",
"sql",
"join",
"except",
""
] |
I am having problem while understanding `=` and `is` operators in SQL Server.
Consider the following example queries which are having different behaviors in their respective output:
```
SELECT * FROM tableName WHERE colName IS NULL;
SELECT * FROM tableName WHERE colName = NULL;
```
First query will provide the r... | Nothing equals `null`.
Not even `null` equals `null`.
`null` is not a value, it is more like a concept, or a mark, meaning unknown value.
As such, you need two operators for this, one for equality, and one for checking the concept of `null`.
Once you start to think of `null` as "unknown value" a lot of the other be... | From <http://msdn.microsoft.com/en-us/library/ms188795.aspx>:
`To determine whether an expression is NULL, use IS NULL or IS NOT NULL instead of comparison operators (such as = or !=). Comparison operators return UNKNOWN when either or both arguments are NULL.`
**EDIT**
The originating question was updated to note t... | Difference between "=" and "is" in sql server | [
"",
"sql",
"sql-server",
""
] |
I'm trying generate a column based on the title of a table.
Is there a way to display the table name specified in the FROM clause in the query results?
Thanks | From the comments, it seems that you have multiple tables all with the same structure and similar names This is almost always a sign of poor database design. You should have a single table `LOAD_UNISTATS_ACCREDITATION` with a column for the year.
If you cannot change the database structure, then perhaps you can create... | The dynamic sql approach, where you could pass in a parameter with the table name (assuming it always has the same structure, length) would be something like this:
**Create Script:**
```
create table LOAD_UNISTATS_2013_ACCREDITATION (value1 int, value2 int)
insert into LOAD_UNISTATS_2013_ACCREDITATION (value1, value... | Display Table Name in Query Results; SQL Server 2008 | [
"",
"sql",
"sql-server",
"sql-server-2008",
"t-sql",
""
] |
My current query runs very slow when accessing a DB with pretty large tables
```
SELECT *
FROM table1
WHERE timestamp BETWEEN 635433140000000000 AND 635433150000000000
AND ID IN ('element1', 'element2', 'element3', ... , 'element 3002');
```
As you can see the `IN` clause has several thousand values. This query is... | Add the elements of the IN to an indexed temporary (if the elements change) or permanent table (if the elements are static) and inner join on them. | This is your query:
```
SELECT *
FROM table1
WHERE timestamp BETWEEN 635433140000000000 AND 635433150000000000 AND
ID IN ('element1', 'element2', 'element3', ... , 'element 3002');
```
The query is fine. Add an index on `table1(id, timestamp)`. | How can I make large IN clauses more efficient in SQL Server? | [
"",
"sql",
"sql-server",
"performance",
""
] |
Example Table:
```
a | b
-----
1 | 1
1 | 2
2 | 1
3 | 0
3 | 1
4 | 1
4 | 2
4 | 3
5 | 0
```
I'd like to get all `DISTINCT` values of column `a`, which are associated with values from column `b`, where `b = 1 AND b = 2`.
The result should be:
```
a
-
1
4
```
Does this work with `GROUP BY`? I tried the following SQL, b... | You are very close. Try this:
```
SELECT t.a
FROM table t
GROUP BY t.a
HAVING SUM(t.b = 1) > 0 AND SUM(t.b = 2) > 0;
```
Each of the `SUM()` conditions counts the number of rows where the condition is true. You want both, hence the `> 0` and `AND`.
**EDIT** removed `t.b` from `GROUP BY` | One way of doing it is as follows:
```
SELECT t.a
FROM table t
GROUP BY t.a
HAVING SUM(CASE WHEN b=1 THEN 1 ELSE 0 END) <> 0
AND SUM(CASE WHEN b=2 THEN 1 ELSE 0 END) <> 0
```
Note that you need to remove `t.b` from `GROUP BY`, otherwise the results would be incorrect.
[Demo.](http://www.sqlfiddle.com/#!2/39348/1) | Group By with multiple Having on the same field | [
"",
"mysql",
"sql",
"group-by",
"having",
""
] |
I have here an sql in which I need to select the id of a user and the status value in the table.
Here is my sql:
```
SELECT *
FROM user
WHERE user_id='".$id."'
AND status='add'
OR status='delete'
```
But then, the outcome is not what I want because it also show the other `id` that has a status value of `dele... | Organize your query so that user id condition will not be disturbed by your multiple OR's
```
SELECT * FROM user
WHERE user_id='".$id."'
AND (status='add' OR status='delete')
```
Or use in
```
SELECT * FROM user
WHERE user_id='".$id."'
AND status IN('add','delete')
``` | Here the query you're looking for:
```
SELECT *
FROM user U
WHERE U.user_id = '".$id"'
AND U.status IN ('add', 'delete')
```
The use of `IN` clause is highly recommended instead of multiple `OR` conditions for the same column.
Hope this will help you. | How to get 2 values from the same table with a parameter of id | [
"",
"mysql",
"sql",
""
] |
I have 2 tables: `item_status_log` and `items` with the following structure:
```
items(itemid, status, ordertype)
item_status_log(itemid, date_time, new_status, old_status)
```
Basically, when the `status` is changed in my program, a record is logged in the `item_status_log` with the `old_status`, the `new_status`, ... | I think you just need conditional aggregation:
```
select to_char(date_time, 'MM-DD-YYYY') as "Shipment Date", count(*) as "TOTAL Items",
sum(case when i.ordertype = 'ORDER' then 1 else 0 end) as NumOrders,
sum(case when i.ordertype = 'INVENTORY' then 1 else 0 end) as NumInventory
from item_status_log il... | Try:
```
select to_char(date_time, 'MM-DD-YYYY') as "Shipment Date",
count(*) as "TOTAL Items",
sum(case when ordertype = 'INVENTORY' then 1 else 0 end) as "Inventory",
sum(case when ordertype = 'ORDER' then 1 else 0 end) as "Ordered"
from item_status_log i
where old_status = 'ONORDER'
group b... | subquery uses ungrouped column "i.date_time" from outer query | [
"",
"sql",
"subquery",
""
] |
I have the following four tables in SQL Server 2008R2:
```
DECLARE @ParentGroup TABLE (ParentGroup_ID INT, ParentGroup_Name VARCHAR(100));
DECLARE @ChildGroup TABLE (ChildGroup_id INT, ChildGroup_name VARCHAR(100), ParentGroup_id INT);
DECLARE @Entity TABLE ([Entity_id] INT, [Entity_name] VARCHAR(100));
DECLARE @Child... | I believe this can be accomplished using [partitioning](http://msdn.microsoft.com/en-us/library/ms189461%28v=sql.100%29.aspx) and [ranking](http://msdn.microsoft.com/en-us/library/ms189798%28v=sql.100%29.aspx) functions like this:
```
SELECT ParentGroup_Name, ChildGroup_name, [Entity_name],
999 + DENSE_RANK() OVE... | You can solve this by using [**ranking functions**](http://msdn.microsoft.com/en-us/library/ms189798.aspx)
```
SELECT ParentGroup_Name, ChildGroup_name, [Entity_name],
899 + DENSE_RANK() OVER(PARTITION BY ParentGroup_Name ORDER BY ChildGroup_name) +
100 * DENSE_RANK() OVER(ORDER BY ParentGroup_Name ASC) ... | SQL server: calculate sequence in a SQL query | [
"",
"sql",
"sql-server",
"sql-server-2008",
"t-sql",
"sql-server-2008-r2",
""
] |
I am new to SQL programming and have the following scenario.
I have three tables which are linked to each other as -
**ForceInstance**
```
ForceInstanceID (PK)
ForceID (FK to Force)
Description
CreatedBy
CreatedOn
```
**Force**
```
ForceID (PK)
ForceTypeID (FK to ForceType)
Description
CreatedBy
CreatedOn`
```
**F... | ```
Select * from ForceInstance FI
inner join Force F on FI.ForceID = F.ForceID
inner join ForceType FT on F.ForceTypeID = FT.ForceTypeID
``` | ```
SELECT *
FROM ForceInstance FI
INNER JOIN Force F
ON FI.ForceID = F.ForceID
INNER JOIN ForceType FT
ON F.ForceTypeID = FT.ForceTypeID
``` | Inner Join on three tables linked by foreignkeys | [
"",
"sql",
"sql-server",
"t-sql",
""
] |
I'm trying run basic Insert sql query.
Here is the insert sql.
```
Insert into tblABC( X1,X2,X3)
Select X1,X2,X3 from tblXX
```
Problem is `tblXX` doesn't have `X3` column.
Sometimes `X3` will be there and sometimes it will be missing. When column is missing then push a default value such as `0`.
Trying to use Ca... | You can try the following:
```
if (exists (select 1 from information_schema.columns where table_name = 'tblXX' and column_name = 'X3'))
begin
Insert into tblABC(X1, X2, X3)
Select X1, X2, X3
from tblXX;
end
else
begin
Insert into tblABC(X1, X2, X3)
Select X1, X2, 0
from tblXX;... | I'm not sure about what you're looking for, if you just want to fill the table `tblABC` with data from table `tblXX` that have no value for the third column, here is the query that use a default value:
```
INSERT INTO tblABC(X1, X2, X3)
SELECT T.X1
,T.X2
,0
FROM tblXX T
```
If you just want to use a default v... | SQL Insert query with missing column and Invalid column name | [
"",
"sql",
"sql-server",
"sql-server-2008",
""
] |
I need to Update these NULL Values:
```
PK | CODE
---+-------
1 | 20
2 | NULL
3 | NULL
4 | 30
5 | NULL
6 | NULL
7 | NULL
8 | 40
9 | NULL
```
Like this:
```
PK | CODE
-----+------------
1 | 20
2 | 20
3 | 20
4 | 30
5 | 30
6 | 30
7 | 30
8 | ... | You can do this as:
```
UPDATE TT
SET CODE = (SELECT TOP 1 CODE
FROM #TSPV_TEMP T2 with(nolock)
WHERE T2.KEY < tt.KEY AND
CODE IS NOT NULL
ORDER BY KEY DESC
)
FROM #TSPV_TEMP TT with (nolock)
where tt.CODE IS NULL;
```
N... | Another way using a derived table which for every pk with a null code contains the maximum lesser pk with a non-null code.
```
update t1
set t1.code = t3.code
from tt t1 join
(select t1.pk, max(t2.pk) max_pk
from tt t1
join tt t2 on t1.pk > t2.pk
and t2.code is not null
and t1.code is null
grou... | Update based on previous value SQL SERVER 2005 | [
"",
"sql",
"sql-server",
"sql-server-2005",
"sql-update",
"logic",
""
] |
I need to update a table every time a certain action is taken.
**MemberTable**
* `Name varchar 60`
* `Phone varchar 20`
* `Title varchar 20`
* `Credits int` <-- **the one that needs constant updates**
* etc with all the relevant member columns 10 - 15 total
Should I update this table with:
```
UPDATE Members
SET C... | I know that this doesn't directly answer the question but I'm going to throw this out there as an alternative solution.
Are you bothered about historic transactions? Not everyone will be, but in case you or other future readers are, here's how I would approach the problem:
```
CREATE TABLE credit_transactions (
me... | Actually the later way would be faster.
If your number transaction is very huge, to the extent where millisecond precision is very important, it's better to do it this way.
Or maybe some members will not have credits, you might save some space here as well.
However, if it's not, it's good to keep your table structur... | Which SQL Update is faster/ more efficient | [
"",
"sql",
"sql-server",
""
] |
Is there a convenient way to use the ARRAY\_CONTAINS function in hive to search for multiple entries in an array column rather than just one? So rather than:
```
WHERE ARRAY_CONTAINS(array, val1) OR ARRAY_CONTAINS(array, val2)
```
I would like to write:
```
WHERE ARRAY_CONTAINS(array, val1, val2)
```
The full probl... | There is a UDF [here](https://github.com/klout/brickhouse/blob/master/src/main/java/brickhouse/udf/collect/ArrayIntersectUDF.java) that will let you take the intersection of two arrays. Assuming your values have the structure
```
values_array = [val1, val2, ..., valn]
```
You could then do
```
where array_intersecti... | ```
Create table tmp_cars AS Select make,COLLECT_LIST(TRIM(model))
model_List from default.cars GROUP BY make;
Select array_contains(model_List,CAST('Rainier' as varchar(40)))
FROM Default.tmp_cars t
where make = 'Buick';
```
Data
[" Rainier"," Rendezvous CX"," Century Custom 4dr"," LeSabre Custom 4dr"," Regal LS ... | ARRAY_CONTAINS muliple values in hive | [
"",
"sql",
"hive",
""
] |
this is the table structure,
```
id int
name varchar
insert_date date
update_date TIMESTAMP
```
Now here the idia is , **insert\_date** will be able to insert by defult current time & the update\_date it will insert current time in each edit or insert it will update it.
so how i could mak... | you may use `NOW()` function in you respective fields | If you want to add only time .. you need to use
CURTIME()
AND if you want current date and time...
NOW()
If you want only current date....
CURDATE()
for more here..
The following SELECT statement:
SELECT NOW(),CURDATE(),CURTIME()
will result in something like this:
NOW() CURDATE() CURTIME()
2008-11-11 12:45:34 ... | mysql insert current date, only in insert time | [
"",
"mysql",
"sql",
""
] |
I have two tables:
* Table 1 with columns `Number` and `TEXT`
* Table 2 with columns `Number` and `TEXT`
Now Table 1 has `Nr = 12345AB` and Table 2 `Nr = 00012345AB`
How can I find all columns from **Table 1** that are not in **Table 2**? | Try this select:
```
select
*
from
table1 t1
left join table2 t2 on t1.number=t2.number
where
t2.number is null
``` | Try ***exists***:
```
select t1.*
from Table1 t1
where not exists (select 1
from Table2 t2
where t2.Number = t1.Number)
``` | Search for same Values in two SQL TABLES | [
"",
"sql",
""
] |
I need to parse row (with spaces) into two different columns in SQL. The rows look like that:
**FullName**
John Mayer
Rajon Jennings
Donna Fraye
Michael Moore
So the expected result is :
**Name**
John
Rajon
Donna
Michael
**Surname**
Mayer
Jennings
Fraye
Moore
How can i do that in SQL? | If you have a requirement like First Name should be string before first space and rest everything what follows should go as Last name , you can update two columns as:
```
Update T
Set T.FirstName = Left(ltrim(rtrim(FullName)), CHARINDEX(' ',ltrim(rtrim(FullName))))
,T.LastName = Right(ltrim(rtrim(FullName)),len(... | You can use a split function.This function must be created.
Here are some examples :
<http://ole.michelsen.dk/blog/split-string-to-table-using-transact-sql/>
[Split function by comma in SQL Server 2008](https://stackoverflow.com/questions/20512855/split-function-by-comma-sql-server-2008) | How to parse a row in SQL into columns (separator-spaces) | [
"",
"sql",
"sql-server",
"function",
"parsing",
"row",
""
] |
I've got the following table in a Postgres database:
Table **Example**:
```
---------------------------
name | number
---------------------------
DefaultName | 1
DefaultName | 2
DefaultName | 3
DefaultName | 4
Charlie | 1
Charlie | 3
Charlie | 4
Charlie ... | I would generate the whole range per name and `LEFT JOIN` to the base table to eliminate the present ones:
```
SELECT n.name, nr.number
FROM (
SELECT DISTINCT name
FROM example
WHERE name <> 'DefaultName'
) n -- all names except 'DefaultName'
CROSS JOIN (
SELECT number ... | It will take a few passes, select default, group names that aren't default, then left join and check for null values. Check the [SQLFiddle](http://sqlfiddle.com/#!15/689d0/1) Example.
```
select Names.name, DefaultConfigs.number
from Example DefaultConfigs
cross join (
select name
from Example
where name... | JOIN using negation clauses | [
"",
"sql",
"postgresql",
""
] |
Here is my table
Table Suppliers in Database A
```
ID(AUTONUMBER) | SupplierCode(Unique) | SupplierName
001 supp001 TestA
002 supp002 TestB
003 supp003 TestC
```
Table Suppliers in Database B
```
ID(AUTONUMBER) | SupplierCode(Unique... | Might as well make it an answer
```
insert into databaseB..suppliers
Select * from databaseA..suppliers where id not in (select id from databaseB..suppliers)
```
The table references should be correct, but I can't verify. You might want to go databasea.dbo.suppliers if that's the correct full name | Assuming the two databases are on the same server and both tables are part of the "dbo" schema, inserting only those records in the A table that don't already exist in B into the B table can be handled like this:
```
INSERT INTO DatabaseB.dbo.Suppliers
SELECT ID,SupplierCode, SupplierName FROM DatabaseA.dbo.Suppliers... | How to Insert from one table to another table from difference Database | [
"",
"sql",
"sql-server",
""
] |
Hello I am so good with sql so I need your help.
I have one table called property. Now I want to retrieve rows with different value in same field. I tried with **LIKE** and **AND** but not getting any result.
**TABLE:**
```
id user_id title approved
-- ------- ----- --------
1 60 one ... | with `title like '%one%' AND title like '%two%'` you looks for a title that have "one" and "two" together. and you want some with "one" OR "two"
```
SELECT *
FROM `property`
WHERE `user_id` =60
AND `approved` =1
AND (`title` like '%one%' OR `title` like '%two%')
``` | You have to use
> OR or ||
condition. You are using LIKE condition to retrieve result.
That will retrieve If title have SIXTYONE also.
Because SIXTYONE contains "ONE" word. If you exactly looking for that, use LIKE as your post mentioned. else You should use =(equal to) for exact result. who having title "ONE" only... | Select rows with different value in same filed | [
"",
"mysql",
"sql",
""
] |
I'm trying to return NOT NULL and NULL as the result of a CASE statement but I can't find the right way to do it
What I have below is incorrect and underlines the `NOT` keyword
```
SELECT ROW_NUMBER() OVER ( ORDER BY d.cnumber DESC) AS RowNum,
d.cnumber,
d.firstname,
d.lastname,
d.current_email,
... | Using a `case` in a `where` clause is usually an indication you've taken the wrong path. I believe that you'll find you can solve this with more standard logic:
```
WHERE (@query in ( 'UNSUBMITTED', 'SUBMITTED')
OR (@query = 'OPTEDIN' AND d.optedin = 1)
OR d.optedin = 0)
AND
(@query in ... | I suggest you modify the condition for d.activated to this:
```
AND (@query = 'UNSUBMITTED' AND d.activated IS NULL OR @query <> 'UNSUBMITTED' AND d.activated IS NOT NULL)
```
Please note that you do not need to specifically test for this condition:
```
CASE WHEN @query = 'OPTEDIN' OR @query = 'OPTEDOUT'
... | SQL Case NOT NULL as value | [
"",
"sql",
"sql-server",
""
] |
I am doing some data mapping and out of my 15 columns on 5 will have data the rest will be empty. When I export my fie as csv my columns that have no data return comas. My vendor needs those trailing comas removed. I tried using trim on one of the colmns and that did not work. sample
sample :
> Clientid,schoolc,schna... | There is very likely a much better approach to get the formatting you're after, but assuming that
-the first five columns will have some data with length >=1
-two commas together indicates the beginning of the end (of the line at least)
you can handle each line/row of data individually in a manner similar to t... | **See this example**:
```
CREATE FUNCTION [dbo].[ufn_TrimLeadingCharacters_reversed] ( @Input VARCHAR(50), @LeadingCharacter CHAR(1) )
RETURNS VARCHAR(50)
AS
BEGIN
RETURN reverse(REPLACE(LTRIM(REPLACE(reverse(@Input), ISNULL(@LeadingCharacter, '0'), ' ')),
' ', ISNULL(@LeadingCharacter, '0')))
... | remove trailing commas using sql | [
"",
"sql",
""
] |
I got the following statement:
```
SELECT XYZ FROM ABC WHERE ID IN (123)
```
At the moment I made the 123 as a configuration parameter in a separate table:
```
SELECT XYZ FROM ABC WHERE ID IN (SELECT CONTENT FROM c_configuration WHERE IDENTIFIER = "ID")
```
Now the content from the c\_configuration parameter change... | try out the following code:
```
SELECT XYZ
FROM ABC
WHERE ID IN
(
SELECT DISTINCT TO_NUMBER(REGEXP_SUBSTR(CONTENT,'[^,]+', 1, level))
FROM c_configuration
WHERE IDENTIFIER = 'ID'
CONNECT BY REGEXP_SUBSTR(CONTENT, '[^,]+', 1, level) IS NOT NULL
)
```
* [SQLFiddle Demo](http://sqlfiddle.com/#!4/d2330/1) | You'll have to split up the csv value or use dynamic sql. | WHERE IN with column content | [
"",
"sql",
"plsql",
""
] |
This is the function which I designed. It got complied successfully
```
CREATE OR REPLACE FUNCTION "F_CHECK"
(
p_id IN VARCHAR2
p_name IN VARCHAR2)RETURN VARCHAR2
is
v_id VARCHAR2;
v_name VARCHAR2;
cnt pls_integer;
BEGIN
IF id IS NULL THEN
RETURN NULL;
END IF;
... | One of the possible causes of exceptions that you will get when you run this code is: If your select into didn't return a value, you will get an exception, an nu-handled exception
Even though you have a return NULL in the end of the function, but still you need to catch all the exceptions that might occur
The area wh... | You must return a value when the execution flow reaches (around line 22)
```
...
else
insert into employees values(p_id,p_name,sysdate);
end if;
...
```
In this case, the function does not return a value which is expected by the caller, hence the error.
You can instruct the PL/SQL compiler to warn you about such c... | Function returned without value | [
"",
"sql",
"oracle",
"plsql",
""
] |
I feel my problem is very complicated.
I have a Table A with a column named AbsenceLinks.
The table would look like this:
- - - - - - - - - - - - - - - - - - - - - - - - - - - -
| **Description** | **AbsenceLinks** |
|- - - - - - - - - - - - - + - - - - - - - - - - - - - -|
| Illness ... | With help from Jaugar Chang I found out the solution to my problem. The code below will show the following result:
**\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_**
| **Description** | **AbsenceLinks** |
|- - - - - - - - - - - - - - + - - - - - - - - - - - - |
| Education ... | ## UPDATE: Method with substring and join only.
There is a similar question [expand-comma-separated-values-into-separate-rows](https://stackoverflow.com/a/703125/3630826) answered by @KM. we could reference.
Your case is a little different from that one. You should take all the parts within some spaces before and a s... | How to extract and split IDs from nvarchar column surrounded by spaces and a slash to compare to other table's value | [
"",
"sql",
"sql-server-2008",
""
] |
I have a table that contains Phone# like this:
```
Phone#
------------------
1234567890
2548796584
9999
2126543133
9999999999
999999
999
9853
9999999
```
Now I want a query that will return rows having only number 9 in it, in this case result should be.
```
Phone#
------------------
9999
9999999999
999999
999
999999... | Here is a much simpler way than using CLR for this. The reason this like pattern works is we are finding rows that not like NOT 9. The carrot ( ^ ) in RegEx means NOT.
```
create table #Phones
(
Num varchar(20)
)
insert #Phones
select '1234567890' union all
select '2548796584' union all
select '9999' union all
se... | You can use a query like this:
```
select * from Phones
where 1 = dbo.RegExpLike(number, '^9+$')
```
You can check more examples about using regex here:
<http://www.codeproject.com/Articles/42764/Regular-Expressions-in-MS-SQL-Server> | SQL Server Regex Select | [
"",
"sql",
"sql-server",
"regex",
"sql-server-2008",
""
] |
I am working on a project, and need to join results from 2 tables into one set.
The tables are ordered as such:
```
gameData: [Id,TeamID, data..........]
players: [Id (same as above), name, data.....]
```
I need to do something like:
```
SELECT * FROM gameData and SELECT data FROM players WHERE gameData.Id = player... | ```
Select a.Id, a.TeamID, a.data, b.data
FROM gameData as a
LEFT OUTER JOIN
players b On a.ID = b.ID
``` | You could enumerate the fields that you select and alias the tables, like:
```
select a.Id, a.TeamId, a.data, b.data
from tableA a
join tableB b on a.Id = b.Id
``` | Please help - SQL Join query | [
"",
"sql",
"sqlite",
""
] |
i am trying the below query but i am getting error like incorrect syntax at SqlDataReader reader = command.ExecuteReader .. please correct me where i am wrong
```
string querystring = "SELECT ImageName FROM dbo.ProfilePic WHERE UserName = @UserName & IsActive = 'Y' order by ID Desc";
SqlCommand command = n... | SQL doesn't need the double equal signs.
```
SELECT ImageName FROM dbo.ProfilePic WHERE Username = @UserName
``` | in `SQL` you don't need to use double equal sign to compare values and `&&` is wrong, then this is wrong:
```
string querystring = "select ImageName from dbo.ProfilePic where UserName == @UserName && IsActive == 'Y' order by ID descending";
```
and this is true:
```
string querystring = "select ImageName from dbo.Pr... | sql query error incorrect syntax | [
"",
"sql",
""
] |
I am trying to create a view that will point to the most recent version of a table. For instance, if there are two tables, tblZipCode2014 and tblZipCode2013, I would want the view to return everything in tblZipCode2014. Then, if a new table called tblZipCode2015 is created the view would return everything in tblZipCode... | Why are you storing similar data in multiple tables?
You should have one table `tblZipCode` that has a column for the year. Then you could just do:
```
create view v_tblZipCode
select *
from tblZipCode
where year = (select max(year) from tblZipcode);
```
(The subquery would actually be fast using an inde... | This is not possible to do in a view. You cannot make a table name dynamic in a select statement unless you are using dynamic sql and you cannot use dynamic SQL in a view, because you cannot use the exec command.
You might try something like this instead:
* Create a table called tblZipCodeCurrent (create a synonym or... | Creating a view which references the most recent version of a table? | [
"",
"sql",
"sql-server",
""
] |
I am sure this questions has been answered before, but I have no idea what to search for.
I have 2 tables (coming from Wordpress), Users and User Meta Data. I need to create a query that takes the Meta Data and includes that with the other user data. I am developing independent solution in MS Access that will use WP d... | Thanks so much for @GolezTrol for pointing me in the right direction. I did need to pivot the data. I searched and Access has this feature. I created a "cross-tab query." Here is the query in case anyone else has the same problem.
```
TRANSFORM Last(meta.meta_value) AS LastOfmeta_value
SELECT meta.[user_id], Last(meta... | You are probably looking for *pivot table*, which is a slow and complex process in MySQL.
If you like to read more about that, you can read [this question](https://stackoverflow.com/questions/7674786/mysql-pivot-table).
But since you seem to have exactly two fields, maybe a join will do just fine for you.
To do it wit... | Database Query - One to Many | [
"",
"sql",
"ms-access",
""
] |
I have a stored procedure with a nested query that checks whether "`category`" from the main table matches a "`category`" in a sub table.
So there can either be one match or none.
How can I return Yes if there is a match and the sub query returns something and No if there is no match and the sub query returns nothing ... | If subquery doesn't return any rows then your result will be NULL. Thus you need to check it. In SQL Server you can do this by using functions [`ISNULL`](http://msdn.microsoft.com/en-us/library/ms184325.aspx) and [`COALESCE`](http://msdn.microsoft.com/en-us/library/ms190349.aspx), it depends on version that you're usin... | ```
SELECT A.categoryID,
A.category,
A.[description],
(
SELECT
case
when count(subscribed) > 0 then 'Yes'
else 'No'
end
FROM MOC_Categories_Subscribers D
... | How to return Yes or No if nested query has result or not in SQL Server? | [
"",
"sql",
"sql-server",
"stored-procedures",
"subquery",
""
] |
I would like to do a SQL request like this :
```
SELECT p.ID, p.post_title
FROM ".$wpdb->prefix."posts AS p
INNER JOIN ".$wpdb->prefix."postmeta pm
ON pm.post_id=p.ID AND pm.meta_key='shops_list'
INNER JOIN ".$wpdb->prefix."follow AS f
ON pm.meta_value LIKE CONCAT('%',f.shop_followed_id,'%')
```
`shop_followed_id` is... | looks to me you got the like backwards. try:
```
INNER JOIN ".$wpdb->prefix."follow AS f
ON f.shop_followed_id LIKE CONCAT('%',pm.meta_value,'%')
``` | Use Casting for the f.shop\_followed\_id.
CONCAT('%',CAST(f.shop\_followed\_id As VARCHAR),'%')
May be this work | SQL concat with columns name | [
"",
"mysql",
"sql",
"concatenation",
""
] |
I am an SQL newby and I'm struggling with the following (simplified) Query.
It must extract an Account number from a master file (Master) and the associated transactions from a Current table (nTrans) and a History table (nTransArc) using the common Account number fields. This works fine.
The part I can't get to work ... | my best guess:
```
SELECT
m.MAccNo,
t.TranCode,
v.TaxCode,
vt.taxcode
FROM
Master m inner JOIN
(SELECT
AccNo,TranCode
FROM
nTrans
UNION ALL
SELECT
AccNo,TranCode
FROM
nTransArc) t ON
m.MAccNo = t.TAccNo INNER JOIN
(select
... | As I read your question I believe the following will get you what you want:
```
SELECT m.MAccNo
, t.TAccNo
, t.TranCode
, v.VTranCode
, v.TaxCode
FROM Master m
INNER JOIN nTrans t ON t.TAccNo = m.MAccNo
INNER JOIN VatTrans v ON v.VTranCode = t.TranCode
UNION ALL
SELECT m.MAccNo
, t.TAccNo
,... | SQL Server: multiple SELECTs in a single query | [
"",
"sql",
"sql-server",
""
] |
This is my first question since every question I have ever had has already had an answer on here. please forgive the poor formatting.
The query runs in 1ms by itself which is great. It produces about 600,000 results from about 3 million entries while the database is getting inserted into about 10 per second. I know th... | Just to make sure your database is properly configured to process this kind of workload, run the open source tool mysqltuner and look at the suggestions.
Your problem description sounds like you possibly want different tmp\_table\_size and max\_heap\_table\_size in my.cnf
You can find the tool here:
<https://raw.gith... | One thing jumps up and smacks me in the face here:
```
WHERE timestamp LIKE '2014-08-29%' /* slow! */
```
This defeats the use of the index on the `timestamp` column, because it implicitly casts `timestamp` to a string.
Try using this instead:
```
WHERE timestamp >= '2014-08-29'
AND timestamp < '2014-08-29' + I... | MySQL query slows way down when inserting into file | [
"",
"mysql",
"sql",
"performance",
"optimization",
"query-optimization",
""
] |
I frequently used `integer = ANY(integer[])` syntax, but now ANY operator doesn't work. This is the first time I use it to compare a scalar with an integer returned from CTE, but I thought this shouldn't cause problems.
My query:
```
WITH bar AS (
SELECT array_agg(b) AS bs
FROM foo
WHERE c < 3
)
SELECT a FROM f... | Based on the error message portion `operator does not exist: integer = integer[]`, it appears that the `bs` column needs to be `unnest`ed, in order to get the right hand side back to an `integer` so the comparison operator can be found:
```
WITH bar AS (
SELECT array_agg(b) AS bs
FROM foo
WHERE c < 3
)
SELECT a
... | without unnest
```
WITH bar AS (
SELECT array_agg(b) AS bs
FROM foo
WHERE c < 3
)
SELECT a FROM foo WHERE ( SELECT b = ANY (bs) FROM bar);
``` | Operator does not exist: integer = integer[] in a query with ANY | [
"",
"sql",
"postgresql",
""
] |
I have a table in SQLite
```
/* Create a table called NAMES */
CREATE TABLE EVENTS(Id integer , Eventtype integer,value integer,Timestamp DATETIME);
/* Create few records in this table */
INSERT INTO EVENTS VALUES(1,2,1,'2009-01-01 10:00:00'); --ROW1
INSERT INTO EVENTS VALUES(1,2,2,'2007-01-01 10:00:00'); --ROW2
IN... | In SQLite 3.7.11 or later, you can use GROUP BY with MAX() to select which row in a group to return:
```
SELECT *, MAX(timestamp)
FROM events
GROUP BY id, eventtype
```
In earlier versions, you have to look up some unique ID of the largest row in a group with a subquery (as in you answer). | I'm a bit late to this question, but I wasn't satisfied with the current answers as they mostly use [correlated subqueries](https://en.wikipedia.org/wiki/Correlated_subquery) which can seriously ruin performance.
In many situations, single-column analytical functions can simulated using a standard join:
```
SELECT e.... | SQLITE equivalent of ROW_NUMBER | [
"",
"sql",
"sqlite",
"greatest-n-per-group",
""
] |
I have a temp table where i have changed some values in the database and am trying to nsert these back into the real table but it is not working I have this below:
```
SELECT * INTO dbo.PackageProduct FROM #PackageP
```
where #PackageP is my temp table
I am getting this error after the second run:
```
There is alre... | If the table already exists you have to use `INSERT` as `SELECT...INTO` creates a new table:
```
INSERT dbo.PackageProduct (<columns...>)
SELECT (<columns...>) FROM #PackageP
``` | TRY
```
INSERT INTO dbo.PackageProduct SELECT * FROM #PackageP
``` | Insert contents from #Temp table into real table | [
"",
"sql",
"sql-server",
"ssms",
""
] |
I'm having a trouble with something that looks like simple thing. I'm trying to find first row that satisfies WHERE part of query and UPDATE it.
```
UPDATE Donation SET Available=0 WHERE Available != 0 and BloodGroup='" + bloodGroup + "' LIMIT 1"
```
bloodGroup is variable that gets filled automatically using C# and ... | Because C# is often used with SQL Server, perhaps the question is mistagged. The syntax looks fine for MySQL.
In SQL Server, you can do this as:
```
UPDATE TOP (1) Donation
SET Available = 0
WHERE Available <> 0 AND BloodGroup = 'AB-';
```
Note that this chooses an arbitrary matching row, as does your origin... | Can you try it? way of getting row\_number
```
UPDATE Donation d1 join (SELECT id,(SELECT @Row:=0) as row,(@Row := @Row + 1) AS row_number FROM Donation where Available <> 0 AND BloodGroup='AB-') d2
ON d1.id=d2.id
SET d1.Available='three'
WHERE d1.Available <> 0 AND d1.BloodGroup='AB-' AND d2.row_number='1'
``` | Update first row in SQL using LIMIT | [
"",
"mysql",
"sql",
"limit",
""
] |
I have a column stop\_execution\_date in sysjobactivity table. I need to get details of job only which ran after 4:10 AM.
I tried it using
```
cast(DATEPART(hour, sja.stop_execution_date) as varchar)+cast(DATEPART(minute, sja.stop_execution_date) as varchar) >410
```
But, if job completes at 9:05 AM it is not ac... | How about:
```
(DATEPART(hour, sja.stop_execution_date) = 4 and (DATEPART(minute, sja.stop_execution_date) > 10)
OR DATEPART(hour, sja.stop_execution_date) > 4
``` | Could cast as a time.
```
cast(sja.stop_execution_date as time) > '04:10:00.0000000'
``` | How can I compare only hour and minute in sql | [
"",
"sql",
"sql-server",
"sql-server-2008",
"t-sql",
"sql-server-2008-r2",
""
] |
This is my table/ source data,
```
|---------------------------------------------------|
|ID | DT | DAY | ATTENDANCE |
|-------+---------------+-----------+---------------|
|89 | 2014-08-23 | NULL | 1 |
|90 | 2014-08-24 | Sunday | NULL |
|91 | 2014... | @HHH, I added another temp table around @TAB. This works, Please test it and tell.
```
DECLARE @TAB2 TABLE (MASTERID INT IDENTITY(1,1),ID INT,DT DATE,DAY VARCHAR(15),ATTENDANCE BIT)
INSERT INTO @TAB2
SELECT * FROM @TAB WHERE DAY IS NULL
SELECT Y.*,
LU2.Streak
FROM @TAB Y LEFT JOIN (
SELECT X.ID, X.MASTER... | Like said Gordon, you need to identify groups of consecutive attendace day. But this is another version..
```
select
t.*,
t2.Seq,
(case ATTENDANCE
when 1 then ROW_NUMBER() over (partition by t2.Seq,t.attendance order by t.id)
when 0 then 0
else null end) Streak
from
@TAB t
outer apply
(select
count(1) as Seq
fr... | Calculate Running count in SQL Server excluding certain rows | [
"",
"sql",
"sql-server",
"t-sql",
"sql-server-2012",
""
] |
I am trying to understand how to UPDATE multiple rows with different values and I just don't get it. The solution is everywhere but to me it looks difficult to understand.
For instance, three updates into 1 query:
```
UPDATE table_users
SET cod_user = '622057'
, date = '12082014'
WHERE user_rol = 'student'
AN... | You can do it this way:
```
UPDATE table_users
SET cod_user = (case when user_role = 'student' then '622057'
when user_role = 'assistant' then '2913659'
when user_role = 'admin' then '6160230'
end),
date = '12082014'
WHERE user_role ... | MySQL allows a more readable way to combine multiple updates into a single query. This seems to better fit the scenario you describe, is much easier to read, and avoids those difficult-to-untangle multiple conditions.
```
INSERT INTO table_users (cod_user, date, user_rol, cod_office)
VALUES
('622057', '12082014', 'stu... | UPDATE multiple rows with different values in one query in MySQL | [
"",
"mysql",
"sql",
"sql-update",
""
] |
I have two tables with similar column names and I need to return records from the left table which are not found in the right table? I have a primary key(column) which will help me to compare both tables. Which join is preferred? | If you are asking for T-SQL then lets look at fundamentals first. There are three types of joins here each with its own set of logical processing phases as:
1. A `cross join` is simplest of all. It implements only one logical query processing phase, a `Cartesian Product`. This phase operates on the two tables provided... | Try This
```
SELECT f.*
FROM first_table f LEFT JOIN second_table s ON f.key=s.key
WHERE s.key is NULL
```
For more please read this article : [Joins in Sql Server](https://medium.com/@CodAffection/complete-guide-on-joins-in-sql-server-726a76a1274d)
[ you can select the number of Students
```
SELECT MAX(t_course.NAME) AS Course_name, COUNT(t_enrolment.student_fk) AS Count_students
FROM t_course
LEFT JOIN t_enrolment ON t_enrolment.course_fk = t_... | You need a select statement with a join to the couse table (for the `Course_name`). Group by `'t_course'.name` to use the `COUNT(*)` function
this will work:
```
SELECT COUNT(*) AS Count_students, c.NAME AS Course_name
FROM t_enrolment e
JOIN course c
ON e.course_fk = c.course_id
GROUP BY c.NAME
```
**More informat... | How to get number of students per course in sql? | [
"",
"sql",
"count",
""
] |
For example,
string is `abc123CD` need to find out a method to read only *numbers* in the string
i.e.
```
select a_postgres_function('abc123CD')
------
Result
------
123
```
---
*My try*
```
select substring('abc123CD' from '%#"^[0-9]+$#"%' for '#')
``` | Try this:
```
select (regexp_matches('abc123CD', '\d+'))[1];
```
Since `regexp_matches` returns array of text, you should access the first element by `[1]`. | As per [ntalbs's Answer](https://stackoverflow.com/a/25681789/3682599)
---
Wrap that query into a *Function*
```
create or replace function shownums(text) returns integer as
$$
select (regexp_matches($1,'\d+'))[1]::int;
$$
language sql;
``` | Return Only number from a string if it contains numbers | [
"",
"sql",
"regex",
"postgresql",
"substring",
""
] |
There are two tables. I need to select the columns from ONLY the table where the color Red is in the Color or ColorName column.
```
Columns
-------
moms: id,Name, Number, Color
dads: id,FullName, Phone, ColorName
Data
----
moms: 1, Jill, 832, Red
dads: 1, Jack, 123, Blue
-- SELECT * FROM moms,dads WHERE Color = R... | **Q: Do I need a IF or IF Exists clause?**
**A:** No.
What you need to recognize is that your query is returning a semi-Cartesian product.
The syntax you have is equivalent to:
```
SELECT m.*
, d.*
FROM moms m
CROSS
JOIN dads d
WHERE m.Color = 'Red'
OR d.ColorName = 'Red'
```
Basically, *every* row... | You can use Union:
```
select color as c from moms where color = 'Red'
union all
select colorName as c from dads where colorName = 'Red'
``` | How to select data from columns in only one table when checking two tables limited by where clause in MySQL | [
"",
"mysql",
"sql",
"select",
"multiple-tables",
""
] |
Hoping someone can help me out here.
I'm trying to have subtotals in an sql query, but not as another column.
See screenshot with the results I get and the explanation

This is the query I have so far
```
SELECT
ar.Person_Id AS 'Id',
pa.Serial_Number,
... | ```
WITH
DataSet AS (
--Your original query. For simplicity, I hard-coded the results.
SELECT '4142722'AS ID, 1 AS Serial_Number, 'Name1' AS Name, 'Activity: Description' AS DESCRIPTION, 10000.00 AS AmountExclVAT,10000.00 AS AmountInclVAT, 0 AS VATAmount, 'EUR' AS Currency_Code, NULL AS Payment_Type, NULL AS Payme... | If you're exporting to Excel, I think your best bet would be to export as is from your first query and leverage subtotaling in Excel (under the Data menu). You could automate this via a macro in Excel, or in your application code (upon clicking "Export" button). | SQL Query with multiple subtotals | [
"",
"sql",
"sql-server",
"sql-server-2008",
""
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.